LLVM 24.0.0git
SelectionDAGBuilder.cpp
Go to the documentation of this file.
1//===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SelectionDAGBuilder.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
26#include "llvm/Analysis/Loads.h"
58#include "llvm/IR/Argument.h"
59#include "llvm/IR/Attributes.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/CallingConv.h"
63#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
72#include "llvm/IR/Function.h"
74#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/InstrTypes.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsAArch64.h"
80#include "llvm/IR/IntrinsicsAMDGPU.h"
81#include "llvm/IR/IntrinsicsBPF.h"
82#include "llvm/IR/IntrinsicsWebAssembly.h"
83#include "llvm/IR/LLVMContext.h"
86#include "llvm/IR/Metadata.h"
87#include "llvm/IR/Module.h"
88#include "llvm/IR/Operator.h"
91#include "llvm/IR/Statepoint.h"
92#include "llvm/IR/Type.h"
93#include "llvm/IR/User.h"
94#include "llvm/IR/Value.h"
95#include "llvm/MC/MCAsmInfo.h"
96#include "llvm/MC/MCContext.h"
101#include "llvm/Support/Debug.h"
109#include <cstddef>
110#include <limits>
111#include <optional>
112#include <tuple>
113
114using namespace llvm;
115using namespace PatternMatch;
116using namespace SwitchCG;
117
118#define DEBUG_TYPE "isel"
119
120/// LimitFloatPrecision - Generate low-precision inline sequences for
121/// some float libcalls (6, 8 or 12 bits).
122static unsigned LimitFloatPrecision;
123
124static cl::opt<bool>
125 InsertAssertAlign("insert-assert-align", cl::init(true),
126 cl::desc("Insert the experimental `assertalign` node."),
128
130 LimitFPPrecision("limit-float-precision",
131 cl::desc("Generate low-precision inline sequences "
132 "for some float libcalls"),
134 cl::init(0));
135
137 "switch-peel-threshold", cl::Hidden, cl::init(66),
138 cl::desc("Set the case probability threshold for peeling the case from a "
139 "switch statement. A value greater than 100 will void this "
140 "optimization"));
141
142// Limit the width of DAG chains. This is important in general to prevent
143// DAG-based analysis from blowing up. For example, alias analysis and
144// load clustering may not complete in reasonable time. It is difficult to
145// recognize and avoid this situation within each individual analysis, and
146// future analyses are likely to have the same behavior. Limiting DAG width is
147// the safe approach and will be especially important with global DAGs.
148//
149// MaxParallelChains default is arbitrarily high to avoid affecting
150// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
151// sequence over this should have been converted to llvm.memcpy by the
152// frontend. It is easy to induce this behavior with .ll code such as:
153// %buffer = alloca [4096 x i8]
154// %data = load [4096 x i8]* %argPtr
155// store [4096 x i8] %data, [4096 x i8]* %buffer
156static const unsigned MaxParallelChains = 64;
157
159 const SDValue *Parts, unsigned NumParts,
160 MVT PartVT, EVT ValueVT, const Value *V,
161 SDValue InChain,
162 std::optional<CallingConv::ID> CC);
163
164/// getCopyFromParts - Create a value that contains the specified legal parts
165/// combined into the value they represent. If the parts combine to a type
166/// larger than ValueVT then AssertOp can be used to specify whether the extra
167/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
168/// (ISD::AssertSext).
169static SDValue
170getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
171 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
172 SDValue InChain,
173 std::optional<CallingConv::ID> CC = std::nullopt,
174 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
175 // Let the target assemble the parts if it wants to
177 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
178 PartVT, ValueVT, CC))
179 return Val;
180
181 if (ValueVT.isVector())
182 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
183 InChain, CC);
184
185 assert(NumParts > 0 && "No parts to assemble!");
186 SDValue Val = Parts[0];
187
188 if (NumParts > 1) {
189 // Assemble the value from multiple parts.
190 if (ValueVT.isInteger()) {
191 unsigned PartBits = PartVT.getSizeInBits();
192 unsigned ValueBits = ValueVT.getSizeInBits();
193
194 // Assemble the power of 2 part.
195 unsigned RoundParts = llvm::bit_floor(NumParts);
196 unsigned RoundBits = PartBits * RoundParts;
197 EVT RoundVT = RoundBits == ValueBits ?
198 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
199 SDValue Lo, Hi;
200
201 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
202
203 if (RoundParts > 2) {
204 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
205 InChain);
206 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
207 PartVT, HalfVT, V, InChain);
208 } else {
209 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
210 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
211 }
212
213 if (DAG.getDataLayout().isBigEndian())
214 std::swap(Lo, Hi);
215
216 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
217
218 if (RoundParts < NumParts) {
219 // Assemble the trailing non-power-of-2 part.
220 unsigned OddParts = NumParts - RoundParts;
221 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
222 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
223 OddVT, V, InChain, CC);
224
225 // Combine the round and odd parts.
226 Lo = Val;
227 if (DAG.getDataLayout().isBigEndian())
228 std::swap(Lo, Hi);
229 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
230 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
231 Hi = DAG.getNode(
232 ISD::SHL, DL, TotalVT, Hi,
233 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
234 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
235 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
236 }
237 } else if (PartVT.isFloatingPoint()) {
238 // FP split into multiple FP parts (for ppcf128)
239 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
240 "Unexpected split");
241 SDValue Lo, Hi;
242 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
243 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
244 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
245 std::swap(Lo, Hi);
246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
247 } else {
248 // FP split into integer parts (soft fp)
249 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
250 !PartVT.isVector() && "Unexpected split");
251 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
252 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
253 InChain, CC);
254 }
255 }
256
257 // There is now one part, held in Val. Correct it to match ValueVT.
258 // PartEVT is the type of the register class that holds the value.
259 // ValueVT is the type of the inline asm operation.
260 EVT PartEVT = Val.getValueType();
261
262 if (PartEVT == ValueVT)
263 return Val;
264
265 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
266 ValueVT.bitsLT(PartEVT)) {
267 // For an FP value in an integer part, we need to truncate to the right
268 // width first.
269 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
270 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
271 }
272
273 // Handle types that have the same size.
274 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
275 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
276
277 // Handle types with different sizes.
278 if (PartEVT.isInteger() && ValueVT.isInteger()) {
279 if (ValueVT.bitsLT(PartEVT)) {
280 // For a truncate, see if we have any information to
281 // indicate whether the truncated bits will always be
282 // zero or sign-extension.
283 if (AssertOp)
284 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
285 DAG.getValueType(ValueVT));
286 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
287 }
288 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
289 }
290
291 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
292 // FP_ROUND's are always exact here.
293 if (ValueVT.bitsLT(Val.getValueType())) {
294
295 SDValue NoChange =
296 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
297
298 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
299 llvm::Attribute::StrictFP)) {
300 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
301 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
302 NoChange);
303 }
304
305 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
306 }
307
308 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
309 }
310
311 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
312 // then truncating.
313 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
314 ValueVT.bitsLT(PartEVT)) {
315 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317 }
318
319 report_fatal_error("Unknown mismatch in getCopyFromParts!");
320}
321
323 const Twine &ErrMsg) {
325 if (!I)
326 return Ctx.emitError(ErrMsg);
327
328 if (const CallInst *CI = dyn_cast<CallInst>(I))
329 if (CI->isInlineAsm()) {
330 return Ctx.diagnose(DiagnosticInfoInlineAsm(
331 *CI, ErrMsg + ", possible invalid constraint for vector type"));
332 }
333
334 return Ctx.emitError(I, ErrMsg);
335}
336
337/// Emit a fatal error if the broken down registers don't match part type
338/// or count.
339static void ensureMatchedVecRegParts(unsigned NumRegs, unsigned NumParts,
340 MVT RegisterVT, MVT PartVT) {
341 if (NumRegs == NumParts && RegisterVT == PartVT)
342 return;
343
345 Twine("Part count doesn't match vector breakdown! ") + Twine(NumRegs) +
346 " registers, " + Twine(NumParts) + " parts, " + RegisterVT.getString() +
347 " RegisterVT, " + PartVT.getString() + " PartVT");
348}
349
350/// getCopyFromPartsVector - Create a value that contains the specified legal
351/// parts combined into the value they represent. If the parts combine to a
352/// type larger than ValueVT then AssertOp can be used to specify whether the
353/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
354/// ValueVT (ISD::AssertSext).
356 const SDValue *Parts, unsigned NumParts,
357 MVT PartVT, EVT ValueVT, const Value *V,
358 SDValue InChain,
359 std::optional<CallingConv::ID> CallConv) {
360 assert(ValueVT.isVector() && "Not a vector value");
361 assert(NumParts > 0 && "No parts to assemble!");
362 const bool IsABIRegCopy = CallConv.has_value();
363
365 SDValue Val = Parts[0];
366
367 // Handle a multi-element vector.
368 if (NumParts > 1) {
369 EVT IntermediateVT;
370 MVT RegisterVT;
371 unsigned NumIntermediates;
372 unsigned NumRegs;
373
374 if (IsABIRegCopy) {
375 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
376 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
377 NumIntermediates, RegisterVT);
378 } else {
379 NumRegs =
380 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
381 NumIntermediates, RegisterVT);
382 }
383
384 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
385 assert(RegisterVT.getSizeInBits() ==
386 Parts[0].getSimpleValueType().getSizeInBits() &&
387 "Part type sizes don't match!");
388
389 // Assemble the parts into intermediate operands.
390 SmallVector<SDValue, 8> Ops(NumIntermediates);
391 if (NumIntermediates == NumParts) {
392 // If the register was not expanded, truncate or copy the value,
393 // as appropriate.
394 for (unsigned i = 0; i != NumParts; ++i)
395 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
396 V, InChain, CallConv);
397 } else if (NumParts > 0) {
398 // If the intermediate type was expanded, build the intermediate
399 // operands from the parts.
400 assert(NumParts % NumIntermediates == 0 &&
401 "Must expand into a divisible number of parts!");
402 unsigned Factor = NumParts / NumIntermediates;
403 for (unsigned i = 0; i != NumIntermediates; ++i)
404 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
405 IntermediateVT, V, InChain, CallConv);
406 }
407
408 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
409 // intermediate operands.
410 EVT BuiltVectorTy =
411 IntermediateVT.isVector()
413 *DAG.getContext(), IntermediateVT.getScalarType(),
414 IntermediateVT.getVectorElementCount() * NumParts)
416 IntermediateVT.getScalarType(),
417 NumIntermediates);
418 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
420 DL, BuiltVectorTy, Ops);
421 }
422
423 // There is now one part, held in Val. Correct it to match ValueVT.
424 EVT PartEVT = Val.getValueType();
425
426 if (PartEVT == ValueVT)
427 return Val;
428
429 if (PartEVT.isVector()) {
430 // Vector/Vector bitcast.
431 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
432 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
433
434 // If the parts vector has more elements than the value vector, then we
435 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
436 // Extract the elements we want.
437 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
440 (PartEVT.getVectorElementCount().isScalable() ==
441 ValueVT.getVectorElementCount().isScalable()) &&
442 "Cannot narrow, it would be a lossy transformation");
443 PartEVT =
445 ValueVT.getVectorElementCount());
446 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
447 DAG.getVectorIdxConstant(0, DL));
448 if (PartEVT == ValueVT)
449 return Val;
450 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
451 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
452
453 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
454 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
455 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
456 }
457
458 // Promoted vector extract
459 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
460 }
461
462 // Trivial bitcast if the types are the same size and the destination
463 // vector type is legal.
464 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
465 TLI.isTypeLegal(ValueVT))
466 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
467
468 if (ValueVT.getVectorNumElements() != 1) {
469 // Certain ABIs require that vectors are passed as integers. For vectors
470 // are the same size, this is an obvious bitcast.
471 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
472 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
473 } else if (ValueVT.bitsLT(PartEVT)) {
474 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
475 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
476 // Drop the extra bits.
477 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
478 return DAG.getBitcast(ValueVT, Val);
479 }
480
482 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
483 return DAG.getUNDEF(ValueVT);
484 }
485
486 // Handle cases such as i8 -> <1 x i1>
487 EVT ValueSVT = ValueVT.getVectorElementType();
488 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
489 unsigned ValueSize = ValueSVT.getSizeInBits();
490 if (ValueSize == PartEVT.getSizeInBits()) {
491 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
492 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
493 // It's possible a scalar floating point type gets softened to integer and
494 // then promoted to a larger integer. If PartEVT is the larger integer
495 // we need to truncate it and then bitcast to the FP type.
496 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
497 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
498 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
499 Val = DAG.getBitcast(ValueSVT, Val);
500 } else {
501 Val = ValueVT.isFloatingPoint()
502 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
503 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
504 }
505 }
506
507 return DAG.getBuildVector(ValueVT, DL, Val);
508}
509
510static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
511 SDValue Val, SDValue *Parts, unsigned NumParts,
512 MVT PartVT, const Value *V,
513 std::optional<CallingConv::ID> CallConv);
514
515/// getCopyToParts - Create a series of nodes that contain the specified value
516/// split into legal parts. If the parts contain more bits than Val, then, for
517/// integers, ExtendKind can be used to specify how to generate the extra bits.
518static void
520 unsigned NumParts, MVT PartVT, const Value *V,
521 std::optional<CallingConv::ID> CallConv = std::nullopt,
523 // Let the target split the parts if it wants to
525 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
526 CallConv))
527 return;
528 EVT ValueVT = Val.getValueType();
529
530 // Handle the vector case separately.
531 if (ValueVT.isVector())
532 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
533 CallConv);
534
535 unsigned OrigNumParts = NumParts;
537 "Copying to an illegal type!");
538
539 if (NumParts == 0)
540 return;
541
542 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
543 EVT PartEVT = PartVT;
544 if (PartEVT == ValueVT) {
545 assert(NumParts == 1 && "No-op copy with multiple parts!");
546 Parts[0] = Val;
547 return;
548 }
549
550 unsigned PartBits = PartVT.getSizeInBits();
551 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
552 // If the parts cover more bits than the value has, promote the value.
553 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
554 assert(NumParts == 1 && "Do not know what to promote to!");
555 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
556 } else {
557 if (ValueVT.isFloatingPoint()) {
558 // FP values need to be bitcast, then extended if they are being put
559 // into a larger container.
560 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
561 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
562 }
563 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
564 ValueVT.isInteger() &&
565 "Unknown mismatch!");
566 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
567 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
568 if (PartVT == MVT::x86mmx)
569 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
570 }
571 } else if (PartBits == ValueVT.getSizeInBits()) {
572 // Different types of the same size.
573 assert(NumParts == 1 && PartEVT != ValueVT);
574 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
575 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
576 // If the parts cover less bits than value has, truncate the value.
577 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
578 ValueVT.isInteger() &&
579 "Unknown mismatch!");
580 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
581 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
582 if (PartVT == MVT::x86mmx)
583 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
584 }
585
586 // The value may have changed - recompute ValueVT.
587 ValueVT = Val.getValueType();
588 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
589 "Failed to tile the value with PartVT!");
590
591 if (NumParts == 1) {
592 if (PartEVT != ValueVT) {
594 "scalar-to-vector conversion failed");
595 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
596 }
597
598 Parts[0] = Val;
599 return;
600 }
601
602 // Expand the value into multiple parts.
603 if (NumParts & (NumParts - 1)) {
604 // The number of parts is not a power of 2. Split off and copy the tail.
605 assert(PartVT.isInteger() && ValueVT.isInteger() &&
606 "Do not know what to expand to!");
607 unsigned RoundParts = llvm::bit_floor(NumParts);
608 unsigned RoundBits = RoundParts * PartBits;
609 unsigned OddParts = NumParts - RoundParts;
610 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
611 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
612
613 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
614 CallConv);
615
616 if (DAG.getDataLayout().isBigEndian())
617 // The odd parts were reversed by getCopyToParts - unreverse them.
618 std::reverse(Parts + RoundParts, Parts + NumParts);
619
620 NumParts = RoundParts;
621 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
622 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
623 }
624
625 // The number of parts is a power of 2. Repeatedly bisect the value using
626 // EXTRACT_ELEMENT.
627 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
629 ValueVT.getSizeInBits()),
630 Val);
631
632 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
633 for (unsigned i = 0; i < NumParts; i += StepSize) {
634 unsigned ThisBits = StepSize * PartBits / 2;
635 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
636 SDValue &Part0 = Parts[i];
637 SDValue &Part1 = Parts[i+StepSize/2];
638
639 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
640 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
641 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
642 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
643
644 if (ThisBits == PartBits && ThisVT != PartVT) {
645 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
646 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
647 }
648 }
649 }
650
651 if (DAG.getDataLayout().isBigEndian())
652 std::reverse(Parts, Parts + OrigNumParts);
653}
654
656 const SDLoc &DL, EVT PartVT) {
657 if (!PartVT.isVector())
658 return SDValue();
659
660 EVT ValueVT = Val.getValueType();
661 EVT PartEVT = PartVT.getVectorElementType();
662 EVT ValueEVT = ValueVT.getVectorElementType();
663 ElementCount PartNumElts = PartVT.getVectorElementCount();
664 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
665
666 // We only support widening vectors with equivalent element types and
667 // fixed/scalable properties. If a target needs to widen a fixed-length type
668 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
669 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
670 PartNumElts.isScalable() != ValueNumElts.isScalable())
671 return SDValue();
672
673 // Have a try for bf16 because some targets share its ABI with fp16.
674 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
676 "Cannot widen to illegal type");
677 Val = DAG.getNode(
679 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
680 } else if (PartEVT != ValueEVT) {
681 return SDValue();
682 }
683
684 // Widening a scalable vector to another scalable vector is done by inserting
685 // the vector into a larger undef one.
686 if (PartNumElts.isScalable())
687 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
688 Val, DAG.getVectorIdxConstant(0, DL));
689
690 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
691 // undef elements.
693 DAG.ExtractVectorElements(Val, Ops);
694 SDValue EltUndef = DAG.getUNDEF(PartEVT);
695 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
696
697 // FIXME: Use CONCAT for 2x -> 4x.
698 return DAG.getBuildVector(PartVT, DL, Ops);
699}
700
701/// getCopyToPartsVector - Create a series of nodes that contain the specified
702/// value split into legal parts.
703static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
704 SDValue Val, SDValue *Parts, unsigned NumParts,
705 MVT PartVT, const Value *V,
706 std::optional<CallingConv::ID> CallConv) {
707 EVT ValueVT = Val.getValueType();
708 assert(ValueVT.isVector() && "Not a vector");
710 const bool IsABIRegCopy = CallConv.has_value();
711
712 if (NumParts == 1) {
713 EVT PartEVT = PartVT;
714 if (PartEVT == ValueVT) {
715 // Nothing to do.
716 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
717 // Bitconvert vector->vector case.
718 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
719 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
720 Val = Widened;
721 } else if (PartVT.isVector() &&
723 ValueVT.getVectorElementType()) &&
724 PartEVT.getVectorElementCount() ==
725 ValueVT.getVectorElementCount()) {
726
727 // Promoted vector extract
728 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
729 } else if (PartEVT.isVector() &&
730 PartEVT.getVectorElementType() !=
731 ValueVT.getVectorElementType() &&
732 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
734 // Combination of widening and promotion.
735 EVT WidenVT =
737 PartVT.getVectorElementCount());
738 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
739 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
740 } else {
741 // Don't extract an integer from a float vector. This can happen if the
742 // FP type gets softened to integer and then promoted. The promotion
743 // prevents it from being picked up by the earlier bitcast case.
744 if (ValueVT.getVectorElementCount().isScalar() &&
745 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
746 // If we reach this condition and PartVT is FP, this means that
747 // ValueVT is also FP and both have a different size, otherwise we
748 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
749 // would be invalid since that would mean the smaller FP type has to
750 // be extended to the larger one.
751 if (PartVT.isFloatingPoint()) {
752 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
753 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
754 } else
755 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
756 DAG.getVectorIdxConstant(0, DL));
757 } else {
758 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
759 assert(PartVT.getFixedSizeInBits() > ValueSize &&
760 "lossy conversion of vector to scalar type");
761 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
762 Val = DAG.getBitcast(IntermediateType, Val);
763 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
764 }
765 }
766
767 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
768 Parts[0] = Val;
769 return;
770 }
771
772 // Handle a multi-element vector.
773 EVT IntermediateVT;
774 MVT RegisterVT;
775 unsigned NumIntermediates;
776 unsigned NumRegs;
777 if (IsABIRegCopy) {
778 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
779 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
780 RegisterVT);
781 } else {
782 NumRegs =
783 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
784 NumIntermediates, RegisterVT);
785 }
786
787 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
788 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
789 "Mixing scalable and fixed vectors when copying in parts");
790
791 std::optional<ElementCount> DestEltCnt;
792
793 if (IntermediateVT.isVector())
794 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
795 else
796 DestEltCnt = ElementCount::getFixed(NumIntermediates);
797
798 EVT BuiltVectorTy = EVT::getVectorVT(
799 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
800
801 if (ValueVT == BuiltVectorTy) {
802 // Nothing to do.
803 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
804 // Bitconvert vector->vector case.
805 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
806 } else {
807 if (BuiltVectorTy.getVectorElementType().bitsGT(
808 ValueVT.getVectorElementType())) {
809 // Integer promotion.
810 ValueVT = EVT::getVectorVT(*DAG.getContext(),
811 BuiltVectorTy.getVectorElementType(),
812 ValueVT.getVectorElementCount());
813 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
814 }
815
816 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
817 Val = Widened;
818 }
819 }
820
821 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
822
823 // Split the vector into intermediate operands.
824 SmallVector<SDValue, 8> Ops(NumIntermediates);
825 for (unsigned i = 0; i != NumIntermediates; ++i) {
826 if (IntermediateVT.isVector()) {
827 // This does something sensible for scalable vectors - see the
828 // definition of EXTRACT_SUBVECTOR for further details.
829 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
830 Ops[i] =
831 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
832 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
833 } else {
834 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
835 DAG.getVectorIdxConstant(i, DL));
836 }
837 }
838
839 // Split the intermediate operands into legal parts.
840 if (NumParts == NumIntermediates) {
841 // If the register was not expanded, promote or copy the value,
842 // as appropriate.
843 for (unsigned i = 0; i != NumParts; ++i)
844 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
845 } else if (NumParts > 0) {
846 // If the intermediate type was expanded, split each the value into
847 // legal parts.
848 assert(NumIntermediates != 0 && "division by zero");
849 assert(NumParts % NumIntermediates == 0 &&
850 "Must expand into a divisible number of parts!");
851 unsigned Factor = NumParts / NumIntermediates;
852 for (unsigned i = 0; i != NumIntermediates; ++i)
853 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
854 CallConv);
855 }
856}
857
858static void failForInvalidBundles(const CallBase &I, StringRef Name,
859 ArrayRef<uint32_t> AllowedBundles) {
860 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
861 ListSeparator LS;
862 std::string Error;
864 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
865 OperandBundleUse U = I.getOperandBundleAt(i);
866 if (!is_contained(AllowedBundles, U.getTagID()))
867 OS << LS << U.getTagName();
868 }
870 Twine("cannot lower ", Name)
871 .concat(Twine(" with arbitrary operand bundles: ", Error)));
872 }
873}
874
876 EVT valuevt, std::optional<CallingConv::ID> CC)
877 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
878 RegCount(1, regs.size()), CallConv(CC) {}
879
881 const DataLayout &DL, Register Reg, Type *Ty,
882 std::optional<CallingConv::ID> CC) {
884
885 CallConv = CC;
886
887 for (EVT ValueVT : ValueVTs) {
888 unsigned NumRegs =
890 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
891 : TLI.getNumRegisters(Context, ValueVT);
892 MVT RegisterVT =
894 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
895 : TLI.getRegisterType(Context, ValueVT);
896 for (unsigned i = 0; i != NumRegs; ++i)
897 Regs.push_back(Reg + i);
898 RegVTs.push_back(RegisterVT);
899 RegCount.push_back(NumRegs);
900 Reg = Reg.id() + NumRegs;
901 }
902}
903
905 FunctionLoweringInfo &FuncInfo,
906 const SDLoc &dl, SDValue &Chain,
907 SDValue *Glue, const Value *V) const {
908 // A Value with type {} or [0 x %t] needs no registers.
909 if (ValueVTs.empty())
910 return SDValue();
911
913
914 // Assemble the legal parts into the final values.
917 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
918 // Copy the legal parts from the registers.
919 EVT ValueVT = ValueVTs[Value];
920 unsigned NumRegs = RegCount[Value];
921 MVT RegisterVT = isABIMangled()
922 ? TLI.getRegisterTypeForCallingConv(
923 *DAG.getContext(), *CallConv, RegVTs[Value])
924 : RegVTs[Value];
925
926 Parts.resize(NumRegs);
927 for (unsigned i = 0; i != NumRegs; ++i) {
928 SDValue P;
929 if (!Glue) {
930 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
931 } else {
932 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
933 *Glue = P.getValue(2);
934 }
935
936 Chain = P.getValue(1);
937 Parts[i] = P;
938
939 // If the source register was virtual and if we know something about it,
940 // add an assert node.
941 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
942 continue;
943
945 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
946 if (!LOI)
947 continue;
948
949 unsigned RegSize = RegisterVT.getScalarSizeInBits();
950 unsigned NumSignBits = LOI->NumSignBits;
951 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
952
953 if (NumZeroBits == RegSize) {
954 // The current value is a zero.
955 // Explicitly express that as it would be easier for
956 // optimizations to kick in.
957 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
958 continue;
959 }
960
961 // FIXME: We capture more information than the dag can represent. For
962 // now, just use the tightest assertzext/assertsext possible.
963 bool isSExt;
964 EVT FromVT(MVT::Other);
965 if (NumZeroBits) {
966 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
967 isSExt = false;
968 } else if (NumSignBits > 1) {
969 FromVT =
970 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
971 isSExt = true;
972 } else {
973 continue;
974 }
975 // Add an assertion node.
976 assert(FromVT != MVT::Other);
977 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
978 RegisterVT, P, DAG.getValueType(FromVT));
979 }
980
981 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
982 RegisterVT, ValueVT, V, Chain, CallConv);
983 Part += NumRegs;
984 Parts.clear();
985 }
986
987 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
988}
989
991 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
992 const Value *V,
993 ISD::NodeType PreferredExtendType) const {
995 ISD::NodeType ExtendKind = PreferredExtendType;
996
997 // Get the list of the values's legal parts.
998 unsigned NumRegs = Regs.size();
999 SmallVector<SDValue, 8> Parts(NumRegs);
1000 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
1001 unsigned NumParts = RegCount[Value];
1002
1003 MVT RegisterVT = isABIMangled()
1004 ? TLI.getRegisterTypeForCallingConv(
1005 *DAG.getContext(), *CallConv, RegVTs[Value])
1006 : RegVTs[Value];
1007
1009 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
1011
1012 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1013 NumParts, RegisterVT, V, CallConv, ExtendKind);
1014 Part += NumParts;
1015 }
1016
1017 // Copy the parts into the registers.
1018 SmallVector<SDValue, 8> Chains(NumRegs);
1019 for (unsigned i = 0; i != NumRegs; ++i) {
1020 SDValue Part;
1021 if (!Glue) {
1022 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1023 } else {
1024 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1025 *Glue = Part.getValue(1);
1026 }
1027
1028 Chains[i] = Part.getValue(0);
1029 }
1030
1031 if (NumRegs == 1 || Glue)
1032 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1033 // flagged to it. That is the CopyToReg nodes and the user are considered
1034 // a single scheduling unit. If we create a TokenFactor and return it as
1035 // chain, then the TokenFactor is both a predecessor (operand) of the
1036 // user as well as a successor (the TF operands are flagged to the user).
1037 // c1, f1 = CopyToReg
1038 // c2, f2 = CopyToReg
1039 // c3 = TokenFactor c1, c2
1040 // ...
1041 // = op c3, ..., f2
1042 Chain = Chains[NumRegs-1];
1043 else
1044 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1045}
1046
1048 unsigned MatchingIdx, const SDLoc &dl,
1049 SelectionDAG &DAG,
1050 std::vector<SDValue> &Ops) const {
1052
1053 InlineAsm::Flag Flag(Code, Regs.size());
1054 if (HasMatching)
1055 Flag.setMatchingOp(MatchingIdx);
1056 else if (!Regs.empty() && Regs.front().isVirtual()) {
1057 // Put the register class of the virtual registers in the flag word. That
1058 // way, later passes can recompute register class constraints for inline
1059 // assembly as well as normal instructions.
1060 // Don't do this for tied operands that can use the regclass information
1061 // from the def.
1063 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1064 Flag.setRegClass(RC->getID());
1065 }
1066
1067 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1068 Ops.push_back(Res);
1069
1070 if (Code == InlineAsm::Kind::Clobber) {
1071 // Clobbers should always have a 1:1 mapping with registers, and may
1072 // reference registers that have illegal (e.g. vector) types. Hence, we
1073 // shouldn't try to apply any sort of splitting logic to them.
1074 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1075 "No 1:1 mapping from clobbers to regs?");
1076 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1077 (void)SP;
1078 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1079 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1080 assert(
1081 (Regs[I] != SP ||
1083 "If we clobbered the stack pointer, MFI should know about it.");
1084 }
1085 return;
1086 }
1087
1088 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1089 MVT RegisterVT = RegVTs[Value];
1090 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1091 RegisterVT);
1092 for (unsigned i = 0; i != NumRegs; ++i) {
1093 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1094 Register TheReg = Regs[Reg++];
1095 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1096 }
1097 }
1098}
1099
1103 unsigned I = 0;
1104 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1105 unsigned RegCount = std::get<0>(CountAndVT);
1106 MVT RegisterVT = std::get<1>(CountAndVT);
1107 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1108 for (unsigned E = I + RegCount; I != E; ++I)
1109 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1110 }
1111 return OutVec;
1112}
1113
1115 AssumptionCache *ac, const TargetLibraryInfo *li,
1116 const TargetTransformInfo &TTI) {
1117 BatchAA = aa;
1118 AC = ac;
1119 GFI = gfi;
1120 LibInfo = li;
1121 Context = DAG.getContext();
1122 LPadToCallSiteMap.clear();
1123 CallBrOutputs.clear();
1124 this->TTI = &TTI;
1125 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1126 CanDescribeGlobalAddressInLocationList =
1127 canDescribeGlobalAddressInLocationList(DAG.getMachineFunction());
1128}
1129
1131 NodeMap.clear();
1132 UnusedArgNodeMap.clear();
1133 PendingLoads.clear();
1134 PendingExports.clear();
1135 PendingConstrainedFP.clear();
1136 PendingConstrainedFPStrict.clear();
1137 CurInst = nullptr;
1138 HasTailCall = false;
1139 SDNodeOrder = LowestSDNodeOrder;
1140 StatepointLowering.clear();
1141}
1142
1144 DanglingDebugInfoMap.clear();
1145}
1146
1147// Update DAG root to include dependencies on Pending chains.
1148SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1149 SDValue Root = DAG.getRoot();
1150
1151 if (Pending.empty())
1152 return Root;
1153
1154 // Add current root to PendingChains, unless we already indirectly
1155 // depend on it.
1156 if (Root.getOpcode() != ISD::EntryToken) {
1157 unsigned i = 0, e = Pending.size();
1158 for (; i != e; ++i) {
1159 assert(Pending[i].getNode()->getNumOperands() > 1);
1160 if (Pending[i].getNode()->getOperand(0) == Root)
1161 break; // Don't add the root if we already indirectly depend on it.
1162 }
1163
1164 if (i == e)
1165 Pending.push_back(Root);
1166 }
1167
1168 if (Pending.size() == 1)
1169 Root = Pending[0];
1170 else
1171 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1172
1173 DAG.setRoot(Root);
1174 Pending.clear();
1175 return Root;
1176}
1177
1181
1183 // If the new exception behavior differs from that of the pending
1184 // ones, chain up them and update the root.
1185 switch (EB) {
1188 // Floating-point exceptions produced by such operations are not intended
1189 // to be observed, so the sequence of these operations does not need to be
1190 // preserved.
1191 //
1192 // They however must not be mixed with the instructions that have strict
1193 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1194 // 'ebStrict' operations could distort the observed exception behavior.
1195 if (!PendingConstrainedFPStrict.empty()) {
1196 assert(PendingConstrainedFP.empty());
1197 updateRoot(PendingConstrainedFPStrict);
1198 }
1199 break;
1201 // Floating-point exception produced by these operations may be observed, so
1202 // they must be correctly chained. If trapping on FP exceptions is
1203 // disabled, the exceptions can be observed only by functions that read
1204 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1205 // the order of operations is not significant between barriers.
1206 //
1207 // If trapping is enabled, each operation becomes an implicit observation
1208 // point, so the operations must be sequenced according their original
1209 // source order.
1210 if (!PendingConstrainedFP.empty()) {
1211 assert(PendingConstrainedFPStrict.empty());
1212 updateRoot(PendingConstrainedFP);
1213 }
1214 // TODO: Add support for trapping-enabled scenarios.
1215 }
1216 return DAG.getRoot();
1217}
1218
1220 // Chain up all pending constrained intrinsics together with all
1221 // pending loads, by simply appending them to PendingLoads and
1222 // then calling getMemoryRoot().
1223 PendingLoads.reserve(PendingLoads.size() +
1224 PendingConstrainedFP.size() +
1225 PendingConstrainedFPStrict.size());
1226 PendingLoads.append(PendingConstrainedFP.begin(),
1227 PendingConstrainedFP.end());
1228 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1229 PendingConstrainedFPStrict.end());
1230 PendingConstrainedFP.clear();
1231 PendingConstrainedFPStrict.clear();
1232 return getMemoryRoot();
1233}
1234
1236 // We need to emit pending fpexcept.strict constrained intrinsics,
1237 // so append them to the PendingExports list.
1238 PendingExports.append(PendingConstrainedFPStrict.begin(),
1239 PendingConstrainedFPStrict.end());
1240 PendingConstrainedFPStrict.clear();
1241 return updateRoot(PendingExports);
1242}
1243
1245 DILocalVariable *Variable,
1247 DebugLoc DL) {
1248 assert(Variable && "Missing variable");
1249
1250 // Check if address has undef value.
1251 if (!Address || isa<UndefValue>(Address) ||
1252 (Address->use_empty() && !isa<Argument>(Address))) {
1253 LLVM_DEBUG(
1254 dbgs()
1255 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1256 return;
1257 }
1258
1259 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1260
1261 SDValue &N = NodeMap[Address];
1262 if (!N.getNode() && isa<Argument>(Address))
1263 // Check unused arguments map.
1264 N = UnusedArgNodeMap[Address];
1265 SDDbgValue *SDV;
1266 if (N.getNode()) {
1267 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1268 Address = BCI->getOperand(0);
1269 // Parameters are handled specially.
1270 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1271 if (IsParameter && FINode) {
1272 // Byval parameter. We have a frame index at this point.
1273 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1274 /*IsIndirect*/ true, DL, SDNodeOrder);
1275 } else if (isa<Argument>(Address)) {
1276 // Address is an argument, so try to emit its dbg value using
1277 // virtual register info from the FuncInfo.ValueMap.
1278 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1279 FuncArgumentDbgValueKind::Declare, N);
1280 return;
1281 } else {
1282 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1283 true, DL, SDNodeOrder);
1284 }
1285 DAG.AddDbgValue(SDV, IsParameter);
1286 } else {
1287 // If Address is an argument then try to emit its dbg value using
1288 // virtual register info from the FuncInfo.ValueMap.
1289 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1290 FuncArgumentDbgValueKind::Declare, N)) {
1291 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1292 << " (could not emit func-arg dbg_value)\n");
1293 }
1294 }
1295}
1296
1298 // Add SDDbgValue nodes for any var locs here. Do so before updating
1299 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1300 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1301 // Add SDDbgValue nodes for any var locs here. Do so before updating
1302 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1303 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1304 It != End; ++It) {
1305 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1306 dropDanglingDebugInfo(Var, It->Expr);
1307 if (It->Values.isKillLocation(It->Expr)) {
1308 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1309 continue;
1310 }
1311 SmallVector<Value *> Values(It->Values.location_ops());
1312 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1313 It->Values.hasArgList())) {
1314 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1316 FnVarLocs->getDILocalVariable(It->VariableID),
1317 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1318 }
1319 }
1320 }
1321
1322 // We must skip DbgVariableRecords if they've already been processed above as
1323 // we have just emitted the debug values resulting from assignment tracking
1324 // analysis, making any existing DbgVariableRecords redundant (and probably
1325 // less correct). We still need to process DbgLabelRecords. This does sink
1326 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1327 // be important as it does so deterministcally and ordering between
1328 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1329 // printing).
1330 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1331 // Is there is any debug-info attached to this instruction, in the form of
1332 // DbgRecord non-instruction debug-info records.
1333 for (DbgRecord &DR : I.getDbgRecordRange()) {
1334 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1335 assert(DLR->getLabel() && "Missing label");
1336 SDDbgLabel *SDV =
1337 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1338 DAG.AddDbgLabel(SDV);
1339 continue;
1340 }
1341
1342 if (SkipDbgVariableRecords)
1343 continue;
1345 DILocalVariable *Variable = DVR.getVariable();
1348
1350 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1351 continue;
1352 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1353 << "\n");
1355 DVR.getDebugLoc());
1356 continue;
1357 }
1358
1359 // A DbgVariableRecord with no locations is a kill location.
1361 if (Values.empty()) {
1363 SDNodeOrder);
1364 continue;
1365 }
1366
1367 // A DbgVariableRecord with an undef or absent location is also a kill
1368 // location.
1369 if (llvm::any_of(Values,
1370 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1372 SDNodeOrder);
1373 continue;
1374 }
1375
1376 bool IsVariadic = DVR.hasArgList();
1377 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1378 SDNodeOrder, IsVariadic)) {
1379 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1380 DVR.getDebugLoc(), SDNodeOrder);
1381 }
1382 }
1383}
1384
1386 visitDbgInfo(I);
1387
1388 // Set up outgoing PHI node register values before emitting the terminator.
1389 if (I.isTerminator()) {
1390 HandlePHINodesInSuccessorBlocks(I.getParent());
1391 }
1392
1393 ++SDNodeOrder;
1394 CurInst = &I;
1395
1396 // Set inserted listener only if required.
1397 bool NodeInserted = false;
1398 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1399 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1400 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1401 if (PCSectionsMD || MMRA) {
1402 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1403 DAG, [&](SDNode *) { NodeInserted = true; });
1404 }
1405
1406 visit(I.getOpcode(), I);
1407
1408 if (!I.isTerminator() && !HasTailCall &&
1409 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1411
1412 // Handle metadata.
1413 if (PCSectionsMD || MMRA) {
1414 auto It = NodeMap.find(&I);
1415 if (It != NodeMap.end()) {
1416 if (PCSectionsMD)
1417 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1418 if (MMRA)
1419 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1420 } else if (NodeInserted) {
1421 // This should not happen; if it does, don't let it go unnoticed so we can
1422 // fix it. Relevant visit*() function is probably missing a setValue().
1423 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1424 << I.getModule()->getName() << "]\n";
1425 LLVM_DEBUG(I.dump());
1426 assert(false);
1427 }
1428 }
1429
1430 CurInst = nullptr;
1431}
1432
1433void SelectionDAGBuilder::visitPHI(const PHINode &) {
1434 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1435}
1436
1437void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1438 // Note: this doesn't use InstVisitor, because it has to work with
1439 // ConstantExpr's in addition to instructions.
1440 switch (Opcode) {
1441 default: llvm_unreachable("Unknown instruction type encountered!");
1442 // Build the switch statement using the Instruction.def file.
1443#define HANDLE_INST(NUM, OPCODE, CLASS) \
1444 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1445#include "llvm/IR/Instruction.def"
1446 }
1447}
1448
1450 DILocalVariable *Variable,
1451 DebugLoc DL, unsigned Order,
1454 // For variadic dbg_values we will now insert poison.
1455 // FIXME: We can potentially recover these!
1457 for (const Value *V : Values) {
1458 auto *Poison = PoisonValue::get(V->getType());
1459 Locs.push_back(SDDbgOperand::fromConst(Poison));
1460 }
1461 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1462 /*IsIndirect=*/false, DL, Order,
1463 /*IsVariadic=*/true);
1464 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1465 return true;
1466}
1467
1469 DILocalVariable *Var,
1470 DIExpression *Expr,
1471 bool IsVariadic, DebugLoc DL,
1472 unsigned Order) {
1473 if (IsVariadic) {
1474 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1475 return;
1476 }
1477 // TODO: Dangling debug info will eventually either be resolved or produce
1478 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1479 // between the original dbg.value location and its resolved DBG_VALUE,
1480 // which we should ideally fill with an extra poison DBG_VALUE.
1481 assert(Values.size() == 1);
1482 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1483}
1484
1486 const DIExpression *Expr) {
1487 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1488 DIVariable *DanglingVariable = DDI.getVariable();
1489 DIExpression *DanglingExpr = DDI.getExpression();
1490 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1491 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1492 << printDDI(nullptr, DDI) << "\n");
1493 return true;
1494 }
1495 return false;
1496 };
1497
1498 for (auto &DDIMI : DanglingDebugInfoMap) {
1499 DanglingDebugInfoVector &DDIV = DDIMI.second;
1500
1501 // If debug info is to be dropped, run it through final checks to see
1502 // whether it can be salvaged.
1503 for (auto &DDI : DDIV)
1504 if (isMatchingDbgValue(DDI))
1505 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1506
1507 erase_if(DDIV, isMatchingDbgValue);
1508 }
1509}
1510
1511// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1512// generate the debug data structures now that we've seen its definition.
1514 SDValue Val) {
1515 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1516 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1517 return;
1518
1519 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1520 for (auto &DDI : DDIV) {
1521 DebugLoc DL = DDI.getDebugLoc();
1522 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1523 DILocalVariable *Variable = DDI.getVariable();
1524 DIExpression *Expr = DDI.getExpression();
1525 assert(Variable->isValidLocationForIntrinsic(DL) &&
1526 "Expected inlined-at fields to agree");
1527 SDDbgValue *SDV;
1528 if (Val.getNode()) {
1529 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1530 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1531 // we couldn't resolve it directly when examining the DbgValue intrinsic
1532 // in the first place we should not be more successful here). Unless we
1533 // have some test case that prove this to be correct we should avoid
1534 // calling EmitFuncArgumentDbgValue here.
1535 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1536 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1537 FuncArgumentDbgValueKind::Value, Val)) {
1538 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1539 << printDDI(V, DDI) << "\n");
1540 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1541 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1542 // inserted after the definition of Val when emitting the instructions
1543 // after ISel. An alternative could be to teach
1544 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1545 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1546 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1547 << ValSDNodeOrder << "\n");
1548 SDV = getDbgValue(Val, Variable, Expr, DL,
1549 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1550 DAG.AddDbgValue(SDV, false);
1551 } else
1552 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1553 << printDDI(V, DDI)
1554 << " in EmitFuncArgumentDbgValue\n");
1555 } else {
1556 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1557 << "\n");
1558 auto Poison = PoisonValue::get(V->getType());
1559 auto SDV =
1560 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1561 DAG.AddDbgValue(SDV, false);
1562 }
1563 }
1564 DDIV.clear();
1565}
1566
1567/// If \p V is the address of a describable global, possibly displaced by a
1568/// constant, return the global and fold the displacement into location operand
1569/// \p OpIdx of \p Expr. The displacement rides along in the expression rather
1570/// than in the operand, so that it survives into a DBG_INSTR_REF.
1571static const GlobalValue *
1572getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx,
1573 const MachineFunction &MF) {
1574 const auto *C = dyn_cast<Constant>(V);
1575 if (!C)
1576 return nullptr;
1577 int64_t Offset;
1579 if (GV && Offset) {
1582 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx, /*StackValue=*/false);
1583 }
1584 return GV;
1585}
1586
1588 DanglingDebugInfo &DDI) {
1589 // TODO: For the variadic implementation, instead of only checking the fail
1590 // state of `handleDebugValue`, we need know specifically which values were
1591 // invalid, so that we attempt to salvage only those values when processing
1592 // a DIArgList.
1593 const Value *OrigV = V;
1594 DILocalVariable *Var = DDI.getVariable();
1595 DIExpression *Expr = DDI.getExpression();
1596 DebugLoc DL = DDI.getDebugLoc();
1597 unsigned SDOrder = DDI.getSDNodeOrder();
1598
1599 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1600 // that DW_OP_stack_value is desired.
1601 bool StackValue = true;
1602
1603 // handleDebugValue holds out for a register with the address of a global
1604 // that a location list could not name. With no such register forthcoming,
1605 // naming the global still beats dropping the location.
1606 auto HandleGlobalAddress = [&] {
1607 DIExpression *GVExpr = Expr;
1608 const GlobalValue *GV =
1609 getGlobalAddressDbgOperand(V, GVExpr, 0, DAG.getMachineFunction());
1610 if (!GV)
1611 return false;
1612 SDDbgValue *SDV = DAG.getDbgValueList(
1613 Var, GVExpr, SDDbgOperand::fromGlobalAddr(GV), /*Dependencies=*/{},
1614 /*IsIndirect=*/false, DL, SDOrder, /*IsVariadic=*/false);
1615 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1616 return true;
1617 };
1618
1619 // Can this Value can be encoded without any further work?
1620 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1621 HandleGlobalAddress())
1622 return;
1623
1624 // Attempt to salvage back through as many instructions as possible. Bail if
1625 // a non-instruction is seen, such as a constant expression or global
1626 // variable. FIXME: Further work could recover those too.
1627 while (isa<Instruction>(V)) {
1628 const Instruction &VAsInst = *cast<const Instruction>(V);
1629 // Temporary "0", awaiting real implementation.
1631 SmallVector<Value *, 4> AdditionalValues;
1632 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1633 Expr->getNumLocationOperands(), Ops,
1634 AdditionalValues);
1635 // If we cannot salvage any further, and haven't yet found a suitable debug
1636 // expression, bail out.
1637 if (!V)
1638 break;
1639
1640 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1641 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1642 // here for variadic dbg_values, remove that condition.
1643 if (!AdditionalValues.empty())
1644 break;
1645
1646 // New value and expr now represent this debuginfo.
1648
1649 // Some kind of simplification occurred: check whether the operand of the
1650 // salvaged debug expression can be encoded in this DAG.
1651 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1652 HandleGlobalAddress()) {
1653 LLVM_DEBUG(
1654 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1655 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1656 return;
1657 }
1658 }
1659
1660 // This was the final opportunity to salvage this debug information, and it
1661 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1662 // any earlier variable location.
1663 assert(OrigV && "V shouldn't be null");
1664 auto *Poison = PoisonValue::get(OrigV->getType());
1665 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDOrder);
1666 DAG.AddDbgValue(SDV, false);
1667 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1668 << printDDI(OrigV, DDI) << "\n");
1669}
1670
1672 DIExpression *Expr,
1673 DebugLoc DbgLoc,
1674 unsigned Order) {
1675 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1678 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1679 /*IsVariadic*/ false);
1680}
1681
1683 DILocalVariable *Var,
1684 DIExpression *Expr, DebugLoc DbgLoc,
1685 unsigned Order, bool IsVariadic) {
1686 if (Values.empty())
1687 return true;
1688
1689 // Filter EntryValue locations out early.
1690 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1691 return true;
1692
1693 SmallVector<SDDbgOperand> LocationOps;
1694 SmallVector<SDNode *> Dependencies;
1695 for (const auto &[OpIdx, V] : enumerate(Values)) {
1696 // Constant value.
1699 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1700 continue;
1701 }
1702
1703 // Look through IntToPtr constants.
1704 if (auto *CE = dyn_cast<ConstantExpr>(V))
1705 if (CE->getOpcode() == Instruction::IntToPtr) {
1706 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1707 continue;
1708 }
1709
1710 // The address of a global is a link-time constant, and so is a constant
1711 // displacement from one. A global whose address cannot be described this
1712 // way falls through to be described by whatever materializes it instead.
1713 // So does one that a location list could not name, should the variable
1714 // need one; salvageUnresolvedDbgValue names it if nothing materializes it.
1715 if (CanDescribeGlobalAddressInLocationList)
1717 V, Expr, OpIdx, DAG.getMachineFunction())) {
1719 continue;
1720 }
1721
1722 // If the Value is a frame index, we can create a FrameIndex debug value
1723 // without relying on the DAG at all.
1724 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1725 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1726 if (SI != FuncInfo.StaticAllocaMap.end()) {
1727 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1728 continue;
1729 }
1730 }
1731
1732 // Do not use getValue() in here; we don't want to generate code at
1733 // this point if it hasn't been done yet.
1734 SDValue N = NodeMap[V];
1735 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1736 N = UnusedArgNodeMap[V];
1737
1738 if (N.getNode()) {
1739 // Only emit func arg dbg value for non-variadic dbg.values for now.
1740 if (!IsVariadic &&
1741 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1742 FuncArgumentDbgValueKind::Value, N))
1743 return true;
1744 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1745 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1746 // describe stack slot locations.
1747 //
1748 // Consider "int x = 0; int *px = &x;". There are two kinds of
1749 // interesting debug values here after optimization:
1750 //
1751 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1752 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1753 //
1754 // Both describe the direct values of their associated variables.
1755 Dependencies.push_back(N.getNode());
1756 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1757 continue;
1758 }
1759 LocationOps.emplace_back(
1760 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1761 continue;
1762 }
1763
1764 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1765 // Special rules apply for the first dbg.values of parameter variables in a
1766 // function. Identify them by the fact they reference Argument Values, that
1767 // they're parameters, and they are parameters of the current function. We
1768 // need to let them dangle until they get an SDNode.
1769 bool IsParamOfFunc =
1770 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1771 if (IsParamOfFunc)
1772 return false;
1773
1774 // The value is not used in this block yet (or it would have an SDNode).
1775 // We still want the value to appear for the user if possible -- if it has
1776 // an associated VReg, we can refer to that instead.
1777 auto VMI = FuncInfo.ValueMap.find(V);
1778 if (VMI != FuncInfo.ValueMap.end()) {
1779 Register Reg = VMI->second;
1780 // If this is a PHI node, it may be split up into several MI PHI nodes
1781 // (in FunctionLoweringInfo::set).
1782 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1783 V->getType(), std::nullopt);
1784 if (RFV.occupiesMultipleRegs()) {
1785 // FIXME: We could potentially support variadic dbg_values here.
1786 if (IsVariadic)
1787 return false;
1788 unsigned Offset = 0;
1789 unsigned BitsToDescribe = 0;
1790 if (auto VarSize = Var->getSizeInBits())
1791 BitsToDescribe = *VarSize;
1792 if (auto Fragment = Expr->getFragmentInfo())
1793 BitsToDescribe = Fragment->SizeInBits;
1794 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1795 // Bail out if all bits are described already.
1796 if (Offset >= BitsToDescribe)
1797 break;
1798 // TODO: handle scalable vectors.
1799 unsigned RegisterSize = RegAndSize.second;
1800 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1801 ? BitsToDescribe - Offset
1802 : RegisterSize;
1803 auto FragmentExpr = DIExpression::createFragmentExpression(
1804 Expr, Offset, FragmentSize);
1805 if (!FragmentExpr)
1806 continue;
1807 SDDbgValue *SDV = DAG.getVRegDbgValue(
1808 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1809 DAG.AddDbgValue(SDV, false);
1810 Offset += RegisterSize;
1811 }
1812 return true;
1813 }
1814 // We can use simple vreg locations for variadic dbg_values as well.
1815 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1816 continue;
1817 }
1818 // We failed to create a SDDbgOperand for V.
1819 return false;
1820 }
1821
1822 // We have created a SDDbgOperand for each Value in Values.
1823 assert(!LocationOps.empty());
1824 SDDbgValue *SDV =
1825 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1826 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1827 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1828 return true;
1829}
1830
1832 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1833 for (auto &Pair : DanglingDebugInfoMap)
1834 for (auto &DDI : Pair.second)
1835 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1837}
1838
1839/// getCopyFromRegs - If there was virtual register allocated for the value V
1840/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1842 auto It = FuncInfo.ValueMap.find(V);
1844
1845 if (It != FuncInfo.ValueMap.end()) {
1846 Register InReg = It->second;
1847
1848 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1849 DAG.getDataLayout(), InReg, Ty,
1850 std::nullopt); // This is not an ABI copy.
1851 SDValue Chain = DAG.getEntryNode();
1852 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1853 V);
1855 }
1856
1857 return Result;
1858}
1859
1860/// getValue - Return an SDValue for the given Value.
1862 // If we already have an SDValue for this value, use it. It's important
1863 // to do this first, so that we don't create a CopyFromReg if we already
1864 // have a regular SDValue.
1865 SDValue &N = NodeMap[V];
1866 if (N.getNode()) return N;
1867
1868 // If there's a virtual register allocated and initialized for this
1869 // value, use it.
1870 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1871 return copyFromReg;
1872
1873 // Otherwise create a new SDValue and remember it.
1874 SDValue Val = getValueImpl(V);
1875 NodeMap[V] = Val;
1877 return Val;
1878}
1879
1880void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1881 if (V->getType()->isVoidTy())
1882 return;
1883
1884 SmallVector<EVT, 4> ValueVTs;
1885 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1886 V->getType(), ValueVTs);
1887 if (ValueVTs.empty())
1888 return;
1889 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1890}
1891
1892/// getNonRegisterValue - Return an SDValue for the given Value, but
1893/// don't look in FuncInfo.ValueMap for a virtual register.
1895 // If we already have an SDValue for this value, use it.
1896 SDValue &N = NodeMap[V];
1897 if (N.getNode()) {
1898 if (isIntOrFPConstant(N)) {
1899 // Remove the debug location from the node as the node is about to be used
1900 // in a location which may differ from the original debug location. This
1901 // is relevant to Constant and ConstantFP nodes because they can appear
1902 // as constant expressions inside PHI nodes.
1903 N->setDebugLoc(DebugLoc());
1904 }
1905 return N;
1906 }
1907
1908 // Otherwise create a new SDValue and remember it.
1909 SDValue Val = getValueImpl(V);
1910 NodeMap[V] = Val;
1912 return Val;
1913}
1914
1915/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1916/// Create an SDValue for the given value.
1918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1919
1920 if (const Constant *C = dyn_cast<Constant>(V)) {
1921 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1922
1923 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1924 SDLoc DL = getCurSDLoc();
1925
1926 // DAG.getConstant() may attempt to legalise the vector constant which can
1927 // significantly change the combines applied to the DAG. To reduce the
1928 // divergence when enabling ConstantInt based vectors we try to construct
1929 // the DAG in the same way as shufflevector based splats. TODO: The
1930 // divergence sometimes leads to better optimisations. Ideally we should
1931 // prevent DAG.getConstant() from legalising too early but there are some
1932 // degradations preventing this.
1933 if (VT.isScalableVector())
1934 return DAG.getNode(
1935 ISD::SPLAT_VECTOR, DL, VT,
1936 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1937 if (VT.isFixedLengthVector())
1938 return DAG.getSplatBuildVector(
1939 VT, DL,
1940 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1941 return DAG.getConstant(*CI, DL, VT);
1942 }
1943
1944 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1945 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1946
1947 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1948 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1949
1950 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1951 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1952 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1953 getValue(CPA->getAddrDiscriminator()),
1954 getValue(CPA->getDiscriminator()));
1955 }
1956
1958 return DAG.getConstant(0, getCurSDLoc(), VT);
1959
1960 if (match(C, m_VScale()))
1961 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1962
1963 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1964 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1965
1966 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1967 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1968
1969 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1970 visit(CE->getOpcode(), *CE);
1971 SDValue N1 = NodeMap[V];
1972 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1973 return N1;
1974 }
1975
1977 SmallVector<SDValue, 4> Constants;
1978 for (const Use &U : C->operands()) {
1979 SDNode *Val = getValue(U).getNode();
1980 // If the operand is an empty aggregate, there are no values.
1981 if (!Val) continue;
1982 // Add each leaf value from the operand to the Constants list
1983 // to form a flattened list of all the values.
1984 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1985 Constants.push_back(SDValue(Val, i));
1986 }
1987
1988 return DAG.getMergeValues(Constants, getCurSDLoc());
1989 }
1990
1991 if (const ConstantDataSequential *CDS =
1994 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1995 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1996 // Add each leaf value from the operand to the Constants list
1997 // to form a flattened list of all the values.
1998 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1999 Ops.push_back(SDValue(Val, i));
2000 }
2001
2002 if (isa<ArrayType>(CDS->getType()))
2003 return DAG.getMergeValues(Ops, getCurSDLoc());
2004 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2005 }
2006
2007 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
2009 "Unknown struct or array constant!");
2010
2011 SmallVector<EVT, 4> ValueVTs;
2012 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
2013 unsigned NumElts = ValueVTs.size();
2014 if (NumElts == 0)
2015 return SDValue(); // empty struct
2016 SmallVector<SDValue, 4> Constants(NumElts);
2017 for (unsigned i = 0; i != NumElts; ++i) {
2018 EVT EltVT = ValueVTs[i];
2019 if (isa<UndefValue>(C))
2020 Constants[i] = DAG.getUNDEF(EltVT);
2021 else if (EltVT.isFloatingPoint())
2022 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2023 else
2024 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
2025 }
2026
2027 return DAG.getMergeValues(Constants, getCurSDLoc());
2028 }
2029
2030 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
2031 return DAG.getBlockAddress(BA, VT);
2032
2033 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
2034 return getValue(Equiv->getGlobalValue());
2035
2036 if (const auto *NC = dyn_cast<NoCFIValue>(C))
2037 return getValue(NC->getGlobalValue());
2038
2039 if (VT == MVT::aarch64svcount) {
2040 assert(C->isNullValue() && "Can only zero this target type!");
2041 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
2042 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
2043 }
2044
2045 if (VT.isRISCVVectorTuple()) {
2046 assert(C->isNullValue() && "Can only zero this target type!");
2047 return DAG.getNode(
2049 DAG.getNode(
2051 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
2052 VT.getSizeInBits().getKnownMinValue() / 8, true),
2053 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
2054 }
2055
2056 if (VT == MVT::externref || VT == MVT::funcref) {
2057 assert(C->isNullValue() && "Can only zero this target type!");
2058 // The zero value of a WebAssembly reference type is the null reference,
2059 // materialized with ref.null.
2060 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
2061 : Intrinsic::wasm_ref_null_func;
2062 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
2063 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
2064 }
2065
2066 VectorType *VecTy = cast<VectorType>(V->getType());
2067
2068 // Now that we know the number and type of the elements, get that number of
2069 // elements into the Ops array based on what kind of constant it is.
2070 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2072 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2073 for (unsigned i = 0; i != NumElements; ++i)
2074 Ops.push_back(getValue(CV->getOperand(i)));
2075
2076 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2077 }
2078
2080 EVT EltVT =
2081 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2082
2083 SDValue Op;
2084 if (EltVT.isFloatingPoint())
2085 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2086 else
2087 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2088
2089 return DAG.getSplat(VT, getCurSDLoc(), Op);
2090 }
2091
2092 llvm_unreachable("Unknown vector constant");
2093 }
2094
2095 // If this is a static alloca, generate it as the frameindex instead of
2096 // computation.
2097 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2098 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2099 if (SI != FuncInfo.StaticAllocaMap.end())
2100 return DAG.getFrameIndex(
2101 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2102 }
2103
2104 // If this is an instruction which fast-isel has deferred, select it now.
2105 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2106 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2107 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2108 Inst->getType(), std::nullopt);
2109 SDValue Chain = DAG.getEntryNode();
2110 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2111 }
2112
2113 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2114 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2115
2116 if (const auto *BB = dyn_cast<BasicBlock>(V))
2117 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2118
2119 llvm_unreachable("Can't get register for value!");
2120}
2121
2122void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2124 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2125 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2126 bool IsSEH = isAsynchronousEHPersonality(Pers);
2127 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2128 if (IsSEH) {
2129 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2130 CatchPadMBB->setIsEHContTarget(true);
2132 } else
2133 CatchPadMBB->setIsEHScopeEntry();
2134 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2135 if (IsMSVCCXX || IsCoreCLR)
2136 CatchPadMBB->setIsEHFuncletEntry();
2137}
2138
2139void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2140 // Update machine-CFG edge.
2141 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2142 FuncInfo.MBB->addSuccessor(TargetMBB);
2143
2144 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2145 bool IsSEH = isAsynchronousEHPersonality(Pers);
2146 if (IsSEH) {
2147 // If this is not a fall-through branch or optimizations are switched off,
2148 // emit the branch.
2149 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2150 TM.getOptLevel() == CodeGenOptLevel::None)
2151 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2152 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2153 return;
2154 }
2155
2156 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2157 TargetMBB->setIsEHContTarget(true);
2158 DAG.getMachineFunction().setHasEHContTarget(true);
2159
2160 // Figure out the funclet membership for the catchret's successor.
2161 // This will be used by the FuncletLayout pass to determine how to order the
2162 // BB's.
2163 // A 'catchret' returns to the outer scope's color.
2164 Value *ParentPad = I.getCatchSwitchParentPad();
2165 const BasicBlock *SuccessorColor;
2166 if (isa<ConstantTokenNone>(ParentPad))
2167 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2168 else
2169 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2170 assert(SuccessorColor && "No parent funclet for catchret!");
2171 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2172 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2173
2174 // Create the terminator node.
2175 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2176 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2177 DAG.getBasicBlock(SuccessorColorMBB));
2178 DAG.setRoot(Ret);
2179}
2180
2181void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2182 // Don't emit any special code for the cleanuppad instruction. It just marks
2183 // the start of an EH scope/funclet.
2184 FuncInfo.MBB->setIsEHScopeEntry();
2185 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2186 if (Pers != EHPersonality::Wasm_CXX && Pers != EHPersonality::Wasm_D) {
2187 FuncInfo.MBB->setIsEHFuncletEntry();
2188 FuncInfo.MBB->setIsCleanupFuncletEntry();
2189 }
2190}
2191
2192/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2193/// many places it could ultimately go. In the IR, we have a single unwind
2194/// destination, but in the machine CFG, we enumerate all the possible blocks.
2195/// This function skips over imaginary basic blocks that hold catchswitch
2196/// instructions, and finds all the "real" machine
2197/// basic block destinations. As those destinations may not be successors of
2198/// EHPadBB, here we also calculate the edge probability to those destinations.
2199/// The passed-in Prob is the edge probability to EHPadBB.
2201 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2202 BranchProbability Prob,
2203 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2204 &UnwindDests) {
2205 EHPersonality Personality =
2207 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2208 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2209 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2210 bool IsWasmD = Personality == EHPersonality::Wasm_D;
2211 bool IsSEH = isAsynchronousEHPersonality(Personality);
2212
2213 while (EHPadBB) {
2215 BasicBlock *NewEHPadBB = nullptr;
2216 if (isa<LandingPadInst>(Pad)) {
2217 // Stop on landingpads. They are not funclets.
2218 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2219 break;
2220 } else if (isa<CleanupPadInst>(Pad)) {
2221 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2222 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2223 // which always catches an exception.
2224 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2225 UnwindDests.back().first->setIsEHScopeEntry();
2226 // In Wasm, EH scopes are not funclets
2227 if (!IsWasmCXX && !IsWasmD)
2228 UnwindDests.back().first->setIsEHFuncletEntry();
2229 break;
2230 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2231 // Add the catchpad handlers to the possible destinations.
2232 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2233 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2234 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2235 if (IsMSVCCXX || IsCoreCLR)
2236 UnwindDests.back().first->setIsEHFuncletEntry();
2237 if (!IsSEH)
2238 UnwindDests.back().first->setIsEHScopeEntry();
2239 }
2240 NewEHPadBB = CatchSwitch->getUnwindDest();
2241 } else {
2242 continue;
2243 }
2244
2245 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2246 if (BPI && NewEHPadBB)
2247 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2248 EHPadBB = NewEHPadBB;
2249 }
2250}
2251
2252void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2253 // Update successor info.
2255 auto UnwindDest = I.getUnwindDest();
2256 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2257 BranchProbability UnwindDestProb =
2258 (BPI && UnwindDest)
2259 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2261 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2262 for (auto &UnwindDest : UnwindDests) {
2263 UnwindDest.first->setIsEHPad();
2264 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2265 }
2266 FuncInfo.MBB->normalizeSuccProbs();
2267
2268 // Create the terminator node.
2269 MachineBasicBlock *CleanupPadMBB =
2270 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2271 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2272 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2273 DAG.setRoot(Ret);
2274}
2275
2276void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2277 report_fatal_error("visitCatchSwitch not yet implemented!");
2278}
2279
2280void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2281 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2282 auto &DL = DAG.getDataLayout();
2283 SDValue Chain = getControlRoot();
2286
2287 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2288 // lower
2289 //
2290 // %val = call <ty> @llvm.experimental.deoptimize()
2291 // ret <ty> %val
2292 //
2293 // differently.
2294 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2296 return;
2297 }
2298
2299 if (!FuncInfo.CanLowerReturn) {
2300 Register DemoteReg = FuncInfo.DemoteRegister;
2301
2302 // Emit a store of the return value through the virtual register.
2303 // Leave Outs empty so that LowerReturn won't try to load return
2304 // registers the usual way.
2305 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2306 SDValue RetPtr =
2307 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2308 Type *RetTy = I.getOperand(0)->getType();
2309 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2310 RetPtr =
2311 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2312 SDValue RetOp = getValue(I.getOperand(0));
2313
2314 SmallVector<EVT, 4> ValueVTs, MemVTs;
2315 SmallVector<uint64_t, 4> Offsets;
2316 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2317 unsigned NumValues = ValueVTs.size();
2318
2319 SmallVector<SDValue, 4> Chains(NumValues);
2320 for (unsigned i = 0; i != NumValues; ++i) {
2321 // An aggregate return value cannot wrap around the address space, so
2322 // offsets to its parts don't wrap either.
2323 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2324 TypeSize::getFixed(Offsets[i]));
2325
2326 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2327 if (MemVTs[i] != ValueVTs[i])
2328 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2329 Chains[i] = DAG.getStore(
2330 Chain, getCurSDLoc(), Val,
2331 // FIXME: better loc info would be nice.
2332 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2333 commonAlignment(BaseAlign, Offsets[i]));
2334 }
2335
2336 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2337 MVT::Other, Chains);
2338 } else if (I.getNumOperands() != 0) {
2340 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2341 unsigned NumValues = Types.size();
2342 if (NumValues) {
2343 SDValue RetOp = getValue(I.getOperand(0));
2344
2345 const Function *F = I.getParent()->getParent();
2346
2348 I.getOperand(0)->getType(), F->getCallingConv(),
2349 /*IsVarArg*/ false, DL);
2350
2352 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2354 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2356
2357 LLVMContext &Context = F->getContext();
2358 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2359
2360 for (unsigned j = 0; j != NumValues; ++j) {
2361 EVT VT = TLI.getValueType(DL, Types[j]);
2362
2363 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2365
2366 CallingConv::ID CC = F->getCallingConv();
2367
2369 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2372 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2373 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2374
2375 // 'inreg' on function refers to return value
2376 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2377 if (RetInReg)
2378 Flags.setInReg();
2379
2380 if (I.getOperand(0)->getType()->isPointerTy()) {
2381 Flags.setPointer();
2382 Flags.setPointerAddrSpace(
2383 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2384 }
2385
2386 if (NeedsRegBlock) {
2387 Flags.setInConsecutiveRegs();
2388 if (j == NumValues - 1)
2389 Flags.setInConsecutiveRegsLast();
2390 }
2391
2392 // Propagate extension type if any
2394 Flags.setSExt();
2395 else if (ExtendKind == ISD::ZERO_EXTEND)
2396 Flags.setZExt();
2397 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2398 Flags.setNoExt();
2399
2400 for (unsigned i = 0; i < NumParts; ++i) {
2401 Outs.push_back(ISD::OutputArg(Flags,
2402 Parts[i].getValueType().getSimpleVT(),
2403 VT, Types[j], 0, 0));
2404 OutVals.push_back(Parts[i]);
2405 }
2406 }
2407 }
2408 }
2409
2410 // Push in swifterror virtual register as the last element of Outs. This makes
2411 // sure swifterror virtual register will be returned in the swifterror
2412 // physical register.
2413 const Function *F = I.getParent()->getParent();
2414 if (TLI.supportSwiftError() &&
2415 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2416 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2417 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2418 Flags.setSwiftError();
2419 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2420 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2421 PointerType::getUnqual(*DAG.getContext()),
2422 /*origidx=*/1, /*partOffs=*/0));
2423 // Create SDNode for the swifterror virtual register.
2424 OutVals.push_back(
2425 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2426 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2427 EVT(TLI.getPointerTy(DL))));
2428 }
2429
2430 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2431 CallingConv::ID CallConv =
2432 DAG.getMachineFunction().getFunction().getCallingConv();
2433 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2434 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2435
2436 // Verify that the target's LowerReturn behaved as expected.
2437 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2438 "LowerReturn didn't return a valid chain!");
2439
2440 // Update the DAG with the new chain value resulting from return lowering.
2441 DAG.setRoot(Chain);
2442}
2443
2444/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2445/// created for it, emit nodes to copy the value into the virtual
2446/// registers.
2448 // Skip empty types
2449 if (V->getType()->isEmptyTy())
2450 return;
2451
2452 auto VMI = FuncInfo.ValueMap.find(V);
2453 if (VMI != FuncInfo.ValueMap.end()) {
2454 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2455 "Unused value assigned virtual registers!");
2456 CopyValueToVirtualRegister(V, VMI->second);
2457 }
2458}
2459
2460/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2461/// the current basic block, add it to ValueMap now so that we'll get a
2462/// CopyTo/FromReg.
2464 // No need to export constants.
2465 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2466
2467 // Already exported?
2468 if (FuncInfo.isExportedInst(V)) return;
2469
2470 Register Reg = FuncInfo.InitializeRegForValue(V);
2472}
2473
2475 const BasicBlock *FromBB) {
2476 // The operands of the setcc have to be in this block. We don't know
2477 // how to export them from some other block.
2478 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2479 // Can export from current BB.
2480 if (VI->getParent() == FromBB)
2481 return true;
2482
2483 // Is already exported, noop.
2484 return FuncInfo.isExportedInst(V);
2485 }
2486
2487 // If this is an argument, we can export it if the BB is the entry block or
2488 // if it is already exported.
2489 if (isa<Argument>(V)) {
2490 if (FromBB->isEntryBlock())
2491 return true;
2492
2493 // Otherwise, can only export this if it is already exported.
2494 return FuncInfo.isExportedInst(V);
2495 }
2496
2497 // Otherwise, constants can always be exported.
2498 return true;
2499}
2500
2501/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2503SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2504 const MachineBasicBlock *Dst) const {
2506 const BasicBlock *SrcBB = Src->getBasicBlock();
2507 const BasicBlock *DstBB = Dst->getBasicBlock();
2508 if (!BPI) {
2509 // If BPI is not available, set the default probability as 1 / N, where N is
2510 // the number of successors.
2511 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2512 return BranchProbability(1, SuccSize);
2513 }
2514 return BPI->getEdgeProbability(SrcBB, DstBB);
2515}
2516
2517void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2518 MachineBasicBlock *Dst,
2519 BranchProbability Prob) {
2520 if (!FuncInfo.BPI)
2521 Src->addSuccessorWithoutProb(Dst);
2522 else {
2523 if (Prob.isUnknown())
2524 Prob = getEdgeProbability(Src, Dst);
2525 Src->addSuccessor(Dst, Prob);
2526 }
2527}
2528
2529static bool InBlock(const Value *V, const BasicBlock *BB) {
2530 if (const Instruction *I = dyn_cast<Instruction>(V))
2531 return I->getParent() == BB;
2532 return true;
2533}
2534
2535/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2536/// This function emits a branch and is used at the leaves of an OR or an
2537/// AND operator tree.
2538void
2541 MachineBasicBlock *FBB,
2542 MachineBasicBlock *CurBB,
2543 MachineBasicBlock *SwitchBB,
2544 BranchProbability TProb,
2545 BranchProbability FProb,
2546 bool InvertCond) {
2547 const BasicBlock *BB = CurBB->getBasicBlock();
2548
2549 // If the leaf of the tree is a comparison, merge the condition into
2550 // the caseblock.
2551 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2552 // The operands of the cmp have to be in this block. We don't know
2553 // how to export them from some other block. If this is the first block
2554 // of the sequence, no exporting is needed.
2555 if (CurBB == SwitchBB ||
2556 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2557 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2558 ISD::CondCode Condition;
2559 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2560 ICmpInst::Predicate Pred =
2561 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2562 Condition = getICmpCondCode(Pred);
2563 } else {
2564 const FCmpInst *FC = cast<FCmpInst>(Cond);
2565 FCmpInst::Predicate Pred =
2566 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2567 Condition = getFCmpCondCode(Pred);
2568 if (FC->hasNoNaNs() ||
2569 (isKnownNeverNaN(FC->getOperand(0),
2570 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2571 isKnownNeverNaN(FC->getOperand(1),
2572 SimplifyQuery(DAG.getDataLayout(), FC))))
2573 Condition = getFCmpCodeWithoutNaN(Condition);
2574 }
2575
2576 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2577 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2578 SL->SwitchCases.push_back(CB);
2579 return;
2580 }
2581 }
2582
2583 // Create a CaseBlock record representing this branch.
2584 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2585 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2586 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2587 SL->SwitchCases.push_back(CB);
2588}
2589
2590// Collect dependencies on V recursively. This is used for the cost analysis in
2591// `shouldKeepJumpConditionsTogether`.
2595 unsigned Depth = 0) {
2596 // Return false if we have an incomplete count.
2598 return false;
2599
2600 auto *I = dyn_cast<Instruction>(V);
2601 if (I == nullptr)
2602 return true;
2603
2604 if (Necessary != nullptr) {
2605 // This instruction is necessary for the other side of the condition so
2606 // don't count it.
2607 if (Necessary->contains(I))
2608 return true;
2609 }
2610
2611 // Already added this dep.
2612 if (!Deps->try_emplace(I, false).second)
2613 return true;
2614
2615 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2616 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2617 Depth + 1))
2618 return false;
2619 return true;
2620}
2621
2624 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2626 if (Params.BaseCost < 0)
2627 return false;
2628
2629 // Baseline cost.
2630 InstructionCost CostThresh = Params.BaseCost;
2631
2632 BranchProbabilityInfo *BPI = nullptr;
2633 if (Params.LikelyBias || Params.UnlikelyBias)
2634 BPI = FuncInfo.BPI;
2635 if (BPI != nullptr) {
2636 // See if we are either likely to get an early out or compute both lhs/rhs
2637 // of the condition.
2638 BasicBlock *IfTrue = I.getSuccessor(0);
2639 BasicBlock *IfFalse = I.getSuccessor(1);
2641 std::swap(IfTrue, IfFalse);
2642
2643 std::optional<bool> Likely;
2644 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2645 Likely = true;
2646 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2647 Likely = false;
2648
2649 if (Likely) {
2650 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2651 // Its likely we will have to compute both lhs and rhs of condition
2652 CostThresh += Params.LikelyBias;
2653 else {
2654 if (Params.UnlikelyBias < 0)
2655 return false;
2656 // Its likely we will get an early out.
2657 CostThresh -= Params.UnlikelyBias;
2658 }
2659 }
2660 }
2661
2662 if (CostThresh <= 0)
2663 return false;
2664
2665 // Collect "all" instructions that lhs condition is dependent on.
2666 // Use map for stable iteration (to avoid non-determanism of iteration of
2667 // SmallPtrSet). The `bool` value is just a dummy.
2669 collectInstructionDeps(&LhsDeps, Lhs);
2670 // Collect "all" instructions that rhs condition is dependent on AND are
2671 // dependencies of lhs. This gives us an estimate on which instructions we
2672 // stand to save by splitting the condition.
2673 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2674 return false;
2675 // Add the compare instruction itself unless its a dependency on the LHS.
2676 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2677 if (!LhsDeps.contains(RhsI))
2678 RhsDeps.try_emplace(RhsI, false);
2679
2680 InstructionCost CostOfIncluding = 0;
2681 // See if this instruction will need to computed independently of whether RHS
2682 // is.
2683 Value *BrCond = I.getCondition();
2684 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2685 for (const Instruction *UIns : Ins->users()) {
2686 // If user is independent of RHS calculation we don't need to count it.
2687 if (UIns != BrCond && !RhsDeps.contains(UIns))
2688 return false;
2689 }
2690 return true;
2691 };
2692
2693 // Prune instructions from RHS Deps that are dependencies of unrelated
2694 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2695 // arbitrary and just meant to cap the how much time we spend in the pruning
2696 // loop. Its highly unlikely to come into affect.
2697 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2698 // Stop after a certain point. No incorrectness from including too many
2699 // instructions.
2700 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2701 const Instruction *ToDrop = nullptr;
2702 for (const auto &InsPair : RhsDeps) {
2703 if (!ShouldCountInsn(InsPair.first)) {
2704 ToDrop = InsPair.first;
2705 break;
2706 }
2707 }
2708 if (ToDrop == nullptr)
2709 break;
2710 RhsDeps.erase(ToDrop);
2711 }
2712
2713 for (const auto &InsPair : RhsDeps) {
2714 // Finally accumulate latency that we can only attribute to computing the
2715 // RHS condition. Use latency because we are essentially trying to calculate
2716 // the cost of the dependency chain.
2717 // Possible TODO: We could try to estimate ILP and make this more precise.
2718 CostOfIncluding += TTI->getInstructionCost(
2719 InsPair.first, TargetTransformInfo::TCK_Latency);
2720
2721 if (CostOfIncluding > CostThresh)
2722 return false;
2723 }
2724 return true;
2725}
2726
2729 MachineBasicBlock *FBB,
2730 MachineBasicBlock *CurBB,
2731 MachineBasicBlock *SwitchBB,
2733 BranchProbability TProb,
2734 BranchProbability FProb,
2735 bool InvertCond) {
2736 // Skip over not part of the tree and remember to invert op and operands at
2737 // next level.
2738 Value *NotCond;
2739 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2740 InBlock(NotCond, CurBB->getBasicBlock())) {
2741 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2742 !InvertCond);
2743 return;
2744 }
2745
2747 const Value *BOpOp0, *BOpOp1;
2748 // Compute the effective opcode for Cond, taking into account whether it needs
2749 // to be inverted, e.g.
2750 // and (not (or A, B)), C
2751 // gets lowered as
2752 // and (and (not A, not B), C)
2754 if (BOp) {
2755 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2756 ? Instruction::And
2757 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2758 ? Instruction::Or
2760 if (InvertCond) {
2761 if (BOpc == Instruction::And)
2762 BOpc = Instruction::Or;
2763 else if (BOpc == Instruction::Or)
2764 BOpc = Instruction::And;
2765 }
2766 }
2767
2768 // If this node is not part of the or/and tree, emit it as a branch.
2769 // Note that all nodes in the tree should have same opcode.
2770 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2771 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2772 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2773 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2774 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2775 TProb, FProb, InvertCond);
2776 return;
2777 }
2778
2779 // Create TmpBB after CurBB.
2780 MachineFunction::iterator BBI(CurBB);
2781 MachineFunction &MF = DAG.getMachineFunction();
2783 CurBB->getParent()->insert(++BBI, TmpBB);
2784
2785 if (Opc == Instruction::Or) {
2786 // Codegen X | Y as:
2787 // BB1:
2788 // jmp_if_X TBB
2789 // jmp TmpBB
2790 // TmpBB:
2791 // jmp_if_Y TBB
2792 // jmp FBB
2793 //
2794
2795 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2796 // The requirement is that
2797 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2798 // = TrueProb for original BB.
2799 // Assuming the original probabilities are A and B, one choice is to set
2800 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2801 // A/(1+B) and 2B/(1+B). This choice assumes that
2802 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2803 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2804 // TmpBB, but the math is more complicated.
2805
2806 auto NewTrueProb = TProb / 2;
2807 auto NewFalseProb = TProb / 2 + FProb;
2808 // Emit the LHS condition.
2809 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2810 NewFalseProb, InvertCond);
2811
2812 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2813 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2815 // Emit the RHS condition into TmpBB.
2816 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2817 Probs[1], InvertCond);
2818 } else {
2819 assert(Opc == Instruction::And && "Unknown merge op!");
2820 // Codegen X & Y as:
2821 // BB1:
2822 // jmp_if_X TmpBB
2823 // jmp FBB
2824 // TmpBB:
2825 // jmp_if_Y TBB
2826 // jmp FBB
2827 //
2828 // This requires creation of TmpBB after CurBB.
2829
2830 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2831 // The requirement is that
2832 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2833 // = FalseProb for original BB.
2834 // Assuming the original probabilities are A and B, one choice is to set
2835 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2836 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2837 // TrueProb for BB1 * FalseProb for TmpBB.
2838
2839 auto NewTrueProb = TProb + FProb / 2;
2840 auto NewFalseProb = FProb / 2;
2841 // Emit the LHS condition.
2842 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2843 NewFalseProb, InvertCond);
2844
2845 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2846 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2848 // Emit the RHS condition into TmpBB.
2849 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2850 Probs[1], InvertCond);
2851 }
2852}
2853
2854/// If the set of cases should be emitted as a series of branches, return true.
2855/// If we should emit this as a bunch of and/or'd together conditions, return
2856/// false.
2857bool
2858SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2859 if (Cases.size() != 2) return true;
2860
2861 // If this is two comparisons of the same values or'd or and'd together, they
2862 // will get folded into a single comparison, so don't emit two blocks.
2863 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2864 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2865 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2866 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2867 return false;
2868 }
2869
2870 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2871 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2872 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2873 Cases[0].CC == Cases[1].CC &&
2874 isa<Constant>(Cases[0].CmpRHS) &&
2875 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2876 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2877 return false;
2878 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2879 return false;
2880 }
2881
2882 return true;
2883}
2884
2885void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2887
2888 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2889
2890 // Update machine-CFG edges.
2891 BrMBB->addSuccessor(Succ0MBB);
2892
2893 // If this is not a fall-through branch or optimizations are switched off,
2894 // emit the branch.
2895 if (Succ0MBB != NextBlock(BrMBB) ||
2897 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2898 DAG.getBasicBlock(Succ0MBB));
2899 setValue(&I, Br);
2900 DAG.setRoot(Br);
2901 }
2902}
2903
2904void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2905 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2906
2907 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2908
2909 // If this condition is one of the special cases we handle, do special stuff
2910 // now.
2911 const Value *CondVal = I.getCondition();
2912 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2913
2914 // If this is a series of conditions that are or'd or and'd together, emit
2915 // this as a sequence of branches instead of setcc's with and/or operations.
2916 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2917 // unpredictable branches, and vector extracts because those jumps are likely
2918 // expensive for any target), this should improve performance.
2919 // For example, instead of something like:
2920 // cmp A, B
2921 // C = seteq
2922 // cmp D, E
2923 // F = setle
2924 // or C, F
2925 // jnz foo
2926 // Emit:
2927 // cmp A, B
2928 // je foo
2929 // cmp D, E
2930 // jle foo
2931 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2932 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2933 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2934 BOp->hasOneUse() && !IsUnpredictable) {
2935 Value *Vec;
2936 const Value *BOp0, *BOp1;
2938 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2939 Opcode = Instruction::And;
2940 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2941 Opcode = Instruction::Or;
2942
2943 if (Opcode &&
2944 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2945 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2947 FuncInfo, I, Opcode, BOp0, BOp1,
2948 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2949 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2950 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2951 getEdgeProbability(BrMBB, Succ0MBB),
2952 getEdgeProbability(BrMBB, Succ1MBB),
2953 /*InvertCond=*/false);
2954 // If the compares in later blocks need to use values not currently
2955 // exported from this block, export them now. This block should always
2956 // be the first entry.
2957 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2958
2959 // Allow some cases to be rejected.
2960 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2961 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2962 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2963 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2964 }
2965
2966 // Emit the branch for this block.
2967 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2968 SL->SwitchCases.erase(SL->SwitchCases.begin());
2969 return;
2970 }
2971
2972 // Okay, we decided not to do this, remove any inserted MBB's and clear
2973 // SwitchCases.
2974 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2975 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2976
2977 SL->SwitchCases.clear();
2978 }
2979 }
2980
2981 // Create a CaseBlock record representing this branch.
2982 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2983 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2985 IsUnpredictable);
2986
2987 // Use visitSwitchCase to actually insert the fast branch sequence for this
2988 // cond branch.
2989 visitSwitchCase(CB, BrMBB);
2990}
2991
2992/// visitSwitchCase - Emits the necessary code to represent a single node in
2993/// the binary search tree resulting from lowering a switch instruction.
2995 MachineBasicBlock *SwitchBB) {
2996 SDValue Cond;
2997 SDValue CondLHS = getValue(CB.CmpLHS);
2998 SDLoc dl = CB.DL;
2999
3000 if (CB.CC == ISD::SETTRUE) {
3001 // Branch or fall through to TrueBB.
3002 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3003 SwitchBB->normalizeSuccProbs();
3004 if (CB.TrueBB != NextBlock(SwitchBB)) {
3005 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
3006 DAG.getBasicBlock(CB.TrueBB)));
3007 }
3008 return;
3009 }
3010
3011 auto &TLI = DAG.getTargetLoweringInfo();
3012 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
3013
3014 // Build the setcc now.
3015 if (!CB.CmpMHS) {
3016 // Fold "(X == true)" to X and "(X == false)" to !X to
3017 // handle common cases produced by branch lowering.
3018 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
3019 CB.CC == ISD::SETEQ)
3020 Cond = CondLHS;
3021 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
3022 CB.CC == ISD::SETEQ) {
3023 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
3024 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
3025 } else {
3026 SDValue CondRHS = getValue(CB.CmpRHS);
3027
3028 // If a pointer's DAG type is larger than its memory type then the DAG
3029 // values are zero-extended. This breaks signed comparisons so truncate
3030 // back to the underlying type before doing the compare.
3031 if (CondLHS.getValueType() != MemVT) {
3032 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
3033 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
3034 }
3035 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
3036 }
3037 } else {
3038 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
3039
3040 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
3041 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
3042
3043 SDValue CmpOp = getValue(CB.CmpMHS);
3044 EVT VT = CmpOp.getValueType();
3045
3046 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
3047 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
3048 ISD::SETLE);
3049 } else {
3050 SDValue SUB = DAG.getNode(ISD::SUB, dl,
3051 VT, CmpOp, DAG.getConstant(Low, dl, VT));
3052 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
3053 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
3054 }
3055 }
3056
3057 // Update successor info
3058 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3059 // TrueBB and FalseBB are always different unless the incoming IR is
3060 // degenerate. This only happens when running llc on weird IR.
3061 if (CB.TrueBB != CB.FalseBB)
3062 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
3063 SwitchBB->normalizeSuccProbs();
3064
3065 // If the lhs block is the next block, invert the condition so that we can
3066 // fall through to the lhs instead of the rhs block.
3067 if (CB.TrueBB == NextBlock(SwitchBB)) {
3068 std::swap(CB.TrueBB, CB.FalseBB);
3069 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3070 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3071 }
3072
3073 SDNodeFlags Flags;
3075 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3076 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3077
3078 setValue(CurInst, BrCond);
3079
3080 // Insert the false branch. Do this even if it's a fall through branch,
3081 // this makes it easier to do DAG optimizations which require inverting
3082 // the branch condition.
3083 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3084 DAG.getBasicBlock(CB.FalseBB));
3085
3086 DAG.setRoot(BrCond);
3087}
3088
3089/// visitJumpTable - Emit JumpTable node in the current MBB
3091 // Emit the code for the jump table
3092 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3093 assert(JT.Reg && "Should lower JT Header first!");
3094 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3095 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3096 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3097 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3098 Index.getValue(1), Table, Index);
3099 DAG.setRoot(BrJumpTable);
3100}
3101
3102/// visitJumpTableHeader - This function emits necessary code to produce index
3103/// in the JumpTable from switch case.
3105 JumpTableHeader &JTH,
3106 MachineBasicBlock *SwitchBB) {
3107 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3108 const SDLoc &dl = *JT.SL;
3109
3110 // Subtract the lowest switch case value from the value being switched on.
3111 SDValue SwitchOp = getValue(JTH.SValue);
3112 EVT VT = SwitchOp.getValueType();
3113 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3114 DAG.getConstant(JTH.First, dl, VT));
3115
3116 // The SDNode we just created, which holds the value being switched on minus
3117 // the smallest case value, needs to be copied to a virtual register so it
3118 // can be used as an index into the jump table in a subsequent basic block.
3119 // This value may be smaller or larger than the target's pointer type, and
3120 // therefore require extension or truncating.
3121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3122 SwitchOp =
3123 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3124
3125 Register JumpTableReg =
3126 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3127 SDValue CopyTo =
3128 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3129 JT.Reg = JumpTableReg;
3130
3131 if (!JTH.FallthroughUnreachable) {
3132 // Emit the range check for the jump table, and branch to the default block
3133 // for the switch statement if the value being switched on exceeds the
3134 // largest case in the switch.
3135 SDValue CMP = DAG.getSetCC(
3136 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3137 Sub.getValueType()),
3138 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3139
3140 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3141 MVT::Other, CopyTo, CMP,
3142 DAG.getBasicBlock(JT.Default));
3143
3144 // Avoid emitting unnecessary branches to the next block.
3145 if (JT.MBB != NextBlock(SwitchBB))
3146 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3147 DAG.getBasicBlock(JT.MBB));
3148
3149 DAG.setRoot(BrCond);
3150 } else {
3151 // Avoid emitting unnecessary branches to the next block.
3152 if (JT.MBB != NextBlock(SwitchBB))
3153 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3154 DAG.getBasicBlock(JT.MBB)));
3155 else
3156 DAG.setRoot(CopyTo);
3157 }
3158}
3159
3160/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3161/// variable if there exists one.
3163 SDValue &Chain) {
3165 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3166 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3168 Value *Global =
3169 TLI.getSDagStackGuard(*MF.getFunction().getParent(), DAG.getLibcalls());
3171 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3172 if (Global) {
3173 MachinePointerInfo MPInfo(Global);
3177 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3178 DAG.setNodeMemRefs(Node, {MemRef});
3179 }
3180 if (PtrTy != PtrMemTy)
3181 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3182 return SDValue(Node, 0);
3183}
3184
3185/// Codegen a new tail for a stack protector check ParentMBB which has had its
3186/// tail spliced into a stack protector check success bb.
3187///
3188/// For a high level explanation of how this fits into the stack protector
3189/// generation see the comment on the declaration of class
3190/// StackProtectorDescriptor.
3192 MachineBasicBlock *ParentBB) {
3193
3194 // First create the loads to the guard/stack slot for the comparison.
3195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3196 auto &DL = DAG.getDataLayout();
3197 EVT PtrTy = TLI.getFrameIndexTy(DL);
3198 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3199
3200 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3201 int FI = MFI.getStackProtectorIndex();
3202
3203 SDValue Guard;
3204 SDLoc dl = getCurSDLoc();
3205 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3206 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3207 Align Align = DL.getPrefTypeAlign(
3208 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3209
3210 // Generate code to load the content of the guard slot.
3211 SDValue GuardVal = DAG.getLoad(
3212 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3213 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3215
3216 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3217 // original cookie for comparison. The prologue stored (FP - Cookie) or
3218 // (FP XOR Cookie), so we apply the same operation again to unmix:
3219 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3220 if (TLI.useStackGuardMixFP())
3221 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3222
3223 // If we're using function-based instrumentation, call the guard check
3224 // function
3226 // Get the guard check function from the target and verify it exists since
3227 // we're using function-based instrumentation
3228 const Function *GuardCheckFn =
3229 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3230 assert(GuardCheckFn && "Guard check function is null");
3231
3232 // The target provides a guard check function to validate the guard value.
3233 // Generate a call to that function with the content of the guard slot as
3234 // argument.
3235 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3236 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3237
3239 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3240 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3241 Entry.IsInReg = true;
3242 Args.push_back(Entry);
3243
3246 .setChain(DAG.getEntryNode())
3247 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3248 getValue(GuardCheckFn), std::move(Args));
3249
3250 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3251 DAG.setRoot(Result.second);
3252 return;
3253 }
3254
3255 // Load the fresh guard value for comparison.
3256 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3257 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3258 SDValue Chain = DAG.getEntryNode();
3259 if (TLI.useStackGuardMixFP()) {
3260 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3261 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3262 SDValue GuardPtr = getValue(IRGuard);
3263 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3264 MachinePointerInfo(IRGuard, 0), Align,
3266 } else {
3267 LLVMContext &Ctx = *DAG.getContext();
3268 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3269 Guard = DAG.getPOISON(PtrMemTy);
3270 }
3271 } else {
3272 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3273 if (TLI.useLoadStackGuardNode(M)) {
3274 Guard = getLoadStackGuard(DAG, dl, Chain);
3275 } else {
3276 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3277 SDValue GuardPtr = getValue(IRGuard);
3278 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3279 MachinePointerInfo(IRGuard, 0), Align,
3281 } else {
3282 LLVMContext &Ctx = *DAG.getContext();
3283 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3284 Guard = DAG.getPOISON(PtrMemTy);
3285 }
3286 }
3287 }
3288
3289 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3290 // contain unmixed cookie values that can be compared directly.
3291
3292 // Perform the comparison via a getsetcc.
3293 SDValue Cmp = DAG.getSetCC(
3294 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3295 Guard, GuardVal, ISD::SETNE);
3296
3297 // If the guard/stackslot do not equal, branch to failure MBB.
3298 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3299 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3300 // Otherwise branch to success MBB.
3301 SDValue Br = DAG.getNode(ISD::BR, dl,
3302 MVT::Other, BrCond,
3303 DAG.getBasicBlock(SPD.getSuccessMBB()));
3304
3305 DAG.setRoot(Br);
3306}
3307
3308/// Codegen the failure basic block for a stack protector check.
3309///
3310/// A failure stack protector machine basic block consists simply of a call to
3311/// __stack_chk_fail().
3312///
3313/// For a high level explanation of how this fits into the stack protector
3314/// generation see the comment on the declaration of class
3315/// StackProtectorDescriptor.
3318
3319 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3320 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3321 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3322 SDValue Chain;
3323
3324 // For -Oz builds with a guard check function, we use function-based
3325 // instrumentation. Otherwise, if we have a guard check function, we call it
3326 // in the failure block.
3327 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3328 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3329 // First create the loads to the guard/stack slot for the comparison.
3330 auto &DL = DAG.getDataLayout();
3331 EVT PtrTy = TLI.getFrameIndexTy(DL);
3332 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3333
3334 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3335 int FI = MFI.getStackProtectorIndex();
3336
3337 SDLoc dl = getCurSDLoc();
3338 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3339 Align Align = DL.getPrefTypeAlign(
3340 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3341
3342 // Generate code to load the content of the guard slot.
3343 SDValue GuardVal = DAG.getLoad(
3344 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3345 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3347
3348 if (TLI.useStackGuardMixFP())
3349 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3350
3351 // The target provides a guard check function to validate the guard value.
3352 // Generate a call to that function with the content of the guard slot as
3353 // argument.
3354 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3355 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3356
3358 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3359 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3360 Entry.IsInReg = true;
3361 Args.push_back(Entry);
3362
3365 .setChain(DAG.getEntryNode())
3366 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3367 getValue(GuardCheckFn), std::move(Args));
3368
3369 Chain = TLI.LowerCallTo(CLI).second;
3370 } else {
3372 CallOptions.setDiscardResult(true);
3373 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3374 {}, CallOptions, getCurSDLoc())
3375 .second;
3376 }
3377
3378 // Emit a trap instruction if we are required to do so.
3379 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3380 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3381 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3382
3383 DAG.setRoot(Chain);
3384}
3385
3386/// visitBitTestHeader - This function emits necessary code to produce value
3387/// suitable for "bit tests"
3389 MachineBasicBlock *SwitchBB) {
3390 SDLoc dl = getCurSDLoc();
3391
3392 // Subtract the minimum value.
3393 SDValue SwitchOp = getValue(B.SValue);
3394 EVT VT = SwitchOp.getValueType();
3395 SDValue RangeSub =
3396 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3397
3398 // Determine the type of the test operands.
3399 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3400 bool UsePtrType = false;
3401 if (!TLI.isTypeLegal(VT)) {
3402 UsePtrType = true;
3403 } else {
3404 for (const BitTestCase &Case : B.Cases)
3405 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3406 // Switch table case range are encoded into series of masks.
3407 // Just use pointer type, it's guaranteed to fit.
3408 UsePtrType = true;
3409 break;
3410 }
3411 }
3412 SDValue Sub = RangeSub;
3413 if (UsePtrType) {
3414 VT = TLI.getPointerTy(DAG.getDataLayout());
3415 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3416 }
3417
3418 B.RegVT = VT.getSimpleVT();
3419 B.Reg = FuncInfo.CreateReg(B.RegVT);
3420 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3421
3422 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3423
3424 if (!B.FallthroughUnreachable)
3425 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3426 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3427 SwitchBB->normalizeSuccProbs();
3428
3429 SDValue Root = CopyTo;
3430 if (!B.FallthroughUnreachable) {
3431 // Conditional branch to the default block.
3432 SDValue RangeCmp = DAG.getSetCC(dl,
3433 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3434 RangeSub.getValueType()),
3435 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3436 ISD::SETUGT);
3437
3438 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3439 DAG.getBasicBlock(B.Default));
3440 }
3441
3442 // Avoid emitting unnecessary branches to the next block.
3443 if (MBB != NextBlock(SwitchBB))
3444 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3445
3446 DAG.setRoot(Root);
3447}
3448
3449/// visitBitTestCase - this function produces one "bit test"
3451 MachineBasicBlock *NextMBB,
3452 BranchProbability BranchProbToNext,
3453 Register Reg, BitTestCase &B,
3454 MachineBasicBlock *SwitchBB) {
3455 SDLoc dl = getCurSDLoc();
3456 MVT VT = BB.RegVT;
3457 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3458 SDValue Cmp;
3459 unsigned PopCount = llvm::popcount(B.Mask);
3460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3461 if (PopCount == 1) {
3462 // Testing for a single bit; just compare the shift count with what it
3463 // would need to be to shift a 1 bit in that position.
3464 Cmp = DAG.getSetCC(
3465 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3466 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3467 ISD::SETEQ);
3468 } else if (PopCount == BB.Range) {
3469 // There is only one zero bit in the range, test for it directly.
3470 Cmp = DAG.getSetCC(
3471 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3472 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3473 } else {
3474 // Make desired shift
3475 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3476 DAG.getConstant(1, dl, VT), ShiftOp);
3477
3478 // Emit bit tests and jumps
3479 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3480 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3481 Cmp = DAG.getSetCC(
3482 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3483 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3484 }
3485
3486 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3487 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3488 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3489 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3490 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3491 // one as they are relative probabilities (and thus work more like weights),
3492 // and hence we need to normalize them to let the sum of them become one.
3493 SwitchBB->normalizeSuccProbs();
3494
3495 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3496 MVT::Other, getControlRoot(),
3497 Cmp, DAG.getBasicBlock(B.TargetBB));
3498
3499 // Avoid emitting unnecessary branches to the next block.
3500 if (NextMBB != NextBlock(SwitchBB))
3501 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3502 DAG.getBasicBlock(NextMBB));
3503
3504 DAG.setRoot(BrAnd);
3505}
3506
3507void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3508 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3509
3510 // Retrieve successors. Look through artificial IR level blocks like
3511 // catchswitch for successors.
3512 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3513 const BasicBlock *EHPadBB = I.getSuccessor(1);
3514 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3515
3516 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3517 // have to do anything here to lower funclet bundles.
3518 failForInvalidBundles(I, "invokes",
3524
3525 const Value *Callee(I.getCalledOperand());
3526 const Function *Fn = dyn_cast<Function>(Callee);
3527 if (isa<InlineAsm>(Callee))
3528 visitInlineAsm(I, EHPadBB);
3529 else if (Fn && Fn->isIntrinsic()) {
3530 switch (Fn->getIntrinsicID()) {
3531 default:
3532 llvm_unreachable("Cannot invoke this intrinsic");
3533 case Intrinsic::donothing:
3534 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3535 case Intrinsic::seh_try_begin:
3536 case Intrinsic::seh_scope_begin:
3537 case Intrinsic::seh_try_end:
3538 case Intrinsic::seh_scope_end:
3539 if (EHPadMBB)
3540 // a block referenced by EH table
3541 // so dtor-funclet not removed by opts
3542 EHPadMBB->setMachineBlockAddressTaken();
3543 break;
3544 case Intrinsic::experimental_patchpoint_void:
3545 case Intrinsic::experimental_patchpoint:
3546 visitPatchpoint(I, EHPadBB);
3547 break;
3548 case Intrinsic::experimental_gc_statepoint:
3550 break;
3551 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3552 // but these intrinsics are special because they can be invoked, so we
3553 // manually lower it to a DAG node here.
3554 case Intrinsic::wasm_throw: {
3556 std::array<SDValue, 4> Ops = {
3557 getControlRoot(), // inchain for the terminator node
3558 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3559 TLI.getPointerTy(DAG.getDataLayout())),
3560 getValue(I.getArgOperand(0)), // tag
3561 getValue(I.getArgOperand(1)) // thrown value
3562 };
3563 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3564 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3565 break;
3566 }
3567 case Intrinsic::wasm_rethrow: {
3568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3569 std::array<SDValue, 2> Ops = {
3570 getControlRoot(), // inchain for the terminator node
3571 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3572 TLI.getPointerTy(DAG.getDataLayout()))};
3573 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3574 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3575 break;
3576 }
3577 // EH labels mark it as an invoke site, like a call.
3578 case Intrinsic::bpf_unwind_exit: {
3579 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3580 MCSymbol *BeginLabel;
3581 std::array<SDValue, 2> Ops = {
3582 lowerStartEH(getControlRoot(), EHPadBB, BeginLabel),
3583 DAG.getTargetConstant(Intrinsic::bpf_unwind_exit, getCurSDLoc(),
3584 TLI.getPointerTy(DAG.getDataLayout()))};
3585 SDValue Chain =
3586 DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), MVT::Other, Ops);
3587 DAG.setRoot(lowerEndEH(Chain, &I, EHPadBB, BeginLabel));
3588 break;
3589 }
3590 }
3591 } else if (I.hasDeoptState()) {
3592 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3593 // Eventually we will support lowering the @llvm.experimental.deoptimize
3594 // intrinsic, and right now there are no plans to support other intrinsics
3595 // with deopt state.
3596 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3597 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3599 } else {
3600 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3601 }
3602
3603 // If the value of the invoke is used outside of its defining block, make it
3604 // available as a virtual register.
3605 // We already took care of the exported value for the statepoint instruction
3606 // during call to the LowerStatepoint.
3607 if (!isa<GCStatepointInst>(I)) {
3609 }
3610
3612 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3613 BranchProbability EHPadBBProb =
3614 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3616 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3617
3618 // Update successor info.
3619 addSuccessorWithProb(InvokeMBB, Return);
3620 for (auto &UnwindDest : UnwindDests) {
3621 UnwindDest.first->setIsEHPad();
3622 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3623 }
3624 InvokeMBB->normalizeSuccProbs();
3625
3626 // Drop into normal successor.
3627 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3628 DAG.getBasicBlock(Return)));
3629}
3630
3631/// The intrinsics currently supported by callbr are implicit control flow
3632/// intrinsics such as amdgcn.kill.
3633/// - they should be called (no "dontcall-" attributes)
3634/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3635/// - they do not need custom argument handling (no
3636/// TLI.CollectTargetIntrinsicOperands())
3637void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3638#ifndef NDEBUG
3640 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3641 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3642 assert(Infos.empty() && "Intrinsic touches memory");
3643#endif
3644
3645 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3646
3648 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3649 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3650
3651 // Create the node.
3652 SDValue Result =
3653 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3654 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3655
3656 setValue(&I, Result);
3657}
3658
3659void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3660 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3661
3662 if (I.isInlineAsm()) {
3663 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3664 // have to do anything here to lower funclet bundles.
3665 failForInvalidBundles(I, "callbrs",
3667 visitInlineAsm(I);
3668 } else {
3669 assert(!I.hasOperandBundles() &&
3670 "Can't have operand bundles for intrinsics");
3671 visitCallBrIntrinsic(I);
3672 }
3674
3675 // Retrieve successors.
3676 SmallPtrSet<BasicBlock *, 8> Dests;
3677 Dests.insert(I.getDefaultDest());
3678 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3679
3680 // Update successor info.
3681 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3682 // TODO: For most of the cases where there is an intrinsic callbr, we're
3683 // having exactly one indirect target, which will be unreachable. As soon as
3684 // this changes, we might need to enhance
3685 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3686 // intrinsic indirect branches.
3687 if (I.isInlineAsm()) {
3688 for (BasicBlock *Dest : I.getIndirectDests()) {
3689 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3690 Target->setIsInlineAsmBrIndirectTarget();
3691 // If we introduce a type of asm goto statement that is permitted to use
3692 // an indirect call instruction to jump to its labels, then we should add
3693 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3694 // target block as requiring a BTI.
3695
3696 Target->setLabelMustBeEmitted();
3697 // Don't add duplicate machine successors.
3698 if (Dests.insert(Dest).second)
3699 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3700 }
3701 }
3702 CallBrMBB->normalizeSuccProbs();
3703
3704 // Drop into default successor.
3705 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3706 MVT::Other, getControlRoot(),
3707 DAG.getBasicBlock(Return)));
3708}
3709
3710void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3711 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3712}
3713
3714void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3715 assert(FuncInfo.MBB->isEHPad() &&
3716 "Call to landingpad not in landing pad!");
3717
3718 // If there aren't registers to copy the values into (e.g., during SjLj
3719 // exceptions), then don't bother to create these DAG nodes.
3720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3721 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3722 if (TLI.getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn) ==
3723 0 &&
3725 PersonalityFn) == 0)
3726 return;
3727
3728 // If landingpad's return type is token type, we don't create DAG nodes
3729 // for its exception pointer and selector value. The extraction of exception
3730 // pointer or selector value from token type landingpads is not currently
3731 // supported.
3732 if (LP.getType()->isTokenTy())
3733 return;
3734
3735 // LangRef leaves the result type target-specific, so diagnose types this
3736 // lowering cannot represent instead of asserting.
3737 SDLoc dl = getCurSDLoc();
3739 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3740 *LP.getFunction(),
3741 "landingpad result type must be a struct of an exception pointer and "
3742 "an integer selector",
3743 dl.getDebugLoc()));
3744 setValueToPoison(&LP, dl);
3745 return;
3746 }
3747
3748 SmallVector<EVT, 2> ValueVTs;
3749 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3750 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3751
3752 // Get the two live-in registers as SDValues. The physregs have already been
3753 // copied into virtual registers.
3754 SDValue Ops[2];
3755 if (FuncInfo.ExceptionPointerVirtReg) {
3756 Ops[0] = DAG.getZExtOrTrunc(
3757 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3758 FuncInfo.ExceptionPointerVirtReg,
3759 TLI.getPointerTy(DAG.getDataLayout())),
3760 dl, ValueVTs[0]);
3761 } else {
3762 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3763 }
3764 Ops[1] = DAG.getZExtOrTrunc(
3765 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3766 FuncInfo.ExceptionSelectorVirtReg,
3767 TLI.getPointerTy(DAG.getDataLayout())),
3768 dl, ValueVTs[1]);
3769
3770 // Merge into one.
3771 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3772 DAG.getVTList(ValueVTs), Ops);
3773 setValue(&LP, Res);
3774}
3775
3778 // Update JTCases.
3779 for (JumpTableBlock &JTB : SL->JTCases)
3780 if (JTB.first.HeaderBB == First)
3781 JTB.first.HeaderBB = Last;
3782
3783 // Update BitTestCases.
3784 for (BitTestBlock &BTB : SL->BitTestCases)
3785 if (BTB.Parent == First)
3786 BTB.Parent = Last;
3787}
3788
3789void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3790 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3791
3792 // Update machine-CFG edges with unique successors.
3794 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3795 BasicBlock *BB = I.getSuccessor(i);
3796 bool Inserted = Done.insert(BB).second;
3797 if (!Inserted)
3798 continue;
3799
3800 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3801 addSuccessorWithProb(IndirectBrMBB, Succ);
3802 }
3803 IndirectBrMBB->normalizeSuccProbs();
3804
3806 MVT::Other, getControlRoot(),
3807 getValue(I.getAddress())));
3808}
3809
3810void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3811 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3812 DAG.getTarget().Options.NoTrapAfterNoreturn))
3813 return;
3814
3815 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3816}
3817
3818void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3819 SDNodeFlags Flags;
3820 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3821 Flags.copyFMF(*FPOp);
3822
3823 SDValue Op = getValue(I.getOperand(0));
3824 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3825 Op, Flags);
3826 setValue(&I, UnNodeValue);
3827}
3828
3829void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3830 SDNodeFlags Flags;
3831 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3832 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3833 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3834 }
3835 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3836 Flags.setExact(ExactOp->isExact());
3837 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3838 Flags.setDisjoint(DisjointOp->isDisjoint());
3839 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3840 Flags.copyFMF(*FPOp);
3841
3842 SDValue Op1 = getValue(I.getOperand(0));
3843 SDValue Op2 = getValue(I.getOperand(1));
3844 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3845 Op1, Op2, Flags);
3846 setValue(&I, BinNodeValue);
3847}
3848
3849void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3850 SDValue Op1 = getValue(I.getOperand(0));
3851 SDValue Op2 = getValue(I.getOperand(1));
3852
3853 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3854 Op1.getValueType(), DAG.getDataLayout());
3855
3856 // Coerce the shift amount to the right type if we can. This exposes the
3857 // truncate or zext to optimization early.
3858 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3860 "Unexpected shift type");
3861 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3862 }
3863
3864 bool nuw = false;
3865 bool nsw = false;
3866 bool exact = false;
3867
3868 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3869
3870 if (const OverflowingBinaryOperator *OFBinOp =
3872 nuw = OFBinOp->hasNoUnsignedWrap();
3873 nsw = OFBinOp->hasNoSignedWrap();
3874 }
3875 if (const PossiblyExactOperator *ExactOp =
3877 exact = ExactOp->isExact();
3878 }
3879 SDNodeFlags Flags;
3880 Flags.setExact(exact);
3881 Flags.setNoSignedWrap(nsw);
3882 Flags.setNoUnsignedWrap(nuw);
3883 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3884 Flags);
3885 setValue(&I, Res);
3886}
3887
3888void SelectionDAGBuilder::visitSDiv(const User &I) {
3889 SDValue Op1 = getValue(I.getOperand(0));
3890 SDValue Op2 = getValue(I.getOperand(1));
3891
3892 SDNodeFlags Flags;
3893 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3894 cast<PossiblyExactOperator>(&I)->isExact());
3895 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3896 Op2, Flags));
3897}
3898
3899void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3900 ICmpInst::Predicate predicate = I.getPredicate();
3901 SDValue Op1 = getValue(I.getOperand(0));
3902 SDValue Op2 = getValue(I.getOperand(1));
3903 ISD::CondCode Opcode = getICmpCondCode(predicate);
3904
3905 auto &TLI = DAG.getTargetLoweringInfo();
3906 EVT MemVT =
3907 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3908
3909 // If a pointer's DAG type is larger than its memory type then the DAG values
3910 // are zero-extended. This breaks signed comparisons so truncate back to the
3911 // underlying type before doing the compare.
3912 if (Op1.getValueType() != MemVT) {
3913 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3914 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3915 }
3916
3917 SDNodeFlags Flags;
3918 Flags.setSameSign(I.hasSameSign());
3919
3920 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3921 I.getType());
3922 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3923 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3924}
3925
3926void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3927 FCmpInst::Predicate predicate = I.getPredicate();
3928 SDValue Op1 = getValue(I.getOperand(0));
3929 SDValue Op2 = getValue(I.getOperand(1));
3930
3931 ISD::CondCode Condition = getFCmpCondCode(predicate);
3932 auto *FPMO = cast<FPMathOperator>(&I);
3933 if (FPMO->hasNoNaNs() ||
3934 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3935 Condition = getFCmpCodeWithoutNaN(Condition);
3936
3937 SDNodeFlags Flags;
3938 Flags.copyFMF(*FPMO);
3939
3940 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3941 I.getType());
3942 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3943 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3944}
3945
3946// Check if the condition of the select has one use or two users that are both
3947// selects with the same condition.
3948static bool hasOnlySelectUsers(const Value *Cond) {
3949 return llvm::all_of(Cond->users(), [](const Value *V) {
3950 return isa<SelectInst>(V);
3951 });
3952}
3953
3954void SelectionDAGBuilder::visitSelect(const User &I) {
3955 SmallVector<EVT, 4> ValueVTs;
3956 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3957 ValueVTs);
3958 unsigned NumValues = ValueVTs.size();
3959 if (NumValues == 0) return;
3960
3962 SDValue Cond = getValue(I.getOperand(0));
3963 SDValue LHSVal = getValue(I.getOperand(1));
3964 SDValue RHSVal = getValue(I.getOperand(2));
3965 SmallVector<SDValue, 1> BaseOps(1, Cond);
3967 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3968
3969 bool IsUnaryAbs = false;
3970 bool Negate = false;
3971
3972 SDNodeFlags Flags;
3973 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3974 Flags.copyFMF(*FPOp);
3975
3976 Flags.setUnpredictable(
3977 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3978
3979 // Min/max matching is only viable if all output VTs are the same.
3980 if (all_equal(ValueVTs)) {
3981 EVT VT = ValueVTs[0];
3982 LLVMContext &Ctx = *DAG.getContext();
3983 auto &TLI = DAG.getTargetLoweringInfo();
3984
3985 // We care about the legality of the operation after it has been type
3986 // legalized.
3988 VT = TLI.getTypeToTransformTo(Ctx, VT);
3989
3990 // If the vselect is legal, assume we want to leave this as a vector setcc +
3991 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3992 // min/max is legal on the scalar type.
3993 bool UseScalarMinMax = VT.isVector() &&
3995
3996 // ValueTracking's select pattern matching does not account for -0.0,
3997 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3998 // -0.0 is less than +0.0.
3999 const Value *LHS, *RHS;
4000 auto SPR = matchSelectPattern(&I, LHS, RHS);
4002 switch (SPR.Flavor) {
4003 case SPF_UMAX: Opc = ISD::UMAX; break;
4004 case SPF_UMIN: Opc = ISD::UMIN; break;
4005 case SPF_SMAX: Opc = ISD::SMAX; break;
4006 case SPF_SMIN: Opc = ISD::SMIN; break;
4007 case SPF_FMINNUM:
4009 break;
4010
4011 switch (SPR.NaNBehavior) {
4012 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4013 case SPNB_RETURNS_ANY:
4014 case SPNB_RETURNS_NAN:
4015 break;
4016 case SPNB_RETURNS_OTHER:
4018 Flags.setNoSignedZeros(true);
4019 break;
4020 }
4021 break;
4022 case SPF_FMAXNUM:
4024 break;
4025
4026 switch (SPR.NaNBehavior) {
4027 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4028 case SPNB_RETURNS_NAN:
4029 case SPNB_RETURNS_ANY:
4030 break;
4031 case SPNB_RETURNS_OTHER:
4033 Flags.setNoSignedZeros(true);
4034 break;
4035 }
4036 break;
4037 case SPF_NABS:
4038 Negate = true;
4039 [[fallthrough]];
4040 case SPF_ABS:
4041 IsUnaryAbs = true;
4042 Opc = ISD::ABS;
4043 break;
4044 default: break;
4045 }
4046
4047 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
4049 (UseScalarMinMax &&
4051 // If the underlying comparison instruction is used by any other
4052 // instruction, the consumed instructions won't be destroyed, so it is
4053 // not profitable to convert to a min/max.
4055 OpCode = Opc;
4056 LHSVal = getValue(LHS);
4057 RHSVal = getValue(RHS);
4058 BaseOps.clear();
4059 }
4060
4061 if (IsUnaryAbs) {
4062 OpCode = Opc;
4063 LHSVal = getValue(LHS);
4064 BaseOps.clear();
4065 }
4066 }
4067
4068 if (IsUnaryAbs) {
4069 for (unsigned i = 0; i != NumValues; ++i) {
4070 SDLoc dl = getCurSDLoc();
4071 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
4072 Values[i] =
4073 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
4074 if (Negate)
4075 Values[i] = DAG.getNegative(Values[i], dl, VT);
4076 }
4077 } else {
4078 for (unsigned i = 0; i != NumValues; ++i) {
4079 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
4080 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
4081 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
4082 Values[i] = DAG.getNode(
4083 OpCode, getCurSDLoc(),
4084 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
4085 }
4086 }
4087
4089 DAG.getVTList(ValueVTs), Values));
4090}
4091
4092void SelectionDAGBuilder::visitTrunc(const User &I) {
4093 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4094 SDValue N = getValue(I.getOperand(0));
4095 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4096 I.getType());
4097 SDNodeFlags Flags;
4098 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4099 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4100 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4101 }
4102
4103 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4104}
4105
4106void SelectionDAGBuilder::visitZExt(const User &I) {
4107 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4108 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4109 SDValue N = getValue(I.getOperand(0));
4110 auto &TLI = DAG.getTargetLoweringInfo();
4111 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4112
4113 SDNodeFlags Flags;
4114 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4115 Flags.setNonNeg(PNI->hasNonNeg());
4116
4117 // Eagerly use nonneg information to canonicalize towards sign_extend if
4118 // that is the target's preference.
4119 // TODO: Let the target do this later.
4120 if (Flags.hasNonNeg() &&
4121 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4122 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4123 return;
4124 }
4125
4126 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4127}
4128
4129void SelectionDAGBuilder::visitSExt(const User &I) {
4130 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4131 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4132 SDValue N = getValue(I.getOperand(0));
4133 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4134 I.getType());
4135 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4136}
4137
4138void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4139 // FPTrunc is never a no-op cast, no need to check
4140 SDValue N = getValue(I.getOperand(0));
4141 SDLoc dl = getCurSDLoc();
4142 SDNodeFlags Flags;
4143 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4144 Flags.copyFMF(*FPOp);
4145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4146 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4147 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4148 DAG.getTargetConstant(
4149 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4150 Flags));
4151}
4152
4153void SelectionDAGBuilder::visitFPExt(const User &I) {
4154 // FPExt is never a no-op cast, no need to check
4155 SDValue N = getValue(I.getOperand(0));
4156 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4157 I.getType());
4158 SDNodeFlags Flags;
4159 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4160 Flags.copyFMF(*FPOp);
4161 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4162}
4163
4164void SelectionDAGBuilder::visitFPToUI(const User &I) {
4165 // FPToUI is never a no-op cast, no need to check
4166 SDValue N = getValue(I.getOperand(0));
4167 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4168 I.getType());
4169 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4170}
4171
4172void SelectionDAGBuilder::visitFPToSI(const User &I) {
4173 // FPToSI is never a no-op cast, no need to check
4174 SDValue N = getValue(I.getOperand(0));
4175 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4176 I.getType());
4177 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4178}
4179
4180void SelectionDAGBuilder::visitUIToFP(const User &I) {
4181 // UIToFP is never a no-op cast, no need to check
4182 SDValue N = getValue(I.getOperand(0));
4183 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4184 I.getType());
4185 SDNodeFlags Flags;
4186 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4187 Flags.copyFMF(*cast<FPMathOperator>(&I));
4188
4189 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4190}
4191
4192void SelectionDAGBuilder::visitSIToFP(const User &I) {
4193 // SIToFP is never a no-op cast, no need to check
4194 SDValue N = getValue(I.getOperand(0));
4195 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4196 I.getType());
4197 SDNodeFlags Flags;
4198 Flags.copyFMF(*cast<FPMathOperator>(&I));
4199
4200 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4201}
4202
4203void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4204 SDValue N = getValue(I.getOperand(0));
4205 // By definition the type of the ptrtoaddr must be equal to the address type.
4206 const auto &TLI = DAG.getTargetLoweringInfo();
4207 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4208 // The address width must be smaller or equal to the pointer representation
4209 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4210 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4211 setValue(&I, N);
4212}
4213
4214void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4215 // What to do depends on the size of the integer and the size of the pointer.
4216 // We can either truncate, zero extend, or no-op, accordingly.
4217 SDValue N = getValue(I.getOperand(0));
4218 auto &TLI = DAG.getTargetLoweringInfo();
4219 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4220 I.getType());
4221 EVT PtrMemVT =
4222 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4223 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4224 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4225 setValue(&I, N);
4226}
4227
4228void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4229 // What to do depends on the size of the integer and the size of the pointer.
4230 // We can either truncate, zero extend, or no-op, accordingly.
4231 SDValue N = getValue(I.getOperand(0));
4232 auto &TLI = DAG.getTargetLoweringInfo();
4233 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4234 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4235 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4236 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4237 setValue(&I, N);
4238}
4239
4240void SelectionDAGBuilder::visitBitCast(const User &I) {
4241 SDValue N = getValue(I.getOperand(0));
4242 SDLoc dl = getCurSDLoc();
4243 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4244 Type *SrcTy = I.getOperand(0)->getType();
4245 Type *DestTy = I.getType();
4246 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), DestTy);
4247
4248 // A pointer may be wider in a register than in memory. A bitcast between a
4249 // pointer and a byte type uses the memory type, like ptrtoint and inttoptr.
4250 if (SrcTy->isPtrOrPtrVectorTy() && !DestTy->isPtrOrPtrVectorTy()) {
4251 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), SrcTy);
4252 N = DAG.getPtrExtOrTrunc(N, dl, PtrMemVT);
4253 N = DAG.getBitcast(DestVT, N);
4254 setValue(&I, N);
4255 return;
4256 }
4257 if (DestTy->isPtrOrPtrVectorTy() && !SrcTy->isPtrOrPtrVectorTy()) {
4258 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), DestTy);
4259 N = DAG.getBitcast(PtrMemVT, N);
4260 N = DAG.getPtrExtOrTrunc(N, dl, DestVT);
4261 setValue(&I, N);
4262 return;
4263 }
4264
4265 // BitCast assures us that source and destination are the same size so this is
4266 // either a BITCAST or a no-op.
4267 if (DestVT != N.getValueType())
4268 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4269 DestVT, N)); // convert types.
4270 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4271 // might fold any kind of constant expression to an integer constant and that
4272 // is not what we are looking for. Only recognize a bitcast of a genuine
4273 // constant integer as an opaque constant.
4274 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4275 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4276 /*isOpaque*/true));
4277 else
4278 setValue(&I, N); // noop cast.
4279}
4280
4281void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4282 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4283 const Value *SV = I.getOperand(0);
4284 SDValue N = getValue(SV);
4285 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4286
4287 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4288 unsigned DestAS = I.getType()->getPointerAddressSpace();
4289
4290 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(), SrcAS, DestAS)) {
4291 SDNodeFlags Flags;
4292 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4293 Flags.setNonNull(ASC->hasNonNull());
4294 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4295 }
4296
4297 setValue(&I, N);
4298}
4299
4300void SelectionDAGBuilder::visitInsertElement(const User &I) {
4301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4302 SDValue InVec = getValue(I.getOperand(0));
4303 SDValue InVal = getValue(I.getOperand(1));
4304 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4305 TLI.getVectorIdxTy(DAG.getDataLayout()));
4307 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4308 InVec, InVal, InIdx));
4309}
4310
4311void SelectionDAGBuilder::visitBitInsert(const User &I) {
4312 SDValue Base = getValue(I.getOperand(0));
4313 SDValue Val = getValue(I.getOperand(1));
4314 SDValue Offset = getValue(I.getOperand(2));
4315 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4316 SDLoc dl = getCurSDLoc();
4317
4318 // A pointer may be wider in a register than in memory. Truncate it to its
4319 // memory type before inserting it, like ptrtoint.
4320 Type *ValTy = I.getOperand(1)->getType();
4321 if (ValTy->isPtrOrPtrVectorTy()) {
4322 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), ValTy);
4323 Val = DAG.getPtrExtOrTrunc(Val, dl, PtrMemVT);
4324 }
4325
4326 EVT BaseVT = Base.getValueType();
4327 EVT ValVT = Val.getValueType();
4328
4329 assert(BaseVT.getScalarSizeInBits() >= ValVT.getScalarSizeInBits() &&
4330 "bitinsert val wider than base should be rejected by verifier");
4331
4332 // If Val is a float, cast it to an integer of the same bitwidth
4333 // so DAG.getZExtOrTrunc can process it safely.
4334 if (!ValVT.isInteger()) {
4335 ValVT = ValVT.changeTypeToInteger();
4336 Val = DAG.getBitcast(ValVT, Val);
4337 }
4338
4339 // Legalize shift amount to the target's shift amount type.
4340 EVT ShiftAmtTy = TLI.getShiftAmountTy(BaseVT, DAG.getDataLayout());
4341 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4342
4343 unsigned BaseBitWidth = BaseVT.getScalarSizeInBits();
4344 unsigned ValBitWidth = ValVT.getScalarSizeInBits();
4345 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4346 SDValue ShiftedMask =
4347 DAG.getNode(ISD::SHL, dl, BaseVT, DAG.getConstant(InsertMask, dl, BaseVT),
4348 LegalShiftAmount);
4349 SDValue ClearMask = DAG.getNOT(dl, ShiftedMask, BaseVT);
4350 SDValue ClearedBase = DAG.getNode(ISD::AND, dl, BaseVT, Base, ClearMask);
4351
4352 SDValue ExtVal = DAG.getZExtOrTrunc(Val, dl, BaseVT);
4353 SDValue ShiftedVal =
4354 DAG.getNode(ISD::SHL, dl, BaseVT, ExtVal, LegalShiftAmount);
4355 SDValue Result = DAG.getNode(ISD::OR, dl, BaseVT, ClearedBase, ShiftedVal);
4356 setValue(&I, Result);
4357}
4358
4359void SelectionDAGBuilder::visitBitExtract(const User &I) {
4360 SDValue Src = getValue(I.getOperand(0));
4361 SDValue Offset = getValue(I.getOperand(1));
4362 EVT SrcVT = Src.getValueType();
4363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4364 SDLoc dl = getCurSDLoc();
4365 Type *ResultTy = I.getType();
4366
4367 // A pointer may be wider in a register than in memory. Extract it in its
4368 // memory type and extend it afterwards, like inttoptr.
4369 bool IsPtr = ResultTy->isPtrOrPtrVectorTy();
4370 EVT ResultVT = IsPtr ? TLI.getMemValueType(DAG.getDataLayout(), ResultTy)
4371 : TLI.getValueType(DAG.getDataLayout(), ResultTy);
4372
4373 assert(ResultVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
4374 "bitextract result wider than source should be rejected by verifier");
4375
4376 // Legalize shift amount to the target's shift amount type.
4377 EVT ShiftAmtTy = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
4378 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4379
4380 // Shift right by Offset - brings target field to bit 0
4381 SDValue Shifted = DAG.getNode(ISD::SRL, dl, SrcVT, Src, LegalShiftAmount);
4382
4384 if (!ResultVT.isInteger()) {
4385 // Drop into the integer domain to safely truncate the shifted bits
4386 EVT IntResultVT = ResultVT.changeTypeToInteger();
4387 Result = DAG.getNode(ISD::TRUNCATE, dl, IntResultVT, Shifted);
4388 Result = DAG.getBitcast(ResultVT, Result);
4389 } else {
4390 // Normal integer path
4391 Result = DAG.getNode(ISD::TRUNCATE, dl, ResultVT, Shifted);
4392 }
4393
4394 if (IsPtr) {
4395 EVT PtrVT = TLI.getValueType(DAG.getDataLayout(), ResultTy);
4396 Result = DAG.getPtrExtOrTrunc(Result, dl, PtrVT);
4397 }
4398
4399 setValue(&I, Result);
4400}
4401
4402void SelectionDAGBuilder::visitExtractElement(const User &I) {
4403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4404 SDValue InVec = getValue(I.getOperand(0));
4405 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4406 TLI.getVectorIdxTy(DAG.getDataLayout()));
4408 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4409 InVec, InIdx));
4410}
4411
4412void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4413 SDValue Src1 = getValue(I.getOperand(0));
4414 SDValue Src2 = getValue(I.getOperand(1));
4415 ArrayRef<int> Mask;
4416 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4417 Mask = SVI->getShuffleMask();
4418 else
4419 Mask = cast<ConstantExpr>(I).getShuffleMask();
4420 SDLoc DL = getCurSDLoc();
4421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4422 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4423 EVT SrcVT = Src1.getValueType();
4424
4425 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4426 // Canonical splat form of first element of first input vector.
4427 SDValue FirstElt =
4428 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4429 DAG.getVectorIdxConstant(0, DL));
4430 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4431 return;
4432 }
4433
4434 // For now, we only handle splats for scalable vectors.
4435 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4436 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4437 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4438
4439 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4440 unsigned MaskNumElts = Mask.size();
4441
4442 if (SrcNumElts == MaskNumElts) {
4443 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4444 return;
4445 }
4446
4447 // Normalize the shuffle vector since mask and vector length don't match.
4448 if (SrcNumElts < MaskNumElts) {
4449 // Mask is longer than the source vectors. We can use concatenate vector to
4450 // make the mask and vectors lengths match.
4451
4452 if (MaskNumElts % SrcNumElts == 0) {
4453 // Mask length is a multiple of the source vector length.
4454 // Check if the shuffle is some kind of concatenation of the input
4455 // vectors.
4456 unsigned NumConcat = MaskNumElts / SrcNumElts;
4457 bool IsConcat = true;
4458 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4459 for (unsigned i = 0; i != MaskNumElts; ++i) {
4460 int Idx = Mask[i];
4461 if (Idx < 0)
4462 continue;
4463 // Ensure the indices in each SrcVT sized piece are sequential and that
4464 // the same source is used for the whole piece.
4465 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4466 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4467 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4468 IsConcat = false;
4469 break;
4470 }
4471 // Remember which source this index came from.
4472 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4473 }
4474
4475 // The shuffle is concatenating multiple vectors together. Just emit
4476 // a CONCAT_VECTORS operation.
4477 if (IsConcat) {
4478 SmallVector<SDValue, 8> ConcatOps;
4479 for (auto Src : ConcatSrcs) {
4480 if (Src < 0)
4481 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4482 else if (Src == 0)
4483 ConcatOps.push_back(Src1);
4484 else
4485 ConcatOps.push_back(Src2);
4486 }
4487 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4488 return;
4489 }
4490 }
4491
4492 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4493 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4494 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4495 PaddedMaskNumElts);
4496
4497 // Pad both vectors with undefs to make them the same length as the mask.
4498 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4499
4500 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4501 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4502 MOps1[0] = Src1;
4503 MOps2[0] = Src2;
4504
4505 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4506 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4507
4508 // Readjust mask for new input vector length.
4509 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4510 for (unsigned i = 0; i != MaskNumElts; ++i) {
4511 int Idx = Mask[i];
4512 if (Idx >= (int)SrcNumElts)
4513 Idx -= SrcNumElts - PaddedMaskNumElts;
4514 MappedOps[i] = Idx;
4515 }
4516
4517 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4518
4519 // If the concatenated vector was padded, extract a subvector with the
4520 // correct number of elements.
4521 if (MaskNumElts != PaddedMaskNumElts)
4522 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4523 DAG.getVectorIdxConstant(0, DL));
4524
4525 setValue(&I, Result);
4526 return;
4527 }
4528
4529 assert(SrcNumElts > MaskNumElts);
4530
4531 // Analyze the access pattern of the vector to see if we can extract
4532 // two subvectors and do the shuffle.
4533 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4534 bool CanExtract = true;
4535 for (int Idx : Mask) {
4536 unsigned Input = 0;
4537 if (Idx < 0)
4538 continue;
4539
4540 if (Idx >= (int)SrcNumElts) {
4541 Input = 1;
4542 Idx -= SrcNumElts;
4543 }
4544
4545 // If all the indices come from the same MaskNumElts sized portion of
4546 // the sources we can use extract. Also make sure the extract wouldn't
4547 // extract past the end of the source.
4548 int NewStartIdx = alignDown(Idx, MaskNumElts);
4549 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4550 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4551 CanExtract = false;
4552 // Make sure we always update StartIdx as we use it to track if all
4553 // elements are undef.
4554 StartIdx[Input] = NewStartIdx;
4555 }
4556
4557 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4558 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4559 return;
4560 }
4561 if (CanExtract) {
4562 // Extract appropriate subvector and generate a vector shuffle
4563 for (unsigned Input = 0; Input < 2; ++Input) {
4564 SDValue &Src = Input == 0 ? Src1 : Src2;
4565 if (StartIdx[Input] < 0)
4566 Src = DAG.getUNDEF(VT);
4567 else {
4568 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4569 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4570 }
4571 }
4572
4573 // Calculate new mask.
4574 SmallVector<int, 8> MappedOps(Mask);
4575 for (int &Idx : MappedOps) {
4576 if (Idx >= (int)SrcNumElts)
4577 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4578 else if (Idx >= 0)
4579 Idx -= StartIdx[0];
4580 }
4581
4582 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4583 return;
4584 }
4585
4586 // We can't use either concat vectors or extract subvectors so fall back to
4587 // replacing the shuffle with extract and build vector.
4588 // to insert and build vector.
4589 EVT EltVT = VT.getVectorElementType();
4591 for (int Idx : Mask) {
4592 SDValue Res;
4593
4594 if (Idx < 0) {
4595 Res = DAG.getUNDEF(EltVT);
4596 } else {
4597 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4598 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4599
4600 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4601 DAG.getVectorIdxConstant(Idx, DL));
4602 }
4603
4604 Ops.push_back(Res);
4605 }
4606
4607 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4608}
4609
4610void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4611 ArrayRef<unsigned> Indices = I.getIndices();
4612 const Value *Op0 = I.getOperand(0);
4613 const Value *Op1 = I.getOperand(1);
4614 Type *AggTy = I.getType();
4615 Type *ValTy = Op1->getType();
4616 bool IntoUndef = isa<UndefValue>(Op0);
4617 bool FromUndef = isa<UndefValue>(Op1);
4618
4619 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4620
4621 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4622 SmallVector<EVT, 4> AggValueVTs;
4623 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4624 SmallVector<EVT, 4> ValValueVTs;
4625 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4626
4627 unsigned NumAggValues = AggValueVTs.size();
4628 unsigned NumValValues = ValValueVTs.size();
4629 SmallVector<SDValue, 4> Values(NumAggValues);
4630
4631 // Ignore an insertvalue that produces an empty object
4632 if (!NumAggValues) {
4633 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4634 return;
4635 }
4636
4637 SDValue Agg = getValue(Op0);
4638 unsigned i = 0;
4639 // Copy the beginning value(s) from the original aggregate.
4640 for (; i != LinearIndex; ++i)
4641 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4642 SDValue(Agg.getNode(), Agg.getResNo() + i);
4643 // Copy values from the inserted value(s).
4644 if (NumValValues) {
4645 SDValue Val = getValue(Op1);
4646 for (; i != LinearIndex + NumValValues; ++i)
4647 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4648 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4649 }
4650 // Copy remaining value(s) from the original aggregate.
4651 for (; i != NumAggValues; ++i)
4652 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4653 SDValue(Agg.getNode(), Agg.getResNo() + i);
4654
4656 DAG.getVTList(AggValueVTs), Values));
4657}
4658
4659void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4660 ArrayRef<unsigned> Indices = I.getIndices();
4661 const Value *Op0 = I.getOperand(0);
4662 Type *AggTy = Op0->getType();
4663 Type *ValTy = I.getType();
4664 bool OutOfUndef = isa<UndefValue>(Op0);
4665
4666 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4667
4668 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4669 SmallVector<EVT, 4> ValValueVTs;
4670 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4671
4672 unsigned NumValValues = ValValueVTs.size();
4673
4674 // Ignore a extractvalue that produces an empty object
4675 if (!NumValValues) {
4676 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4677 return;
4678 }
4679
4680 SmallVector<SDValue, 4> Values(NumValValues);
4681
4682 SDValue Agg = getValue(Op0);
4683 // Copy out the selected value(s).
4684 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4685 Values[i - LinearIndex] =
4686 OutOfUndef ?
4687 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4688 SDValue(Agg.getNode(), Agg.getResNo() + i);
4689
4691 DAG.getVTList(ValValueVTs), Values));
4692}
4693
4694void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4695 Value *Op0 = I.getOperand(0);
4696 // Note that the pointer operand may be a vector of pointers. Take the scalar
4697 // element which holds a pointer.
4698 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4699 SDValue N = getValue(Op0);
4700 SDLoc dl = getCurSDLoc();
4701 auto &TLI = DAG.getTargetLoweringInfo();
4702 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4703
4704 // For a vector GEP, keep the prefix scalar as long as possible, then
4705 // convert any scalars encountered after the first vector operand to vectors.
4706 bool IsVectorGEP = I.getType()->isVectorTy();
4707 ElementCount VectorElementCount =
4708 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4710
4712 GTI != E; ++GTI) {
4713 const Value *Idx = GTI.getOperand();
4714 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4715 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4716 if (Field) {
4717 // N = N + Offset
4719 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4720
4721 // In an inbounds GEP with an offset that is nonnegative even when
4722 // interpreted as signed, assume there is no unsigned overflow.
4723 SDNodeFlags Flags;
4724 if (NW.hasNoUnsignedWrap() ||
4725 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4727 Flags.setInBounds(NW.isInBounds());
4728
4729 N = DAG.getMemBasePlusOffset(
4730 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4731 }
4732 } else {
4733 // IdxSize is the width of the arithmetic according to IR semantics.
4734 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4735 // (and fix up the result later).
4736 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4737 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4738 TypeSize ElementSize =
4739 GTI.getSequentialElementStride(DAG.getDataLayout());
4740 // We intentionally mask away the high bits here; ElementSize may not
4741 // fit in IdxTy.
4742 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4743 /*isSigned=*/false, /*implicitTrunc=*/true);
4744 bool ElementScalable = ElementSize.isScalable();
4745
4746 // If this is a scalar constant or a splat vector of constants,
4747 // handle it quickly.
4748 const auto *C = dyn_cast<Constant>(Idx);
4749 if (C && isa<VectorType>(C->getType()))
4750 C = C->getSplatValue();
4751
4752 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4753 if (CI && CI->isZero())
4754 continue;
4755 if (CI && !ElementScalable) {
4756 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4757 LLVMContext &Context = *DAG.getContext();
4758 SDValue OffsVal;
4759 if (N.getValueType().isVector())
4760 OffsVal = DAG.getConstant(
4761 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4762 else
4763 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4764
4765 // In an inbounds GEP with an offset that is nonnegative even when
4766 // interpreted as signed, assume there is no unsigned overflow.
4767 SDNodeFlags Flags;
4768 if (NW.hasNoUnsignedWrap() ||
4769 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4770 Flags.setNoUnsignedWrap(true);
4771 Flags.setInBounds(NW.isInBounds());
4772
4773 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4774
4775 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4776 continue;
4777 }
4778
4779 // N = N + Idx * ElementMul;
4780 SDValue IdxN = getValue(Idx);
4781
4782 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4783 if (N.getValueType().isVector()) {
4784 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4785 VectorElementCount);
4786 IdxN = DAG.getSplat(VT, dl, IdxN);
4787 } else {
4788 EVT VT =
4789 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4790 N = DAG.getSplat(VT, dl, N);
4791 }
4792 }
4793
4794 // If the index is smaller or larger than intptr_t, truncate or extend
4795 // it.
4796 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4797
4798 SDNodeFlags ScaleFlags;
4799 // The multiplication of an index by the type size does not wrap the
4800 // pointer index type in a signed sense (mul nsw).
4802
4803 // The multiplication of an index by the type size does not wrap the
4804 // pointer index type in an unsigned sense (mul nuw).
4805 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4806
4807 if (ElementScalable) {
4808 EVT VScaleTy = N.getValueType().getScalarType();
4809 SDValue VScale = DAG.getNode(
4810 ISD::VSCALE, dl, VScaleTy,
4811 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4812 if (N.getValueType().isVector())
4813 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4814 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4815 ScaleFlags);
4816 } else {
4817 // If this is a multiply by a power of two, turn it into a shl
4818 // immediately. This is a very common case.
4819 if (ElementMul != 1) {
4820 if (ElementMul.isPowerOf2()) {
4821 unsigned Amt = ElementMul.logBase2();
4822 IdxN = DAG.getNode(
4823 ISD::SHL, dl, N.getValueType(), IdxN,
4824 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4825 ScaleFlags);
4826 } else {
4827 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4828 IdxN.getValueType());
4829 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4830 ScaleFlags);
4831 }
4832 }
4833 }
4834
4835 // The successive addition of the current address, truncated to the
4836 // pointer index type and interpreted as an unsigned number, and each
4837 // offset, also interpreted as an unsigned number, does not wrap the
4838 // pointer index type (add nuw).
4839 SDNodeFlags AddFlags;
4840 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4841 AddFlags.setInBounds(NW.isInBounds());
4842
4843 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4844 }
4845 }
4846
4847 if (IsVectorGEP && !N.getValueType().isVector()) {
4848 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4849 N = DAG.getSplat(VT, dl, N);
4850 }
4851
4852 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4853 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4854 if (IsVectorGEP) {
4855 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4856 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4857 }
4858
4859 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4860 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4861
4862 setValue(&I, N);
4863}
4864
4865void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4866 // If this is a fixed sized alloca in the entry block of the function,
4867 // allocate it statically on the stack.
4868 if (FuncInfo.StaticAllocaMap.count(&I))
4869 return; // getValue will auto-populate this.
4870
4871 SDLoc dl = getCurSDLoc();
4872 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4873 auto &DL = DAG.getDataLayout();
4874 TypeSize TySize = I.getAllocationBaseSize(DL);
4875 MaybeAlign Alignment = I.getAlign();
4876
4877 SDValue AllocSize = getValue(I.getArraySize());
4878
4879 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4880 if (AllocSize.getValueType() != IntPtr)
4881 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4882
4883 AllocSize = DAG.getNode(
4884 ISD::MUL, dl, IntPtr, AllocSize,
4885 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4886
4887 // Handle alignment. If the requested alignment is less than or equal to
4888 // the stack alignment, ignore it. If the size is greater than or equal to
4889 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4890 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4891 if (*Alignment <= StackAlign)
4892 Alignment = std::nullopt;
4893
4894 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4895 // Round the size of the allocation up to the stack alignment size
4896 // by add SA-1 to the size. This doesn't overflow because we're computing
4897 // an address inside an alloca.
4898 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4899 DAG.getConstant(StackAlignMask, dl, IntPtr),
4901
4902 // Mask out the low bits for alignment purposes.
4903 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4904 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4905
4906 SDValue Ops[] = {
4907 getRoot(), AllocSize,
4908 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4909 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4910 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4911 setValue(&I, DSA);
4912 DAG.setRoot(DSA.getValue(1));
4913
4914 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4915}
4916
4917static const MDNode *getRangeMetadata(const Instruction &I) {
4918 return I.getMetadata(LLVMContext::MD_range);
4919}
4920
4921static std::optional<ConstantRange> getRange(const Instruction &I) {
4922 if (const auto *CB = dyn_cast<CallBase>(&I))
4923 if (std::optional<ConstantRange> CR = CB->getRange())
4924 return CR;
4925 if (const MDNode *Range = getRangeMetadata(I))
4927 return std::nullopt;
4928}
4929
4931 if (const auto *CB = dyn_cast<CallBase>(&I))
4932 return CB->getRetNoFPClass();
4933 return fcNone;
4934}
4935
4936void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4937 if (I.isAtomic())
4938 return visitAtomicLoad(I);
4939
4940 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4941 const Value *SV = I.getOperand(0);
4942 if (TLI.supportSwiftError()) {
4943 // Swifterror values can come from either a function parameter with
4944 // swifterror attribute or an alloca with swifterror attribute.
4945 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4946 if (Arg->hasSwiftErrorAttr())
4947 return visitLoadFromSwiftError(I);
4948 }
4949
4950 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4951 if (Alloca->isSwiftError())
4952 return visitLoadFromSwiftError(I);
4953 }
4954 }
4955
4956 SDValue Ptr = getValue(SV);
4957
4958 Type *Ty = I.getType();
4959 SmallVector<EVT, 4> ValueVTs, MemVTs;
4961 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4962 unsigned NumValues = ValueVTs.size();
4963 if (NumValues == 0)
4964 return;
4965
4966 Align Alignment = I.getAlign();
4967 AAMDNodes AAInfo = I.getAAMetadata();
4968 const MDNode *Ranges = getRangeMetadata(I);
4969 const MDNode *MemCacheHint = getMemCacheHint(I);
4970 bool isVolatile = I.isVolatile();
4971 MachineMemOperand::Flags MMOFlags =
4972 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4973
4974 SDValue Root;
4975 bool ConstantMemory = false;
4976 if (isVolatile)
4977 // Serialize volatile loads with other side effects.
4978 Root = getRoot();
4979 else if (NumValues > MaxParallelChains)
4980 Root = getMemoryRoot();
4981 else if (BatchAA &&
4982 BatchAA->pointsToConstantMemory(MemoryLocation(
4983 SV,
4984 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4985 AAInfo))) {
4986 // Do not serialize (non-volatile) loads of constant memory with anything.
4987 Root = DAG.getEntryNode();
4988 ConstantMemory = true;
4990 } else {
4991 // Do not serialize non-volatile loads against each other.
4992 Root = DAG.getRoot();
4993 }
4994
4995 SDLoc dl = getCurSDLoc();
4996
4997 if (isVolatile)
4998 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4999
5001 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5002
5003 unsigned ChainI = 0;
5004 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5005 // Serializing loads here may result in excessive register pressure, and
5006 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
5007 // could recover a bit by hoisting nodes upward in the chain by recognizing
5008 // they are side-effect free or do not alias. The optimizer should really
5009 // avoid this case by converting large object/array copies to llvm.memcpy
5010 // (MaxParallelChains should always remain as failsafe).
5011 if (ChainI == MaxParallelChains) {
5012 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
5013 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5014 ArrayRef(Chains.data(), ChainI));
5015 Root = Chain;
5016 ChainI = 0;
5017 }
5018
5019 // TODO: MachinePointerInfo only supports a fixed length offset.
5020 MachinePointerInfo PtrInfo =
5021 !Offsets[i].isScalable() || Offsets[i].isZero()
5022 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
5023 : MachinePointerInfo();
5024
5025 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5026 SDValue L =
5027 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
5028 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5029 Chains[ChainI] = L.getValue(1);
5030
5031 if (MemVTs[i] != ValueVTs[i])
5032 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
5033
5034 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
5035 uint64_t FPTestInt =
5036 cast<ConstantInt>(
5037 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
5038 ->getZExtValue();
5039 if (FPTestInt != fcNone) {
5040 SDValue FPTestConst =
5041 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
5042 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
5043 FPTestConst);
5044 }
5045 }
5046 Values[i] = L;
5047 }
5048
5049 if (!ConstantMemory) {
5050 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5051 ArrayRef(Chains.data(), ChainI));
5052 if (isVolatile)
5053 DAG.setRoot(Chain);
5054 else
5055 PendingLoads.push_back(Chain);
5056 }
5057
5058 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
5059 DAG.getVTList(ValueVTs), Values));
5060}
5061
5062void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
5063 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5064 "call visitStoreToSwiftError when backend supports swifterror");
5065
5066 SmallVector<EVT, 4> ValueVTs;
5067 SmallVector<uint64_t, 4> Offsets;
5068 const Value *SrcV = I.getOperand(0);
5069 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5070 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5071 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5072 "expect a single EVT for swifterror");
5073
5074 SDValue Src = getValue(SrcV);
5075 // Create a virtual register, then update the virtual register.
5076 Register VReg =
5077 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
5078 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
5079 // Chain can be getRoot or getControlRoot.
5080 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
5081 SDValue(Src.getNode(), Src.getResNo()));
5082 DAG.setRoot(CopyNode);
5083}
5084
5085void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
5086 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5087 "call visitLoadFromSwiftError when backend supports swifterror");
5088
5089 assert(!I.isVolatile() &&
5090 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
5091 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
5092 "Support volatile, non temporal, invariant for load_from_swift_error");
5093
5094 const Value *SV = I.getOperand(0);
5095 Type *Ty = I.getType();
5096 assert(
5097 (!BatchAA ||
5098 !BatchAA->pointsToConstantMemory(MemoryLocation(
5099 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
5100 I.getAAMetadata()))) &&
5101 "load_from_swift_error should not be constant memory");
5102
5103 SmallVector<EVT, 4> ValueVTs;
5104 SmallVector<uint64_t, 4> Offsets;
5105 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
5106 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5107 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5108 "expect a single EVT for swifterror");
5109
5110 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
5111 SDValue L = DAG.getCopyFromReg(
5112 getRoot(), getCurSDLoc(),
5113 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
5114
5115 setValue(&I, L);
5116}
5117
5118void SelectionDAGBuilder::visitStore(const StoreInst &I) {
5119 if (I.isAtomic())
5120 return visitAtomicStore(I);
5121
5122 const Value *SrcV = I.getOperand(0);
5123 const Value *PtrV = I.getOperand(1);
5124
5125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5126 if (TLI.supportSwiftError()) {
5127 // Swifterror values can come from either a function parameter with
5128 // swifterror attribute or an alloca with swifterror attribute.
5129 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
5130 if (Arg->hasSwiftErrorAttr())
5131 return visitStoreToSwiftError(I);
5132 }
5133
5134 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
5135 if (Alloca->isSwiftError())
5136 return visitStoreToSwiftError(I);
5137 }
5138 }
5139
5140 SmallVector<EVT, 4> ValueVTs, MemVTs;
5142 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5143 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
5144 unsigned NumValues = ValueVTs.size();
5145 if (NumValues == 0)
5146 return;
5147
5148 // Get the lowered operands. Note that we do this after
5149 // checking if NumResults is zero, because with zero results
5150 // the operands won't have values in the map.
5151 SDValue Src = getValue(SrcV);
5152 SDValue Ptr = getValue(PtrV);
5153
5154 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
5155 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5156 SDLoc dl = getCurSDLoc();
5157 Align Alignment = I.getAlign();
5158 AAMDNodes AAInfo = I.getAAMetadata();
5159 const MDNode *MemCacheHint = getMemCacheHint(I, I.getPointerOperandIndex());
5160
5161 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5162
5163 unsigned ChainI = 0;
5164 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5165 // See visitLoad comments.
5166 if (ChainI == MaxParallelChains) {
5167 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5168 ArrayRef(Chains.data(), ChainI));
5169 Root = Chain;
5170 ChainI = 0;
5171 }
5172
5173 // TODO: MachinePointerInfo only supports a fixed length offset.
5174 MachinePointerInfo PtrInfo =
5175 !Offsets[i].isScalable() || Offsets[i].isZero()
5176 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
5177 : MachinePointerInfo();
5178
5179 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5180 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
5181 if (MemVTs[i] != ValueVTs[i])
5182 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
5183 SDValue St =
5184 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
5185 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
5186 Chains[ChainI] = St;
5187 }
5188
5189 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5190 ArrayRef(Chains.data(), ChainI));
5191 setValue(&I, StoreNode);
5192 DAG.setRoot(StoreNode);
5193}
5194
5195void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
5196 bool IsCompressing) {
5197 SDLoc sdl = getCurSDLoc();
5198
5199 Value *Src0Operand = I.getArgOperand(0);
5200 Value *PtrOperand = I.getArgOperand(1);
5201 Value *MaskOperand = I.getArgOperand(2);
5202 Align Alignment = I.getParamAlign(1).valueOrOne();
5203
5204 SDValue Ptr = getValue(PtrOperand);
5205 SDValue Src0 = getValue(Src0Operand);
5206 SDValue Mask = getValue(MaskOperand);
5207 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5208
5209 EVT VT = Src0.getValueType();
5210
5211 const auto &TLI = DAG.getTargetLoweringInfo();
5212
5213 auto MMOFlags = MachineMemOperand::MOStore;
5214 MMOFlags |= TLI.getTargetMMOFlags(I);
5215 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5217
5218 const MDNode *MemCacheHint = getMemCacheHint(I, /*OperandNo=*/1);
5219
5220 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5221 MachinePointerInfo(PtrOperand), MMOFlags,
5222 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5223 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5224
5225 SDValue StoreNode =
5226 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5227 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5228 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5229 Mask)
5230 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5231 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5232 IsCompressing);
5233 DAG.setRoot(StoreNode);
5234 setValue(&I, StoreNode);
5235}
5236
5237// Get a uniform base for the Gather/Scatter intrinsic.
5238// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5239// We try to represent it as a base pointer + vector of indices.
5240// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5241// The first operand of the GEP may be a single pointer or a vector of pointers
5242// Example:
5243// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5244// or
5245// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5246// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5247//
5248// When the first GEP operand is a single pointer - it is the uniform base we
5249// are looking for. If first operand of the GEP is a splat vector - we
5250// extract the splat value and use it as a uniform base.
5251// In all other cases the function returns 'false'.
5252static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5253 SDValue &Scale, SelectionDAGBuilder *SDB,
5254 const BasicBlock *CurBB, uint64_t ElemSize) {
5255 SelectionDAG& DAG = SDB->DAG;
5257 const DataLayout &DL = DAG.getDataLayout();
5258
5259 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5260
5261 // Handle splat constant pointer.
5262 if (auto *C = dyn_cast<Constant>(Ptr)) {
5263 C = C->getSplatValue();
5264 if (!C)
5265 return false;
5266
5267 Base = SDB->getValue(C);
5268
5269 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5270 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5271 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5272 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5273 return true;
5274 }
5275
5277 if (!GEP || GEP->getParent() != CurBB)
5278 return false;
5279
5280 if (GEP->getNumOperands() != 2)
5281 return false;
5282
5283 const Value *BasePtr = GEP->getPointerOperand();
5284 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5285
5286 // Make sure the base is scalar and the index is a vector.
5287 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5288 return false;
5289
5290 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5291 if (ScaleVal.isScalable())
5292 return false;
5293
5294 // Target may not support the required addressing mode.
5295 if (ScaleVal != 1 &&
5296 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5297 return false;
5298
5299 Base = SDB->getValue(BasePtr);
5300 Index = SDB->getValue(IndexVal);
5301
5302 Scale =
5303 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5304 return true;
5305}
5306
5307void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5308 SDLoc sdl = getCurSDLoc();
5309
5310 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5311 const Value *Ptr = I.getArgOperand(1);
5312 SDValue Src0 = getValue(I.getArgOperand(0));
5313 SDValue Mask = getValue(I.getArgOperand(2));
5314 EVT VT = Src0.getValueType();
5315 Align Alignment = I.getParamAlign(1).valueOrOne();
5316 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5317
5318 SDValue Base;
5319 SDValue Index;
5320 SDValue Scale;
5321 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5322 I.getParent(), VT.getScalarStoreSize());
5323
5324 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5325 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5326 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5327 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5328 if (!UniformBase) {
5329 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5330 Index = getValue(Ptr);
5331 Scale =
5332 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5333 }
5334
5335 EVT IdxVT = Index.getValueType();
5336 EVT EltTy = IdxVT.getVectorElementType();
5337 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5338 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5339 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5340 }
5341
5342 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5343 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5344 Ops, MMO, ISD::SIGNED_SCALED, false);
5345 DAG.setRoot(Scatter);
5346 setValue(&I, Scatter);
5347}
5348
5349void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5350 SDLoc sdl = getCurSDLoc();
5351
5352 Value *PtrOperand = I.getArgOperand(0);
5353 Value *MaskOperand = I.getArgOperand(1);
5354 Value *Src0Operand = I.getArgOperand(2);
5355 Align Alignment = I.getParamAlign(0).valueOrOne();
5356
5357 SDValue Ptr = getValue(PtrOperand);
5358 SDValue Src0 = getValue(Src0Operand);
5359 SDValue Mask = getValue(MaskOperand);
5360 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5361
5362 EVT VT = Src0.getValueType();
5363 AAMDNodes AAInfo = I.getAAMetadata();
5364 const MDNode *Ranges = getRangeMetadata(I);
5365 const MDNode *MemCacheHint = getMemCacheHint(I, /*OperandNo=*/0);
5366
5367 // Do not serialize masked loads of constant memory with anything.
5368 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5369 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5370
5371 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5372
5373 const auto &TLI = DAG.getTargetLoweringInfo();
5374
5375 auto MMOFlags = MachineMemOperand::MOLoad;
5376 MMOFlags |= TLI.getTargetMMOFlags(I);
5377 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5379 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5381
5382 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5383 MachinePointerInfo(PtrOperand), MMOFlags,
5384 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5385 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5386
5387 // The Load/Res may point to different values and both of them are output
5388 // variables.
5389 SDValue Load;
5390 SDValue Res;
5391 if (!IsExpanding &&
5392 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5393 /*IsStore=*/false))
5394 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5395 else
5396 Res = Load =
5397 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5398 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5399 if (AddToChain)
5400 PendingLoads.push_back(Load.getValue(1));
5401 setValue(&I, Res);
5402}
5403
5404void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5405 SDLoc sdl = getCurSDLoc();
5406 Value *PtrOperand = I.getArgOperand(0);
5407 // The remaining arguments (num_accessible_bytes or oracle function + args)
5408 // are IR-level semantics only; they are not needed at codegen.
5409 SDValue Ptr = getValue(PtrOperand);
5410
5411 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5412 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5413 Align Alignment = I.getParamAlign(0).valueOrOne();
5414 AAMDNodes AAInfo = I.getAAMetadata();
5415
5416 SDValue InChain = DAG.getRoot();
5417
5418 // Use MOLoad but NOT MODereferenceable - the memory may not be
5419 // fully dereferenceable.
5420 auto MMOFlags = MachineMemOperand::MOLoad;
5421 MMOFlags |= TLI.getTargetMMOFlags(I);
5422 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5424 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5426
5427 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5428 MachinePointerInfo(PtrOperand), MMOFlags,
5429 LocationSize::precise(VT.getStoreSize()), Alignment, AAInfo);
5430
5431 SDValue Load = DAG.getLoad(VT, sdl, InChain, Ptr, MMO);
5432 PendingLoads.push_back(Load.getValue(1));
5433 setValue(&I, Load);
5434}
5435
5436void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5437 SDLoc sdl = getCurSDLoc();
5438
5439 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5440 const Value *Ptr = I.getArgOperand(0);
5441 SDValue Src0 = getValue(I.getArgOperand(2));
5442 SDValue Mask = getValue(I.getArgOperand(1));
5443
5444 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5445 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5446 Align Alignment = I.getParamAlign(0).valueOrOne();
5447
5448 const MDNode *Ranges = getRangeMetadata(I);
5449
5450 SDValue Root = DAG.getRoot();
5451 SDValue Base;
5452 SDValue Index;
5453 SDValue Scale;
5454 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5455 I.getParent(), VT.getScalarStoreSize());
5456 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5457 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5458 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5460 MMOMetadata(I.getAAMetadata(), Ranges));
5461
5462 if (!UniformBase) {
5463 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5464 Index = getValue(Ptr);
5465 Scale =
5466 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5467 }
5468
5469 EVT IdxVT = Index.getValueType();
5470 EVT EltTy = IdxVT.getVectorElementType();
5471 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5472 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5473 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5474 }
5475
5476 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5477 SDValue Gather =
5478 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5480
5481 PendingLoads.push_back(Gather.getValue(1));
5482 setValue(&I, Gather);
5483}
5484
5485void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5486 SDLoc dl = getCurSDLoc();
5487 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5488 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5489 SyncScope::ID SSID = I.getSyncScopeID();
5490
5491 SDValue InChain = getRoot();
5492
5493 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5494 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5495
5496 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5497 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5498
5499 MachineFunction &MF = DAG.getMachineFunction();
5500 const MDNode *MemCacheHint = getMemCacheHint(I);
5501 MachineMemOperand *MMO = MF.getMachineMemOperand(
5502 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5503 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5504 SSID, SuccessOrdering, FailureOrdering);
5505
5507 dl, MemVT, VTs, InChain,
5508 getValue(I.getPointerOperand()),
5509 getValue(I.getCompareOperand()),
5510 getValue(I.getNewValOperand()), MMO);
5511
5512 SDValue OutChain = L.getValue(2);
5513
5514 setValue(&I, L);
5515 DAG.setRoot(OutChain);
5516}
5517
5518void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5519 SDLoc dl = getCurSDLoc();
5520 ISD::NodeType NT = getAtomicRMWOpcode(I.getOperation());
5521 AtomicOrdering Ordering = I.getOrdering();
5522 SyncScope::ID SSID = I.getSyncScopeID();
5523
5524 SDValue InChain = getRoot();
5525
5526 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5528 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5529
5530 MachineFunction &MF = DAG.getMachineFunction();
5531 const MDNode *MemCacheHint = getMemCacheHint(I);
5532 MachineMemOperand *MMO = MF.getMachineMemOperand(
5533 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5534 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5535 SSID, Ordering);
5536
5537 SDValue L =
5538 DAG.getAtomic(NT, dl, MemVT, InChain,
5539 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5540 MMO);
5541
5542 SDValue OutChain = L.getValue(1);
5543
5544 setValue(&I, L);
5545 DAG.setRoot(OutChain);
5546}
5547
5548void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5549 SDLoc dl = getCurSDLoc();
5550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5551 SDValue Ops[3];
5552 Ops[0] = getRoot();
5553 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5554 TLI.getFenceOperandTy(DAG.getDataLayout()));
5555 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5556 TLI.getFenceOperandTy(DAG.getDataLayout()));
5557 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5558 setValue(&I, N);
5559 DAG.setRoot(N);
5560}
5561
5562void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5563 SDLoc dl = getCurSDLoc();
5564 AtomicOrdering Order = I.getOrdering();
5565 SyncScope::ID SSID = I.getSyncScopeID();
5566
5567 SDValue InChain = getRoot();
5568
5569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5570 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5571 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5572
5573 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5574 report_fatal_error("Cannot generate unaligned atomic load");
5575
5576 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5577
5578 const MDNode *Ranges = getRangeMetadata(I);
5579 const MDNode *MemCacheHint = getMemCacheHint(I);
5580 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5581 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5582 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5583 Order);
5584
5585 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5586
5587 SDValue Ptr = getValue(I.getPointerOperand());
5588 SDValue L =
5589 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5590
5591 SDValue OutChain = L.getValue(1);
5592 if (MemVT != VT)
5593 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5594
5595 setValue(&I, L);
5596 DAG.setRoot(OutChain);
5597}
5598
5599void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5600 SDLoc dl = getCurSDLoc();
5601
5602 AtomicOrdering Ordering = I.getOrdering();
5603 SyncScope::ID SSID = I.getSyncScopeID();
5604
5605 SDValue InChain = getRoot();
5606
5607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5608 EVT MemVT =
5609 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5610
5611 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5612 report_fatal_error("Cannot generate unaligned atomic store");
5613
5614 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5615
5616 MachineFunction &MF = DAG.getMachineFunction();
5617 const MDNode *MemCacheHint = getMemCacheHint(I, I.getPointerOperandIndex());
5618 MachineMemOperand *MMO = MF.getMachineMemOperand(
5619 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5620 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5621 SSID, Ordering);
5622
5623 SDValue Val = getValue(I.getValueOperand());
5624 if (Val.getValueType() != MemVT)
5625 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5626 SDValue Ptr = getValue(I.getPointerOperand());
5627
5628 SDValue OutChain =
5629 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5630
5631 setValue(&I, OutChain);
5632 DAG.setRoot(OutChain);
5633}
5634
5635/// Check if this intrinsic call depends on the chain (1st return value)
5636/// and if it only *loads* memory.
5637/// Ignore the callsite's attributes. A specific call site may be marked with
5638/// readnone, but the lowering code will expect the chain based on the
5639/// definition.
5640std::pair<bool, bool>
5641SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5642 const Function *F = I.getCalledFunction();
5643 bool HasChain = !F->doesNotAccessMemory();
5644 bool OnlyLoad =
5645 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5646
5647 return {HasChain, OnlyLoad};
5648}
5649
5650SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5651 const CallBase &I, bool HasChain, bool OnlyLoad,
5652 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5654
5655 // Build the operand list.
5657 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5658 if (OnlyLoad) {
5659 // We don't need to serialize loads against other loads.
5660 Ops.push_back(DAG.getRoot());
5661 } else {
5662 Ops.push_back(getRoot());
5663 }
5664 }
5665
5666 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5667 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5668 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5669 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5670 TLI.getPointerTy(DAG.getDataLayout())));
5671
5672 // Add all operands of the call to the operand list.
5673 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5674 const Value *Arg = I.getArgOperand(i);
5675 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5676 Ops.push_back(getValue(Arg));
5677 continue;
5678 }
5679
5680 // Use TargetConstant instead of a regular constant for immarg.
5681 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5682 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5683 assert(CI->getBitWidth() <= 64 &&
5684 "large intrinsic immediates not handled");
5685 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5686 } else {
5687 Ops.push_back(
5688 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5689 }
5690 }
5691
5692 if (std::optional<OperandBundleUse> Bundle =
5693 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5694 auto *Sym = Bundle->Inputs[0].get();
5695 SDValue SDSym = getValue(Sym);
5696 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5697 Ops.push_back(SDSym);
5698 }
5699
5700 if (std::optional<OperandBundleUse> Bundle =
5701 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5702 Value *Token = Bundle->Inputs[0].get();
5703 SDValue ConvControlToken = getValue(Token);
5704 assert(Ops.back().getValueType() != MVT::Glue &&
5705 "Did not expect another glue node here.");
5706 ConvControlToken =
5707 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5708 Ops.push_back(ConvControlToken);
5709 }
5710
5711 return Ops;
5712}
5713
5714SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5715 bool HasChain) {
5716 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5717
5718 SmallVector<EVT, 4> ValueVTs;
5719 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5720
5721 if (HasChain)
5722 ValueVTs.push_back(MVT::Other);
5723
5724 return DAG.getVTList(ValueVTs);
5725}
5726
5727/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5728SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5729 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5730 const SDVTList &VTs) {
5731 if (!HasChain)
5732 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5733 if (!IntrinsicVT.isVoidTy())
5734 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5735 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5736}
5737
5738/// Set root, convert return type if necessary and check alignment.
5739SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5740 bool HasChain,
5741 bool OnlyLoad,
5742 SDValue Result) {
5743 if (HasChain) {
5744 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5745 if (OnlyLoad)
5746 PendingLoads.push_back(Chain);
5747 else
5748 DAG.setRoot(Chain);
5749 }
5750
5751 if (I.getType()->isVoidTy())
5752 return Result;
5753
5754 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5755 // Insert `assertalign` node if there's an alignment.
5756 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5757 } else if (!isa<VectorType>(I.getType())) {
5759 }
5760
5761 return Result;
5762}
5763
5764/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5765/// node.
5766void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5767 unsigned Intrinsic) {
5768 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5769 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5770
5771 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5772 Intrinsic)) {
5773 SDLoc DL = getCurSDLoc();
5774 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5775 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5776
5777 // The intrinsic is not available on this subtarget. Preserve the chain for
5778 // side-effecting intrinsics and lower any result to poison so that
5779 // compilation can continue and collect further diagnostics.
5780 if (HasChain && !OnlyLoad)
5781 DAG.setRoot(getRoot());
5782
5784 return;
5785 }
5786
5787 // Infos is set by getTgtMemIntrinsic.
5789 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5790 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5791 // Use the first (primary) info determines the node opcode.
5792 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5793
5795 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5796 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5797
5798 // Propagate fast-math-flags from IR to node(s).
5799 SDNodeFlags Flags;
5800 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5801 Flags.copyFMF(*FPMO);
5802 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5803
5804 // Create the node.
5806
5807 // In some cases, custom collection of operands from CallInst I may be needed.
5809 if (!Infos.empty()) {
5810 // This is target intrinsic that touches memory
5811 // Create MachineMemOperands for each memory access described by the target.
5812 MachineFunction &MF = DAG.getMachineFunction();
5814 for (const auto &Info : Infos) {
5815 // TODO: We currently just fallback to address space 0 if
5816 // getTgtMemIntrinsic didn't yield anything useful.
5817 MachinePointerInfo MPI;
5818 if (Info.ptrVal)
5819 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5820 else if (Info.fallbackAddressSpace)
5821 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5822 EVT MemVT = Info.memVT;
5823 LocationSize Size = LocationSize::precise(Info.size);
5824 if (Size.hasValue() && !Size.getValue())
5826 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5827 MachineMemOperand *MMO = MF.getMachineMemOperand(
5828 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5829 Info.order, Info.failureOrder);
5830 MMOs.push_back(MMO);
5831 }
5832
5833 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5834 Info->memVT, MMOs);
5835 } else {
5836 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5837 }
5838
5839 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5840
5841 setValue(&I, Result);
5842}
5843
5844/// GetSignificand - Get the significand and build it into a floating-point
5845/// number with exponent of 1:
5846///
5847/// Op = (Op & 0x007fffff) | 0x3f800000;
5848///
5849/// where Op is the hexadecimal representation of floating point value.
5851 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5852 DAG.getConstant(0x007fffff, dl, MVT::i32));
5853 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5854 DAG.getConstant(0x3f800000, dl, MVT::i32));
5855 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5856}
5857
5858/// GetExponent - Get the exponent:
5859///
5860/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5861///
5862/// where Op is the hexadecimal representation of floating point value.
5864 const TargetLowering &TLI, const SDLoc &dl) {
5865 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5866 DAG.getConstant(0x7f800000, dl, MVT::i32));
5867 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5868 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5869 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5870 DAG.getConstant(127, dl, MVT::i32));
5871 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5872}
5873
5874/// getF32Constant - Get 32-bit floating point constant.
5875static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5876 const SDLoc &dl) {
5877 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5878 MVT::f32);
5879}
5880
5882 SelectionDAG &DAG) {
5883 // TODO: What fast-math-flags should be set on the floating-point nodes?
5884
5885 // IntegerPartOfX = ((int32_t)(t0);
5886 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5887
5888 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5889 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5890 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5891
5892 // IntegerPartOfX <<= 23;
5893 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5894 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5895
5896 SDValue TwoToFractionalPartOfX;
5897 if (LimitFloatPrecision <= 6) {
5898 // For floating-point precision of 6:
5899 //
5900 // TwoToFractionalPartOfX =
5901 // 0.997535578f +
5902 // (0.735607626f + 0.252464424f * x) * x;
5903 //
5904 // error 0.0144103317, which is 6 bits
5905 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5906 getF32Constant(DAG, 0x3e814304, dl));
5907 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5908 getF32Constant(DAG, 0x3f3c50c8, dl));
5909 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5910 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5911 getF32Constant(DAG, 0x3f7f5e7e, dl));
5912 } else if (LimitFloatPrecision <= 12) {
5913 // For floating-point precision of 12:
5914 //
5915 // TwoToFractionalPartOfX =
5916 // 0.999892986f +
5917 // (0.696457318f +
5918 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5919 //
5920 // error 0.000107046256, which is 13 to 14 bits
5921 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5922 getF32Constant(DAG, 0x3da235e3, dl));
5923 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5924 getF32Constant(DAG, 0x3e65b8f3, dl));
5925 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5926 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5927 getF32Constant(DAG, 0x3f324b07, dl));
5928 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5929 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5930 getF32Constant(DAG, 0x3f7ff8fd, dl));
5931 } else { // LimitFloatPrecision <= 18
5932 // For floating-point precision of 18:
5933 //
5934 // TwoToFractionalPartOfX =
5935 // 0.999999982f +
5936 // (0.693148872f +
5937 // (0.240227044f +
5938 // (0.554906021e-1f +
5939 // (0.961591928e-2f +
5940 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5941 // error 2.47208000*10^(-7), which is better than 18 bits
5942 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5943 getF32Constant(DAG, 0x3924b03e, dl));
5944 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5945 getF32Constant(DAG, 0x3ab24b87, dl));
5946 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5947 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5948 getF32Constant(DAG, 0x3c1d8c17, dl));
5949 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5950 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5951 getF32Constant(DAG, 0x3d634a1d, dl));
5952 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5953 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5954 getF32Constant(DAG, 0x3e75fe14, dl));
5955 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5956 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5957 getF32Constant(DAG, 0x3f317234, dl));
5958 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5959 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5960 getF32Constant(DAG, 0x3f800000, dl));
5961 }
5962
5963 // Add the exponent into the result in integer domain.
5964 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5965 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5966 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5967}
5968
5969/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5970/// limited-precision mode.
5972 const TargetLowering &TLI, SDNodeFlags Flags) {
5973 if (Op.getValueType() == MVT::f32 &&
5975
5976 // Put the exponent in the right bit position for later addition to the
5977 // final result:
5978 //
5979 // t0 = Op * log2(e)
5980
5981 // TODO: What fast-math-flags should be set here?
5982 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5983 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5984 return getLimitedPrecisionExp2(t0, dl, DAG);
5985 }
5986
5987 // No special expansion.
5988 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5989}
5990
5991/// expandLog - Lower a log intrinsic. Handles the special sequences for
5992/// limited-precision mode.
5994 const TargetLowering &TLI, SDNodeFlags Flags) {
5995 // TODO: What fast-math-flags should be set on the floating-point nodes?
5996
5997 if (Op.getValueType() == MVT::f32 &&
5999 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6000
6001 // Scale the exponent by log(2).
6002 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6003 SDValue LogOfExponent =
6004 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6005 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
6006
6007 // Get the significand and build it into a floating-point number with
6008 // exponent of 1.
6009 SDValue X = GetSignificand(DAG, Op1, dl);
6010
6011 SDValue LogOfMantissa;
6012 if (LimitFloatPrecision <= 6) {
6013 // For floating-point precision of 6:
6014 //
6015 // LogofMantissa =
6016 // -1.1609546f +
6017 // (1.4034025f - 0.23903021f * x) * x;
6018 //
6019 // error 0.0034276066, which is better than 8 bits
6020 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6021 getF32Constant(DAG, 0xbe74c456, dl));
6022 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6023 getF32Constant(DAG, 0x3fb3a2b1, dl));
6024 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6025 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6026 getF32Constant(DAG, 0x3f949a29, dl));
6027 } else if (LimitFloatPrecision <= 12) {
6028 // For floating-point precision of 12:
6029 //
6030 // LogOfMantissa =
6031 // -1.7417939f +
6032 // (2.8212026f +
6033 // (-1.4699568f +
6034 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
6035 //
6036 // error 0.000061011436, which is 14 bits
6037 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6038 getF32Constant(DAG, 0xbd67b6d6, dl));
6039 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6040 getF32Constant(DAG, 0x3ee4f4b8, dl));
6041 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6042 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6043 getF32Constant(DAG, 0x3fbc278b, dl));
6044 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6045 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6046 getF32Constant(DAG, 0x40348e95, dl));
6047 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6048 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6049 getF32Constant(DAG, 0x3fdef31a, dl));
6050 } else { // LimitFloatPrecision <= 18
6051 // For floating-point precision of 18:
6052 //
6053 // LogOfMantissa =
6054 // -2.1072184f +
6055 // (4.2372794f +
6056 // (-3.7029485f +
6057 // (2.2781945f +
6058 // (-0.87823314f +
6059 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
6060 //
6061 // error 0.0000023660568, which is better than 18 bits
6062 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6063 getF32Constant(DAG, 0xbc91e5ac, dl));
6064 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6065 getF32Constant(DAG, 0x3e4350aa, dl));
6066 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6067 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6068 getF32Constant(DAG, 0x3f60d3e3, dl));
6069 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6070 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6071 getF32Constant(DAG, 0x4011cdf0, dl));
6072 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6073 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6074 getF32Constant(DAG, 0x406cfd1c, dl));
6075 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6076 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6077 getF32Constant(DAG, 0x408797cb, dl));
6078 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6079 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6080 getF32Constant(DAG, 0x4006dcab, dl));
6081 }
6082
6083 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
6084 }
6085
6086 // No special expansion.
6087 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
6088}
6089
6090/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
6091/// limited-precision mode.
6093 const TargetLowering &TLI, SDNodeFlags Flags) {
6094 // TODO: What fast-math-flags should be set on the floating-point nodes?
6095
6096 if (Op.getValueType() == MVT::f32 &&
6098 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6099
6100 // Get the exponent.
6101 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
6102
6103 // Get the significand and build it into a floating-point number with
6104 // exponent of 1.
6105 SDValue X = GetSignificand(DAG, Op1, dl);
6106
6107 // Different possible minimax approximations of significand in
6108 // floating-point for various degrees of accuracy over [1,2].
6109 SDValue Log2ofMantissa;
6110 if (LimitFloatPrecision <= 6) {
6111 // For floating-point precision of 6:
6112 //
6113 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
6114 //
6115 // error 0.0049451742, which is more than 7 bits
6116 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6117 getF32Constant(DAG, 0xbeb08fe0, dl));
6118 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6119 getF32Constant(DAG, 0x40019463, dl));
6120 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6121 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6122 getF32Constant(DAG, 0x3fd6633d, dl));
6123 } else if (LimitFloatPrecision <= 12) {
6124 // For floating-point precision of 12:
6125 //
6126 // Log2ofMantissa =
6127 // -2.51285454f +
6128 // (4.07009056f +
6129 // (-2.12067489f +
6130 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
6131 //
6132 // error 0.0000876136000, which is better than 13 bits
6133 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6134 getF32Constant(DAG, 0xbda7262e, dl));
6135 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6136 getF32Constant(DAG, 0x3f25280b, dl));
6137 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6138 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6139 getF32Constant(DAG, 0x4007b923, dl));
6140 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6141 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6142 getF32Constant(DAG, 0x40823e2f, dl));
6143 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6144 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6145 getF32Constant(DAG, 0x4020d29c, dl));
6146 } else { // LimitFloatPrecision <= 18
6147 // For floating-point precision of 18:
6148 //
6149 // Log2ofMantissa =
6150 // -3.0400495f +
6151 // (6.1129976f +
6152 // (-5.3420409f +
6153 // (3.2865683f +
6154 // (-1.2669343f +
6155 // (0.27515199f -
6156 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
6157 //
6158 // error 0.0000018516, which is better than 18 bits
6159 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6160 getF32Constant(DAG, 0xbcd2769e, dl));
6161 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6162 getF32Constant(DAG, 0x3e8ce0b9, dl));
6163 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6164 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6165 getF32Constant(DAG, 0x3fa22ae7, dl));
6166 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6167 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6168 getF32Constant(DAG, 0x40525723, dl));
6169 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6170 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6171 getF32Constant(DAG, 0x40aaf200, dl));
6172 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6173 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6174 getF32Constant(DAG, 0x40c39dad, dl));
6175 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6176 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6177 getF32Constant(DAG, 0x4042902c, dl));
6178 }
6179
6180 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
6181 }
6182
6183 // No special expansion.
6184 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
6185}
6186
6187/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6188/// limited-precision mode.
6190 const TargetLowering &TLI, SDNodeFlags Flags) {
6191 // TODO: What fast-math-flags should be set on the floating-point nodes?
6192
6193 if (Op.getValueType() == MVT::f32 &&
6195 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6196
6197 // Scale the exponent by log10(2) [0.30102999f].
6198 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6199 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6200 getF32Constant(DAG, 0x3e9a209a, dl));
6201
6202 // Get the significand and build it into a floating-point number with
6203 // exponent of 1.
6204 SDValue X = GetSignificand(DAG, Op1, dl);
6205
6206 SDValue Log10ofMantissa;
6207 if (LimitFloatPrecision <= 6) {
6208 // For floating-point precision of 6:
6209 //
6210 // Log10ofMantissa =
6211 // -0.50419619f +
6212 // (0.60948995f - 0.10380950f * x) * x;
6213 //
6214 // error 0.0014886165, which is 6 bits
6215 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6216 getF32Constant(DAG, 0xbdd49a13, dl));
6217 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6218 getF32Constant(DAG, 0x3f1c0789, dl));
6219 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6220 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6221 getF32Constant(DAG, 0x3f011300, dl));
6222 } else if (LimitFloatPrecision <= 12) {
6223 // For floating-point precision of 12:
6224 //
6225 // Log10ofMantissa =
6226 // -0.64831180f +
6227 // (0.91751397f +
6228 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6229 //
6230 // error 0.00019228036, which is better than 12 bits
6231 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6232 getF32Constant(DAG, 0x3d431f31, dl));
6233 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6234 getF32Constant(DAG, 0x3ea21fb2, dl));
6235 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6236 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6237 getF32Constant(DAG, 0x3f6ae232, dl));
6238 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6239 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6240 getF32Constant(DAG, 0x3f25f7c3, dl));
6241 } else { // LimitFloatPrecision <= 18
6242 // For floating-point precision of 18:
6243 //
6244 // Log10ofMantissa =
6245 // -0.84299375f +
6246 // (1.5327582f +
6247 // (-1.0688956f +
6248 // (0.49102474f +
6249 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6250 //
6251 // error 0.0000037995730, which is better than 18 bits
6252 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6253 getF32Constant(DAG, 0x3c5d51ce, dl));
6254 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6255 getF32Constant(DAG, 0x3e00685a, dl));
6256 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6257 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6258 getF32Constant(DAG, 0x3efb6798, dl));
6259 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6260 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6261 getF32Constant(DAG, 0x3f88d192, dl));
6262 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6263 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6264 getF32Constant(DAG, 0x3fc4316c, dl));
6265 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6266 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6267 getF32Constant(DAG, 0x3f57ce70, dl));
6268 }
6269
6270 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6271 }
6272
6273 // No special expansion.
6274 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6275}
6276
6277/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6278/// limited-precision mode.
6280 const TargetLowering &TLI, SDNodeFlags Flags) {
6281 if (Op.getValueType() == MVT::f32 &&
6283 return getLimitedPrecisionExp2(Op, dl, DAG);
6284
6285 // No special expansion.
6286 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6287}
6288
6289/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6290/// limited-precision mode with x == 10.0f.
6292 SelectionDAG &DAG, const TargetLowering &TLI,
6293 SDNodeFlags Flags) {
6294 bool IsExp10 = false;
6295 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6298 APFloat Ten(10.0f);
6299 IsExp10 = LHSC->isExactlyValue(Ten);
6300 }
6301 }
6302
6303 // TODO: What fast-math-flags should be set on the FMUL node?
6304 if (IsExp10) {
6305 // Put the exponent in the right bit position for later addition to the
6306 // final result:
6307 //
6308 // #define LOG2OF10 3.3219281f
6309 // t0 = Op * LOG2OF10;
6310 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6311 getF32Constant(DAG, 0x40549a78, dl));
6312 return getLimitedPrecisionExp2(t0, dl, DAG);
6313 }
6314
6315 // No special expansion.
6316 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6317}
6318
6319/// ExpandPowI - Expand a llvm.powi intrinsic.
6321 SelectionDAG &DAG) {
6322 // If RHS is a constant, we can expand this out to a multiplication tree if
6323 // it's beneficial on the target, otherwise we end up lowering to a call to
6324 // __powidf2 (for example).
6326 unsigned Val = RHSC->getSExtValue();
6327
6328 // powi(x, 0) -> 1.0
6329 if (Val == 0)
6330 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6331
6333 Val, DAG.shouldOptForSize())) {
6334 // Get the exponent as a positive value.
6335 if ((int)Val < 0)
6336 Val = -Val;
6337 // We use the simple binary decomposition method to generate the multiply
6338 // sequence. There are more optimal ways to do this (for example,
6339 // powi(x,15) generates one more multiply than it should), but this has
6340 // the benefit of being both really simple and much better than a libcall.
6341 SDValue Res; // Logically starts equal to 1.0
6342 SDValue CurSquare = LHS;
6343 // TODO: Intrinsics should have fast-math-flags that propagate to these
6344 // nodes.
6345 while (Val) {
6346 if (Val & 1) {
6347 if (Res.getNode())
6348 Res =
6349 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6350 else
6351 Res = CurSquare; // 1.0*CurSquare.
6352 }
6353
6354 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6355 CurSquare, CurSquare);
6356 Val >>= 1;
6357 }
6358
6359 // If the original was negative, invert the result, producing 1/(x*x*x).
6360 if (RHSC->getSExtValue() < 0)
6361 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6362 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6363 return Res;
6364 }
6365 }
6366
6367 // Otherwise, expand to a libcall.
6368 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6369}
6370
6371static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6372 SDValue LHS, SDValue RHS, SDValue Scale,
6373 SelectionDAG &DAG, const TargetLowering &TLI) {
6374 EVT VT = LHS.getValueType();
6375 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6376 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6377 LLVMContext &Ctx = *DAG.getContext();
6378
6379 // If the type is legal but the operation isn't, this node might survive all
6380 // the way to operation legalization. If we end up there and we do not have
6381 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6382 // node.
6383
6384 // Coax the legalizer into expanding the node during type legalization instead
6385 // by bumping the size by one bit. This will force it to Promote, enabling the
6386 // early expansion and avoiding the need to expand later.
6387
6388 // We don't have to do this if Scale is 0; that can always be expanded, unless
6389 // it's a saturating signed operation. Those can experience true integer
6390 // division overflow, a case which we must avoid.
6391
6392 // FIXME: We wouldn't have to do this (or any of the early
6393 // expansion/promotion) if it was possible to expand a libcall of an
6394 // illegal type during operation legalization. But it's not, so things
6395 // get a bit hacky.
6396 unsigned ScaleInt = Scale->getAsZExtVal();
6397 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6398 (TLI.isTypeLegal(VT) ||
6399 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6400 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6401 Opcode, VT, ScaleInt);
6402 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6403 EVT PromVT;
6404 if (VT.isScalarInteger())
6405 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6406 else if (VT.isVector()) {
6407 PromVT = VT.getVectorElementType();
6408 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6409 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6410 } else
6411 llvm_unreachable("Wrong VT for DIVFIX?");
6412 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6413 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6414 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6415 // For saturating operations, we need to shift up the LHS to get the
6416 // proper saturation width, and then shift down again afterwards.
6417 if (Saturating)
6418 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6419 DAG.getConstant(1, DL, ShiftTy));
6420 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6421 if (Saturating)
6422 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6423 DAG.getConstant(1, DL, ShiftTy));
6424 return DAG.getZExtOrTrunc(Res, DL, VT);
6425 }
6426 }
6427
6428 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6429}
6430
6431// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6432// bitcasted, or split argument. Returns a list of <Register, size in bits>
6433static void
6434getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6435 const SDValue &N, const DataLayout &DL) {
6436 switch (N.getOpcode()) {
6437 case ISD::CopyFromReg: {
6438 SDValue Op = N.getOperand(1);
6439 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6440 Op.getValueType().getSizeInBits());
6441 return;
6442 }
6443 case ISD::BITCAST:
6444 case ISD::AssertZext:
6445 case ISD::AssertSext:
6446 case ISD::TRUNCATE:
6447 getUnderlyingArgRegs(Regs, N.getOperand(0), DL);
6448 return;
6449 case ISD::BUILD_PAIR:
6450 // Fragment offsets count from the lowest-addressed byte, so on
6451 // big-endian targets the high half (operand 1) comes first.
6452 if (DL.isBigEndian()) {
6453 getUnderlyingArgRegs(Regs, N.getOperand(1), DL);
6454 getUnderlyingArgRegs(Regs, N.getOperand(0), DL);
6455 return;
6456 }
6457 [[fallthrough]];
6458 case ISD::BUILD_VECTOR:
6460 for (SDValue Op : N->op_values())
6461 getUnderlyingArgRegs(Regs, Op, DL);
6462 return;
6463 default:
6464 return;
6465 }
6466}
6467
6468/// If the DbgValueInst is a dbg_value of a function argument, create the
6469/// corresponding DBG_VALUE machine instruction for it now. At the end of
6470/// instruction selection, they will be inserted to the entry BB.
6471/// We don't currently support this for variadic dbg_values, as they shouldn't
6472/// appear for function arguments or in the prologue.
6473bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6474 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6475 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6476 const Argument *Arg = dyn_cast<Argument>(V);
6477 if (!Arg)
6478 return false;
6479
6480 MachineFunction &MF = DAG.getMachineFunction();
6481 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6482
6483 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6484 // we've been asked to pursue.
6485 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6486 bool Indirect) {
6487 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6488 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6489 // pointing at the VReg, which will be patched up later.
6490 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6492 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6493 /* isKill */ false, /* isDead */ false,
6494 /* isUndef */ false, /* isEarlyClobber */ false,
6495 /* SubReg */ 0, /* isDebug */ true)});
6496
6497 auto *NewDIExpr = FragExpr;
6498 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6499 // the DIExpression.
6500 if (Indirect)
6501 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6503 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6504 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6505 } else {
6506 // Create a completely standard DBG_VALUE.
6507 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6508 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6509 }
6510 };
6511
6512 if (Kind == FuncArgumentDbgValueKind::Value) {
6513 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6514 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6515 // the entry block.
6516 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6517 if (!IsInEntryBlock)
6518 return false;
6519
6520 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6521 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6522 // variable that also is a param.
6523 //
6524 // Although, if we are at the top of the entry block already, we can still
6525 // emit using ArgDbgValue. This might catch some situations when the
6526 // dbg.value refers to an argument that isn't used in the entry block, so
6527 // any CopyToReg node would be optimized out and the only way to express
6528 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6529 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6530 // we should only emit as ArgDbgValue if the Variable is an argument to the
6531 // current function, and the dbg.value intrinsic is found in the entry
6532 // block.
6533 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6534 !DL->getInlinedAt();
6535 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6536 if (!IsInPrologue && !VariableIsFunctionInputArg)
6537 return false;
6538
6539 // Here we assume that a function argument on IR level only can be used to
6540 // describe one input parameter on source level. If we for example have
6541 // source code like this
6542 //
6543 // struct A { long x, y; };
6544 // void foo(struct A a, long b) {
6545 // ...
6546 // b = a.x;
6547 // ...
6548 // }
6549 //
6550 // and IR like this
6551 //
6552 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6553 // entry:
6554 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6555 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6556 // call void @llvm.dbg.value(metadata i32 %b, "b",
6557 // ...
6558 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6559 // ...
6560 //
6561 // then the last dbg.value is describing a parameter "b" using a value that
6562 // is an argument. But since we already has used %a1 to describe a parameter
6563 // we should not handle that last dbg.value here (that would result in an
6564 // incorrect hoisting of the DBG_VALUE to the function entry).
6565 // Notice that we allow one dbg.value per IR level argument, to accommodate
6566 // for the situation with fragments above.
6567 // If there is no node for the value being handled, we return true to skip
6568 // the normal generation of debug info, as it would kill existing debug
6569 // info for the parameter in case of duplicates.
6570 if (VariableIsFunctionInputArg) {
6571 unsigned ArgNo = Arg->getArgNo();
6572 if (ArgNo >= FuncInfo.DescribedArgs.size())
6573 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6574 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6575 return !NodeMap[V].getNode();
6576 FuncInfo.DescribedArgs.set(ArgNo);
6577 }
6578 }
6579
6580 bool IsIndirect = false;
6581 std::optional<MachineOperand> Op;
6582 // Some arguments' frame index is recorded during argument lowering.
6583 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6584 if (FI != std::numeric_limits<int>::max())
6586
6588 if (!Op && N.getNode()) {
6589 getUnderlyingArgRegs(ArgRegsAndSizes, N, DAG.getDataLayout());
6590 Register Reg;
6591 if (ArgRegsAndSizes.size() == 1)
6592 Reg = ArgRegsAndSizes.front().first;
6593
6594 if (Reg && Reg.isVirtual()) {
6595 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6596 Register PR = RegInfo.getLiveInPhysReg(Reg);
6597 if (PR)
6598 Reg = PR;
6599 }
6600 if (Reg) {
6602 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6603 }
6604 }
6605
6606 if (!Op && N.getNode()) {
6607 // Check if frame index is available.
6608 SDValue LCandidate = peekThroughBitcasts(N);
6609 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6610 if (FrameIndexSDNode *FINode =
6611 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6612 Op = MachineOperand::CreateFI(FINode->getIndex());
6613 }
6614
6615 if (!Op) {
6616 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6617 auto splitMultiRegDbgValue =
6618 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6619 unsigned Offset = 0;
6620 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6621 // FIXME: Scalable sizes are not supported in fragment expressions.
6622 if (RegSizeInBits.isScalable())
6623 return false;
6624
6625 // If the expression is already a fragment, the current register
6626 // offset+size might extend beyond the fragment. In this case, only
6627 // the register bits that are inside the fragment are relevant.
6628 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6629 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6630 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6631 // The register is entirely outside the expression fragment,
6632 // so is irrelevant for debug info.
6633 if (Offset >= ExprFragmentSizeInBits)
6634 break;
6635 // The register is partially outside the expression fragment, only
6636 // the low bits within the fragment are relevant for debug info.
6637 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6638 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6639 }
6640 }
6641
6642 auto FragmentExpr = DIExpression::createFragmentExpression(
6643 Expr, Offset, RegFragmentSizeInBits);
6644 Offset += RegSizeInBits.getFixedValue();
6645 // If a valid fragment expression cannot be created, the variable's
6646 // correct value cannot be determined and so it is set as poison.
6647 if (!FragmentExpr) {
6648 SDDbgValue *SDV = DAG.getConstantDbgValue(
6649 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6650 DAG.AddDbgValue(SDV, false);
6651 continue;
6652 }
6653 MachineInstr *NewMI = MakeVRegDbgValue(
6654 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6655 FuncInfo.ArgDbgValues.push_back(NewMI);
6656 }
6657
6658 return true;
6659 };
6660
6661 // Check if ValueMap has reg number.
6663 VMI = FuncInfo.ValueMap.find(V);
6664 if (VMI != FuncInfo.ValueMap.end()) {
6665 const auto &TLI = DAG.getTargetLoweringInfo();
6666 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6667 V->getType(), std::nullopt);
6668 if (RFV.occupiesMultipleRegs())
6669 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6670
6671 Op = MachineOperand::CreateReg(VMI->second, false);
6672 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6673 } else if (ArgRegsAndSizes.size() > 1) {
6674 // This was split due to the calling convention, and no virtual register
6675 // mapping exists for the value.
6676 return splitMultiRegDbgValue(ArgRegsAndSizes);
6677 }
6678 }
6679
6680 if (!Op)
6681 return false;
6682
6683 assert(Variable->isValidLocationForIntrinsic(DL) &&
6684 "Expected inlined-at fields to agree");
6685 MachineInstr *NewMI = nullptr;
6686
6687 if (Op->isReg())
6688 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6689 else
6690 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6691 Variable, Expr);
6692
6693 // Otherwise, use ArgDbgValues.
6694 FuncInfo.ArgDbgValues.push_back(NewMI);
6695 return true;
6696}
6697
6698/// Return the appropriate SDDbgValue based on N.
6699SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6700 DILocalVariable *Variable,
6701 DIExpression *Expr,
6702 const DebugLoc &dl,
6703 unsigned DbgSDNodeOrder) {
6704 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6705 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6706 // stack slot locations.
6707 //
6708 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6709 // debug values here after optimization:
6710 //
6711 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6712 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6713 //
6714 // Both describe the direct values of their associated variables.
6715 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6716 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6717 }
6718 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6719 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6720}
6721
6722static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6723 switch (Intrinsic) {
6724 case Intrinsic::smul_fix:
6725 return ISD::SMULFIX;
6726 case Intrinsic::umul_fix:
6727 return ISD::UMULFIX;
6728 case Intrinsic::smul_fix_sat:
6729 return ISD::SMULFIXSAT;
6730 case Intrinsic::umul_fix_sat:
6731 return ISD::UMULFIXSAT;
6732 case Intrinsic::sdiv_fix:
6733 return ISD::SDIVFIX;
6734 case Intrinsic::udiv_fix:
6735 return ISD::UDIVFIX;
6736 case Intrinsic::sdiv_fix_sat:
6737 return ISD::SDIVFIXSAT;
6738 case Intrinsic::udiv_fix_sat:
6739 return ISD::UDIVFIXSAT;
6740 default:
6741 llvm_unreachable("Unhandled fixed point intrinsic");
6742 }
6743}
6744
6745/// Given a @llvm.call.preallocated.setup, return the corresponding
6746/// preallocated call.
6747static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6748 assert(cast<CallBase>(PreallocatedSetup)
6750 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6751 "expected call_preallocated_setup Value");
6752 for (const auto *U : PreallocatedSetup->users()) {
6753 auto *UseCall = cast<CallBase>(U);
6754 const Function *Fn = UseCall->getCalledFunction();
6755 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6756 return UseCall;
6757 }
6758 }
6759 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6760}
6761
6762/// If DI is a debug value with an EntryValue expression, lower it using the
6763/// corresponding physical register of the associated Argument value
6764/// (guaranteed to exist by the verifier).
6765bool SelectionDAGBuilder::visitEntryValueDbgValue(
6767 DIExpression *Expr, DebugLoc DbgLoc) {
6768 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6769 return false;
6770
6771 // These properties are guaranteed by the verifier.
6772 const Argument *Arg = cast<Argument>(Values[0]);
6773 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6774
6775 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6776 if (ArgIt == FuncInfo.ValueMap.end()) {
6777 LLVM_DEBUG(
6778 dbgs() << "Dropping dbg.value: expression is entry_value but "
6779 "couldn't find an associated register for the Argument\n");
6780 return true;
6781 }
6782 Register ArgVReg = ArgIt->getSecond();
6783
6784 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6785 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6786 SDDbgValue *SDV = DAG.getVRegDbgValue(
6787 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6788 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6789 return true;
6790 }
6791 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6792 "couldn't find a physical register\n");
6793 return true;
6794}
6795
6796/// Lower the call to the specified intrinsic function.
6797void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6798 unsigned Intrinsic) {
6799 SDLoc sdl = getCurSDLoc();
6800 switch (Intrinsic) {
6801 case Intrinsic::experimental_convergence_anchor:
6802 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6803 break;
6804 case Intrinsic::experimental_convergence_entry:
6805 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6806 break;
6807 case Intrinsic::experimental_convergence_loop: {
6808 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6809 auto *Token = Bundle->Inputs[0].get();
6810 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6811 getValue(Token)));
6812 break;
6813 }
6814 }
6815}
6816
6817void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6818 unsigned IntrinsicID) {
6819 // For now, we're only lowering an 'add' histogram.
6820 // We can add others later, e.g. saturating adds, min/max.
6821 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6822 "Tried to lower unsupported histogram type");
6823 SDLoc sdl = getCurSDLoc();
6824 Value *Ptr = I.getOperand(0);
6825 SDValue Inc = getValue(I.getOperand(1));
6826 SDValue Mask = getValue(I.getOperand(2));
6827
6828 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6829 EVT VT = Inc.getValueType();
6830 Align Alignment = DAG.getEVTAlign(VT);
6831
6832 const MDNode *Ranges = getRangeMetadata(I);
6833
6834 SDValue Root = DAG.getRoot();
6835 SDValue Base;
6836 SDValue Index;
6837 SDValue Scale;
6838 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6839 I.getParent(), VT.getScalarStoreSize());
6840
6841 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6842
6843 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6844 MachinePointerInfo(AS),
6846 MemoryLocation::UnknownSize, Alignment,
6847 MMOMetadata(I.getAAMetadata(), Ranges));
6848
6849 if (!UniformBase) {
6850 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6851 Index = getValue(Ptr);
6852 Scale =
6853 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6854 }
6855
6856 EVT IdxVT = Index.getValueType();
6857
6858 // Avoid using e.g. i32 as index type when the increment must be performed
6859 // on i64's.
6860 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6861 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6862 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6863 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6864 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6865 }
6866
6867 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6868
6869 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6870 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6871 Ops, MMO, ISD::SIGNED_SCALED);
6872
6873 setValue(&I, Histogram);
6874 DAG.setRoot(Histogram);
6875}
6876
6877void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6878 unsigned Intrinsic) {
6879 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6880 "Tried lowering invalid vector extract last");
6881 SDLoc sdl = getCurSDLoc();
6882 const DataLayout &Layout = DAG.getDataLayout();
6883 SDValue Data = getValue(I.getOperand(0));
6884 SDValue Mask = getValue(I.getOperand(1));
6885
6886 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6887 EVT ResVT = TLI.getValueType(Layout, I.getType());
6888
6889 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6890 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6891 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6892
6893 Value *Default = I.getOperand(2);
6895 SDValue PassThru = getValue(Default);
6896 EVT BoolVT = Mask.getValueType().getScalarType();
6897 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6898 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6899 }
6900
6901 setValue(&I, Result);
6902}
6903
6904/// Lower the call to the specified intrinsic function.
6905void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6906 unsigned Intrinsic) {
6907 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6908 SDLoc sdl = getCurSDLoc();
6909 DebugLoc dl = getCurDebugLoc();
6910 SDValue Res;
6911
6912 SDNodeFlags Flags;
6913 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6914 Flags.copyFMF(*FPOp);
6915
6916 switch (Intrinsic) {
6917 default:
6918 // By default, turn this into a target intrinsic node.
6919 visitTargetIntrinsic(I, Intrinsic);
6920 return;
6921 case Intrinsic::vscale: {
6922 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6923 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6924 return;
6925 }
6926 case Intrinsic::vastart: visitVAStart(I); return;
6927 case Intrinsic::vaend: visitVAEnd(I); return;
6928 case Intrinsic::vacopy: visitVACopy(I); return;
6929 case Intrinsic::returnaddress:
6930 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6931 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6932 getValue(I.getArgOperand(0))));
6933 return;
6934 case Intrinsic::addressofreturnaddress:
6935 setValue(&I,
6936 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6937 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6938 return;
6939 case Intrinsic::sponentry:
6940 setValue(&I,
6941 DAG.getNode(ISD::SPONENTRY, sdl,
6942 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6943 return;
6944 case Intrinsic::frameaddress:
6945 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6946 TLI.getFrameIndexTy(DAG.getDataLayout()),
6947 getValue(I.getArgOperand(0))));
6948 return;
6949 case Intrinsic::read_volatile_register:
6950 case Intrinsic::read_register: {
6951 Value *Reg = I.getArgOperand(0);
6952 SDValue Chain = getRoot();
6954 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6955 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6956 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6957 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6958 setValue(&I, Res);
6959 DAG.setRoot(Res.getValue(1));
6960 return;
6961 }
6962 case Intrinsic::write_register: {
6963 Value *Reg = I.getArgOperand(0);
6964 Value *RegValue = I.getArgOperand(1);
6965 SDValue Chain = getRoot();
6967 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6968 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6969 RegName, getValue(RegValue)));
6970 return;
6971 }
6972 case Intrinsic::write_volatile_register: {
6973 Value *Reg = I.getArgOperand(0);
6974 Value *RegValue = I.getArgOperand(1);
6975 SDValue Chain = getRoot();
6976 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6977 SDValue RegName = DAG.getMDNode(MD);
6978 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6979 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6980 Chain, RegName, getValue(RegValue));
6981 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6982 // preventing the backend from dead-eliminating the write. This is
6983 // preferred over READ_REGISTER, which would emit extra register copies
6984 // (e.g. fmov xN, dN for FP/SIMD registers).
6985 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6986 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6987 const MachineFunction &MF = DAG.getMachineFunction();
6988 Register PhysReg =
6989 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6990 if (PhysReg.isValid()) {
6991 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6992 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6993 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6994 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6995 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6996 } else {
6997 DAG.setRoot(WriteChain);
6998 }
6999 return;
7000 }
7001 case Intrinsic::memcpy:
7002 case Intrinsic::memcpy_inline: {
7003 const auto &MCI = cast<MemCpyInst>(I);
7004 SDValue Dst = getValue(I.getArgOperand(0));
7005 SDValue Src = getValue(I.getArgOperand(1));
7006 SDValue Size = getValue(I.getArgOperand(2));
7007 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7008 "memcpy_inline needs constant size");
7009 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
7010 Align DstAlign = MCI.getDestAlign().valueOrOne();
7011 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
7012 bool isVol = MCI.isVolatile();
7013 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7014 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
7015 isVol, MCI.isForceInlined(), &I, std::nullopt,
7016 MachinePointerInfo(I.getArgOperand(0)),
7017 MachinePointerInfo(I.getArgOperand(1)),
7018 I.getAAMetadata(), BatchAA);
7019 updateDAGForMaybeTailCall(MC);
7020 return;
7021 }
7022 case Intrinsic::memset:
7023 case Intrinsic::memset_inline: {
7024 const auto &MSII = cast<MemSetInst>(I);
7025 SDValue Dst = getValue(I.getArgOperand(0));
7026 SDValue Value = getValue(I.getArgOperand(1));
7027 SDValue Size = getValue(I.getArgOperand(2));
7028 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7029 "memset_inline needs constant size");
7030 // @llvm.memset defines 0 and 1 to both mean no alignment.
7031 Align DstAlign = MSII.getDestAlign().valueOrOne();
7032 bool isVol = MSII.isVolatile();
7033 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7034 SDValue MC = DAG.getMemset(
7035 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
7036 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
7037 updateDAGForMaybeTailCall(MC);
7038 return;
7039 }
7040 case Intrinsic::memmove: {
7041 const auto &MMI = cast<MemMoveInst>(I);
7042 SDValue Op1 = getValue(I.getArgOperand(0));
7043 SDValue Op2 = getValue(I.getArgOperand(1));
7044 SDValue Op3 = getValue(I.getArgOperand(2));
7045 // @llvm.memmove defines 0 and 1 to both mean no alignment.
7046 Align DstAlign = MMI.getDestAlign().valueOrOne();
7047 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
7048 bool isVol = MMI.isVolatile();
7049 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7050 SDValue MM = DAG.getMemmove(
7051 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
7052 /* OverrideTailCall */ std::nullopt,
7053 MachinePointerInfo(I.getArgOperand(0)),
7054 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
7055 updateDAGForMaybeTailCall(MM);
7056 return;
7057 }
7058 case Intrinsic::memcpy_element_unordered_atomic: {
7059 auto &MI = cast<AnyMemCpyInst>(I);
7060 SDValue Dst = getValue(MI.getRawDest());
7061 SDValue Src = getValue(MI.getRawSource());
7062 SDValue Length = getValue(MI.getLength());
7063
7064 Type *LengthTy = MI.getLength()->getType();
7065 unsigned ElemSz = MI.getElementSizeInBytes();
7066 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7067 SDValue MC =
7068 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7069 isTC, MachinePointerInfo(MI.getRawDest()),
7070 MachinePointerInfo(MI.getRawSource()));
7071 updateDAGForMaybeTailCall(MC);
7072 return;
7073 }
7074 case Intrinsic::memmove_element_unordered_atomic: {
7075 auto &MI = cast<AnyMemMoveInst>(I);
7076 SDValue Dst = getValue(MI.getRawDest());
7077 SDValue Src = getValue(MI.getRawSource());
7078 SDValue Length = getValue(MI.getLength());
7079
7080 Type *LengthTy = MI.getLength()->getType();
7081 unsigned ElemSz = MI.getElementSizeInBytes();
7082 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7083 SDValue MC =
7084 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7085 isTC, MachinePointerInfo(MI.getRawDest()),
7086 MachinePointerInfo(MI.getRawSource()));
7087 updateDAGForMaybeTailCall(MC);
7088 return;
7089 }
7090 case Intrinsic::memset_element_unordered_atomic: {
7091 auto &MI = cast<AnyMemSetInst>(I);
7092 SDValue Dst = getValue(MI.getRawDest());
7093 SDValue Val = getValue(MI.getValue());
7094 SDValue Length = getValue(MI.getLength());
7095
7096 Type *LengthTy = MI.getLength()->getType();
7097 unsigned ElemSz = MI.getElementSizeInBytes();
7098 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7099 SDValue MC =
7100 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
7101 isTC, MachinePointerInfo(MI.getRawDest()));
7102 updateDAGForMaybeTailCall(MC);
7103 return;
7104 }
7105 case Intrinsic::call_preallocated_setup: {
7106 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
7107 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7108 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
7109 getRoot(), SrcValue);
7110 setValue(&I, Res);
7111 DAG.setRoot(Res);
7112 return;
7113 }
7114 case Intrinsic::call_preallocated_arg: {
7115 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
7116 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7117 SDValue Ops[3];
7118 Ops[0] = getRoot();
7119 Ops[1] = SrcValue;
7120 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7121 MVT::i32); // arg index
7122 SDValue Res = DAG.getNode(
7124 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
7125 setValue(&I, Res);
7126 DAG.setRoot(Res.getValue(1));
7127 return;
7128 }
7129
7130 case Intrinsic::eh_typeid_for: {
7131 // Find the type id for the given typeinfo.
7132 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
7133 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
7134 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
7135 setValue(&I, Res);
7136 return;
7137 }
7138
7139 case Intrinsic::eh_return_i32:
7140 case Intrinsic::eh_return_i64:
7141 DAG.getMachineFunction().setCallsEHReturn(true);
7142 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
7143 MVT::Other,
7145 getValue(I.getArgOperand(0)),
7146 getValue(I.getArgOperand(1))));
7147 return;
7148 case Intrinsic::eh_unwind_init:
7149 DAG.getMachineFunction().setCallsUnwindInit(true);
7150 return;
7151 case Intrinsic::eh_dwarf_cfa:
7152 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
7153 TLI.getPointerTy(DAG.getDataLayout()),
7154 getValue(I.getArgOperand(0))));
7155 return;
7156 case Intrinsic::eh_sjlj_callsite: {
7157 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
7158 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
7159
7160 FuncInfo.setCurrentCallSite(CI->getZExtValue());
7161 return;
7162 }
7163 case Intrinsic::eh_sjlj_functioncontext: {
7164 // Get and store the index of the function context.
7165 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7166 AllocaInst *FnCtx =
7167 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
7168 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7170 return;
7171 }
7172 case Intrinsic::eh_sjlj_setjmp: {
7173 SDValue Ops[2];
7174 Ops[0] = getRoot();
7175 Ops[1] = getValue(I.getArgOperand(0));
7176 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
7177 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7178 setValue(&I, Op.getValue(0));
7179 DAG.setRoot(Op.getValue(1));
7180 return;
7181 }
7182 case Intrinsic::eh_sjlj_longjmp:
7183 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
7184 getRoot(), getValue(I.getArgOperand(0))));
7185 return;
7186 case Intrinsic::eh_sjlj_setup_dispatch:
7187 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
7188 getRoot()));
7189 return;
7190 case Intrinsic::masked_gather:
7191 visitMaskedGather(I);
7192 return;
7193 case Intrinsic::masked_load:
7194 visitMaskedLoad(I);
7195 return;
7196 case Intrinsic::masked_scatter:
7197 visitMaskedScatter(I);
7198 return;
7199 case Intrinsic::masked_store:
7200 visitMaskedStore(I);
7201 return;
7202 case Intrinsic::masked_expandload:
7203 visitMaskedLoad(I, true /* IsExpanding */);
7204 return;
7205 case Intrinsic::masked_compressstore:
7206 visitMaskedStore(I, true /* IsCompressing */);
7207 return;
7208 case Intrinsic::speculative_load:
7209 visitSpeculativeLoad(I);
7210 return;
7211 case Intrinsic::powi:
7212 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7213 getValue(I.getArgOperand(1)), DAG));
7214 return;
7215 case Intrinsic::log:
7216 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7217 return;
7218 case Intrinsic::log2:
7219 setValue(&I,
7220 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7221 return;
7222 case Intrinsic::log10:
7223 setValue(&I,
7224 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7225 return;
7226 case Intrinsic::exp:
7227 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7228 return;
7229 case Intrinsic::exp2:
7230 setValue(&I,
7231 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7232 return;
7233 case Intrinsic::pow:
7234 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7235 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7236 return;
7237 case Intrinsic::sqrt:
7238 case Intrinsic::fabs:
7239 case Intrinsic::sin:
7240 case Intrinsic::cos:
7241 case Intrinsic::tan:
7242 case Intrinsic::asin:
7243 case Intrinsic::acos:
7244 case Intrinsic::atan:
7245 case Intrinsic::sinh:
7246 case Intrinsic::cosh:
7247 case Intrinsic::tanh:
7248 case Intrinsic::exp10:
7249 case Intrinsic::floor:
7250 case Intrinsic::ceil:
7251 case Intrinsic::trunc:
7252 case Intrinsic::rint:
7253 case Intrinsic::nearbyint:
7254 case Intrinsic::round:
7255 case Intrinsic::roundeven:
7256 case Intrinsic::canonicalize: {
7257 unsigned Opcode;
7258 // clang-format off
7259 switch (Intrinsic) {
7260 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7261 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7262 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7263 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7264 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7265 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7266 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7267 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7268 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7269 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7270 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7271 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7272 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7273 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7274 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7275 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7276 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7277 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7278 case Intrinsic::round: Opcode = ISD::FROUND; break;
7279 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7280 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7281 }
7282 // clang-format on
7283
7284 setValue(&I, DAG.getNode(Opcode, sdl,
7285 getValue(I.getArgOperand(0)).getValueType(),
7286 getValue(I.getArgOperand(0)), Flags));
7287 return;
7288 }
7289 case Intrinsic::atan2:
7290 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7291 getValue(I.getArgOperand(0)).getValueType(),
7292 getValue(I.getArgOperand(0)),
7293 getValue(I.getArgOperand(1)), Flags));
7294 return;
7295 case Intrinsic::lround:
7296 case Intrinsic::llround:
7297 case Intrinsic::lrint:
7298 case Intrinsic::llrint: {
7299 unsigned Opcode;
7300 // clang-format off
7301 switch (Intrinsic) {
7302 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7303 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7304 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7305 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7306 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7307 }
7308 // clang-format on
7309
7310 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7311 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7312 getValue(I.getArgOperand(0))));
7313 return;
7314 }
7315 case Intrinsic::minnum:
7316 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7317 getValue(I.getArgOperand(0)).getValueType(),
7318 getValue(I.getArgOperand(0)),
7319 getValue(I.getArgOperand(1)), Flags));
7320 return;
7321 case Intrinsic::maxnum:
7322 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7323 getValue(I.getArgOperand(0)).getValueType(),
7324 getValue(I.getArgOperand(0)),
7325 getValue(I.getArgOperand(1)), Flags));
7326 return;
7327 case Intrinsic::minimum:
7328 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7329 getValue(I.getArgOperand(0)).getValueType(),
7330 getValue(I.getArgOperand(0)),
7331 getValue(I.getArgOperand(1)), Flags));
7332 return;
7333 case Intrinsic::maximum:
7334 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7335 getValue(I.getArgOperand(0)).getValueType(),
7336 getValue(I.getArgOperand(0)),
7337 getValue(I.getArgOperand(1)), Flags));
7338 return;
7339 case Intrinsic::minimumnum:
7340 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7341 getValue(I.getArgOperand(0)).getValueType(),
7342 getValue(I.getArgOperand(0)),
7343 getValue(I.getArgOperand(1)), Flags));
7344 return;
7345 case Intrinsic::maximumnum:
7346 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7347 getValue(I.getArgOperand(0)).getValueType(),
7348 getValue(I.getArgOperand(0)),
7349 getValue(I.getArgOperand(1)), Flags));
7350 return;
7351 case Intrinsic::copysign:
7352 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7353 getValue(I.getArgOperand(0)).getValueType(),
7354 getValue(I.getArgOperand(0)),
7355 getValue(I.getArgOperand(1)), Flags));
7356 return;
7357 case Intrinsic::ldexp:
7358 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7359 getValue(I.getArgOperand(0)).getValueType(),
7360 getValue(I.getArgOperand(0)),
7361 getValue(I.getArgOperand(1)), Flags));
7362 return;
7363 case Intrinsic::modf:
7364 case Intrinsic::sincos:
7365 case Intrinsic::sincospi:
7366 case Intrinsic::frexp: {
7367 unsigned Opcode;
7368 switch (Intrinsic) {
7369 default:
7370 llvm_unreachable("unexpected intrinsic");
7371 case Intrinsic::sincos:
7372 Opcode = ISD::FSINCOS;
7373 break;
7374 case Intrinsic::sincospi:
7375 Opcode = ISD::FSINCOSPI;
7376 break;
7377 case Intrinsic::modf:
7378 Opcode = ISD::FMODF;
7379 break;
7380 case Intrinsic::frexp:
7381 Opcode = ISD::FFREXP;
7382 break;
7383 }
7384 SmallVector<EVT, 2> ValueVTs;
7385 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7386 SDVTList VTs = DAG.getVTList(ValueVTs);
7387 setValue(
7388 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7389 return;
7390 }
7391 case Intrinsic::arithmetic_fence: {
7392 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7393 getValue(I.getArgOperand(0)).getValueType(),
7394 getValue(I.getArgOperand(0)), Flags));
7395 return;
7396 }
7397 case Intrinsic::fma:
7398 setValue(&I, DAG.getNode(
7399 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7400 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7401 getValue(I.getArgOperand(2)), Flags));
7402 return;
7403#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7404 case Intrinsic::INTRINSIC:
7405#include "llvm/IR/ConstrainedOps.def"
7406 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7407 return;
7408#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7409#include "llvm/IR/VPIntrinsics.def"
7410 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7411 return;
7412 case Intrinsic::fptrunc_round: {
7413 // Get the last argument, the metadata and convert it to an integer in the
7414 // call
7415 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7416 std::optional<RoundingMode> RoundMode =
7417 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7418
7419 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7420
7421 // Propagate fast-math-flags from IR to node(s).
7422 SDNodeFlags Flags;
7423 Flags.copyFMF(*cast<FPMathOperator>(&I));
7424 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7425
7427 Result = DAG.getNode(
7428 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7429 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7430 setValue(&I, Result);
7431
7432 return;
7433 }
7434 case Intrinsic::fmuladd: {
7435 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7436 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7437 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7438 getValue(I.getArgOperand(0)).getValueType(),
7439 getValue(I.getArgOperand(0)),
7440 getValue(I.getArgOperand(1)),
7441 getValue(I.getArgOperand(2)), Flags));
7442 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7443 // TODO: Support splitting the vector.
7444 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7445 getValue(I.getArgOperand(0)).getValueType(),
7446 getValue(I.getArgOperand(0)),
7447 getValue(I.getArgOperand(1)),
7448 getValue(I.getArgOperand(2)), Flags));
7449 } else {
7450 // TODO: Intrinsic calls should have fast-math-flags.
7451 SDValue Mul = DAG.getNode(
7452 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7453 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7454 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7455 getValue(I.getArgOperand(0)).getValueType(),
7456 Mul, getValue(I.getArgOperand(2)), Flags);
7457 setValue(&I, Add);
7458 }
7459 return;
7460 }
7461 case Intrinsic::fptosi_sat: {
7462 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7463 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7464 getValue(I.getArgOperand(0)),
7465 DAG.getValueType(VT.getScalarType())));
7466 return;
7467 }
7468 case Intrinsic::fptoui_sat: {
7469 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7470 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7471 getValue(I.getArgOperand(0)),
7472 DAG.getValueType(VT.getScalarType())));
7473 return;
7474 }
7475 case Intrinsic::convert_from_arbitrary_fp: {
7476 // Extract format metadata and convert to semantics enum.
7477 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7478 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7479 StringRef FormatStr = cast<MDString>(MD)->getString();
7480 const fltSemantics *SrcSem =
7482 if (!SrcSem) {
7483 DAG.getContext()->emitError(
7484 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7485 "'");
7486 setValue(&I, DAG.getPOISON(DstVT));
7487 return;
7488 }
7490
7491 SDValue IntVal = getValue(I.getArgOperand(0));
7492
7493 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7494 SDValue SemConst =
7495 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7496 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7497 SemConst));
7498 return;
7499 }
7500 case Intrinsic::convert_to_arbitrary_fp: {
7501 // Extract format metadata and convert to semantics enum.
7502 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7503 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7504 StringRef FormatStr = cast<MDString>(MD)->getString();
7505 const fltSemantics *DstSem =
7507 if (!DstSem) {
7508 DAG.getContext()->emitError(
7509 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7510 "'");
7511 setValue(&I, DAG.getPOISON(DstVT));
7512 return;
7513 }
7515
7516 Metadata *RoundMD =
7517 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7518 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7519 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7520 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7521 "Dynamic rounding mode should have been rejected by the verifier");
7522
7523 uint64_t Saturate =
7524 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7525
7526 SDValue FloatVal = getValue(I.getArgOperand(0));
7527
7528 SDValue SemConst =
7529 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7530 SDValue RoundConst =
7531 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7532 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7533 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7534 SemConst, RoundConst, SatConst));
7535 return;
7536 }
7537 case Intrinsic::set_rounding:
7538 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7539 {getRoot(), getValue(I.getArgOperand(0))});
7540 setValue(&I, Res);
7541 DAG.setRoot(Res.getValue(0));
7542 return;
7543 case Intrinsic::is_fpclass: {
7544 const DataLayout DLayout = DAG.getDataLayout();
7545 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7546 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7547 FPClassTest Test = static_cast<FPClassTest>(
7548 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7549 MachineFunction &MF = DAG.getMachineFunction();
7550 const Function &F = MF.getFunction();
7551 SDValue Op = getValue(I.getArgOperand(0));
7552 SDNodeFlags Flags;
7553 Flags.setNoFPExcept(
7554 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7555 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7556 // expansion can use illegal types. Making expansion early allows
7557 // legalizing these types prior to selection.
7558 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7560 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7561 setValue(&I, Result);
7562 return;
7563 }
7564
7565 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7566 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7567 setValue(&I, V);
7568 return;
7569 }
7570 case Intrinsic::get_fpenv: {
7571 const DataLayout DLayout = DAG.getDataLayout();
7572 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7573 Align TempAlign = DAG.getEVTAlign(EnvVT);
7574 SDValue Chain = getRoot();
7575 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7576 // and temporary storage in stack.
7578 Res = DAG.getNode(
7579 ISD::GET_FPENV, sdl,
7580 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7581 MVT::Other),
7582 Chain);
7583 } else {
7584 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7585 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7586 auto MPI =
7587 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7588 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7590 TempAlign);
7591 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7592 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7593 }
7594 setValue(&I, Res);
7595 DAG.setRoot(Res.getValue(1));
7596 return;
7597 }
7598 case Intrinsic::set_fpenv: {
7599 SDValue Env = getValue(I.getArgOperand(0));
7600 EVT EnvVT = Env.getValueType();
7601 Align TempAlign = DAG.getEVTAlign(EnvVT);
7602 SDValue Chain = getRoot();
7603 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7604 // environment from memory.
7606 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7607 } else {
7608 // Allocate space in stack, copy environment bits into it and use this
7609 // memory in SET_FPENV_MEM.
7610 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7611 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7612 auto MPI =
7613 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7614 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7616 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7618 TempAlign);
7619 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7620 }
7621 DAG.setRoot(Chain);
7622 return;
7623 }
7624 case Intrinsic::reset_fpenv:
7625 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7626 return;
7627 case Intrinsic::get_fpmode:
7628 Res = DAG.getNode(
7629 ISD::GET_FPMODE, sdl,
7630 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7631 MVT::Other),
7632 DAG.getRoot());
7633 setValue(&I, Res);
7634 DAG.setRoot(Res.getValue(1));
7635 return;
7636 case Intrinsic::set_fpmode:
7637 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7638 getValue(I.getArgOperand(0)));
7639 DAG.setRoot(Res);
7640 return;
7641 case Intrinsic::reset_fpmode: {
7642 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7643 DAG.setRoot(Res);
7644 return;
7645 }
7646 case Intrinsic::pcmarker: {
7647 SDValue Tmp = getValue(I.getArgOperand(0));
7648 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7649 return;
7650 }
7651 case Intrinsic::readcyclecounter: {
7652 SDValue Op = getRoot();
7653 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7654 DAG.getVTList(MVT::i64, MVT::Other), Op);
7655 setValue(&I, Res);
7656 DAG.setRoot(Res.getValue(1));
7657 return;
7658 }
7659 case Intrinsic::readsteadycounter: {
7660 SDValue Op = getRoot();
7661 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7662 DAG.getVTList(MVT::i64, MVT::Other), Op);
7663 setValue(&I, Res);
7664 DAG.setRoot(Res.getValue(1));
7665 return;
7666 }
7667 case Intrinsic::bitreverse:
7668 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7669 getValue(I.getArgOperand(0)).getValueType(),
7670 getValue(I.getArgOperand(0))));
7671 return;
7672 case Intrinsic::bswap:
7673 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7674 getValue(I.getArgOperand(0)).getValueType(),
7675 getValue(I.getArgOperand(0))));
7676 return;
7677 case Intrinsic::cttz: {
7678 SDValue Arg = getValue(I.getArgOperand(0));
7679 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7680 EVT Ty = Arg.getValueType();
7681 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7682 sdl, Ty, Arg));
7683 return;
7684 }
7685 case Intrinsic::ctlz: {
7686 SDValue Arg = getValue(I.getArgOperand(0));
7687 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7688 EVT Ty = Arg.getValueType();
7689 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7690 sdl, Ty, Arg));
7691 return;
7692 }
7693 case Intrinsic::ctpop: {
7694 SDValue Arg = getValue(I.getArgOperand(0));
7695 EVT Ty = Arg.getValueType();
7696 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7697 return;
7698 }
7699 case Intrinsic::fshl:
7700 case Intrinsic::fshr: {
7701 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7702 SDValue X = getValue(I.getArgOperand(0));
7703 SDValue Y = getValue(I.getArgOperand(1));
7704 SDValue Z = getValue(I.getArgOperand(2));
7705 EVT VT = X.getValueType();
7706
7707 if (X == Y) {
7708 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7709 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7710 } else {
7711 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7712 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7713 }
7714 return;
7715 }
7716 case Intrinsic::clmul: {
7717 SDValue X = getValue(I.getArgOperand(0));
7718 SDValue Y = getValue(I.getArgOperand(1));
7719 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7720 return;
7721 }
7722 case Intrinsic::pext: {
7723 SDValue X = getValue(I.getArgOperand(0));
7724 SDValue Y = getValue(I.getArgOperand(1));
7725 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7726 return;
7727 }
7728 case Intrinsic::pdep: {
7729 SDValue X = getValue(I.getArgOperand(0));
7730 SDValue Y = getValue(I.getArgOperand(1));
7731 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7732 return;
7733 }
7734 case Intrinsic::smulh:
7735 case Intrinsic::umulh: {
7736 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7737 SDValue X = getValue(I.getArgOperand(0));
7738 SDValue Y = getValue(I.getArgOperand(1));
7739 setValue(&I, DAG.getNode(Opc, sdl, X.getValueType(), X, Y));
7740 return;
7741 }
7742 case Intrinsic::sadd_sat: {
7743 SDValue Op1 = getValue(I.getArgOperand(0));
7744 SDValue Op2 = getValue(I.getArgOperand(1));
7745 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7746 return;
7747 }
7748 case Intrinsic::uadd_sat: {
7749 SDValue Op1 = getValue(I.getArgOperand(0));
7750 SDValue Op2 = getValue(I.getArgOperand(1));
7751 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7752 return;
7753 }
7754 case Intrinsic::ssub_sat: {
7755 SDValue Op1 = getValue(I.getArgOperand(0));
7756 SDValue Op2 = getValue(I.getArgOperand(1));
7757 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7758 return;
7759 }
7760 case Intrinsic::usub_sat: {
7761 SDValue Op1 = getValue(I.getArgOperand(0));
7762 SDValue Op2 = getValue(I.getArgOperand(1));
7763 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7764 return;
7765 }
7766 case Intrinsic::sshl_sat:
7767 case Intrinsic::ushl_sat: {
7768 SDValue Op1 = getValue(I.getArgOperand(0));
7769 SDValue Op2 = getValue(I.getArgOperand(1));
7770
7771 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7772 Op1.getValueType(), DAG.getDataLayout());
7773
7774 // Coerce the shift amount to the right type if we can. This exposes the
7775 // truncate or zext to optimization early.
7776 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7777 assert(ShiftTy.getSizeInBits() >=
7779 "Unexpected shift type");
7780 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7781 }
7782
7783 unsigned Opc =
7784 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7785 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7786 return;
7787 }
7788 case Intrinsic::smul_fix:
7789 case Intrinsic::umul_fix:
7790 case Intrinsic::smul_fix_sat:
7791 case Intrinsic::umul_fix_sat: {
7792 SDValue Op1 = getValue(I.getArgOperand(0));
7793 SDValue Op2 = getValue(I.getArgOperand(1));
7794 SDValue Op3 = getValue(I.getArgOperand(2));
7795 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7796 Op1.getValueType(), Op1, Op2, Op3));
7797 return;
7798 }
7799 case Intrinsic::sdiv_fix:
7800 case Intrinsic::udiv_fix:
7801 case Intrinsic::sdiv_fix_sat:
7802 case Intrinsic::udiv_fix_sat: {
7803 SDValue Op1 = getValue(I.getArgOperand(0));
7804 SDValue Op2 = getValue(I.getArgOperand(1));
7805 SDValue Op3 = getValue(I.getArgOperand(2));
7807 Op1, Op2, Op3, DAG, TLI));
7808 return;
7809 }
7810 case Intrinsic::smax: {
7811 SDValue Op1 = getValue(I.getArgOperand(0));
7812 SDValue Op2 = getValue(I.getArgOperand(1));
7813 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7814 return;
7815 }
7816 case Intrinsic::smin: {
7817 SDValue Op1 = getValue(I.getArgOperand(0));
7818 SDValue Op2 = getValue(I.getArgOperand(1));
7819 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7820 return;
7821 }
7822 case Intrinsic::umax: {
7823 SDValue Op1 = getValue(I.getArgOperand(0));
7824 SDValue Op2 = getValue(I.getArgOperand(1));
7825 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7826 return;
7827 }
7828 case Intrinsic::umin: {
7829 SDValue Op1 = getValue(I.getArgOperand(0));
7830 SDValue Op2 = getValue(I.getArgOperand(1));
7831 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7832 return;
7833 }
7834 case Intrinsic::abs: {
7835 SDValue Op1 = getValue(I.getArgOperand(0));
7836 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7837 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7838 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7839 return;
7840 }
7841 case Intrinsic::scmp: {
7842 SDValue Op1 = getValue(I.getArgOperand(0));
7843 SDValue Op2 = getValue(I.getArgOperand(1));
7844 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7845 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7846 break;
7847 }
7848 case Intrinsic::ucmp: {
7849 SDValue Op1 = getValue(I.getArgOperand(0));
7850 SDValue Op2 = getValue(I.getArgOperand(1));
7851 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7852 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7853 break;
7854 }
7855 case Intrinsic::stackaddress:
7856 case Intrinsic::stacksave: {
7857 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7859 SDValue Op = getRoot();
7860 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7861 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7862 setValue(&I, Res);
7863 DAG.setRoot(Res.getValue(1));
7864 return;
7865 }
7866 case Intrinsic::stackrestore:
7867 Res = getValue(I.getArgOperand(0));
7868 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7869 return;
7870 case Intrinsic::get_dynamic_area_offset: {
7871 SDValue Op = getRoot();
7872 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7873 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7874 Op);
7875 DAG.setRoot(Op);
7876 setValue(&I, Res);
7877 return;
7878 }
7879 case Intrinsic::stackguard: {
7880 MachineFunction &MF = DAG.getMachineFunction();
7881 const Module &M = *MF.getFunction().getParent();
7882 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7883 SDValue Chain = getRoot();
7884 if (TLI.useLoadStackGuardNode(M)) {
7885 Res = getLoadStackGuard(DAG, sdl, Chain);
7886 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7887 } else {
7888 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7889 if (!Global) {
7890 LLVMContext &Ctx = *DAG.getContext();
7891 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7892 setValue(&I, DAG.getPOISON(PtrTy));
7893 return;
7894 }
7895
7896 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7897 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7898 MachinePointerInfo(Global, 0), Align,
7900 }
7901 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7902 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7903 // post-RA expansion of LOAD_STACK_GUARD.
7905 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7906 DAG.setRoot(Chain);
7907 setValue(&I, Res);
7908 return;
7909 }
7910 case Intrinsic::stackprotector: {
7911 // Emit code into the DAG to store the stack guard onto the stack.
7912 MachineFunction &MF = DAG.getMachineFunction();
7913 MachineFrameInfo &MFI = MF.getFrameInfo();
7914 const Module &M = *MF.getFunction().getParent();
7915 SDValue Src, Chain = getRoot();
7916
7918 Src = getLoadStackGuard(DAG, sdl, Chain);
7919 else
7920 Src = getValue(I.getArgOperand(0)); // The guard's value.
7921
7922 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7923
7924 int FI = FuncInfo.StaticAllocaMap[Slot];
7925 MFI.setStackProtectorIndex(FI);
7926 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7927
7928 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7929
7930 // Store the stack protector onto the stack.
7931 Res = DAG.getStore(
7932 Chain, sdl, Src, FIN,
7933 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7934 MaybeAlign(), MachineMemOperand::MOVolatile);
7935 setValue(&I, Res);
7936 DAG.setRoot(Res);
7937 return;
7938 }
7939 case Intrinsic::objectsize:
7940 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7941
7942 case Intrinsic::is_constant:
7943 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7944
7945 case Intrinsic::annotation:
7946 case Intrinsic::ptr_annotation:
7947 case Intrinsic::launder_invariant_group:
7948 // Drop the intrinsic, but forward the value
7949 setValue(&I, getValue(I.getOperand(0)));
7950 return;
7951
7952 case Intrinsic::type_test:
7953 case Intrinsic::public_type_test:
7954 case Intrinsic::type_checked_load:
7955 case Intrinsic::type_checked_load_relative: {
7956 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7957 // before code generation. Surviving until here usually indicates a
7958 // misconfiguration, for instance when devirtualization is enabled but LTO
7959 // does not actually run.
7960 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7961 *I.getFunction(),
7962 Intrinsic::getBaseName(Intrinsic) +
7963 " intrinsic must be lowered by the LowerTypeTests pass "
7964 "before code generation",
7965 sdl.getDebugLoc()));
7966
7967 // Lower the result to poison so that compilation can continue and collect
7968 // any further diagnostics.
7969 setValueToPoison(&I, sdl);
7970 return;
7971 }
7972
7973 case Intrinsic::assume:
7974 case Intrinsic::experimental_noalias_scope_decl:
7975 case Intrinsic::var_annotation:
7976 case Intrinsic::sideeffect:
7977 // Discard annotate attributes, noalias scope declarations, assumptions, and
7978 // artificial side-effects.
7979 return;
7980
7981 case Intrinsic::codeview_annotation: {
7982 // Emit a label associated with this metadata.
7983 MachineFunction &MF = DAG.getMachineFunction();
7984 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7985 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7986 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7987 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7988 DAG.setRoot(Res);
7989 return;
7990 }
7991
7992 case Intrinsic::init_trampoline: {
7993 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7994
7995 SDValue Ops[6];
7996 Ops[0] = getRoot();
7997 Ops[1] = getValue(I.getArgOperand(0));
7998 Ops[2] = getValue(I.getArgOperand(1));
7999 Ops[3] = getValue(I.getArgOperand(2));
8000 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
8001 Ops[5] = DAG.getSrcValue(F);
8002
8003 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
8004
8005 DAG.setRoot(Res);
8006 return;
8007 }
8008 case Intrinsic::adjust_trampoline:
8009 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
8010 TLI.getPointerTy(DAG.getDataLayout()),
8011 getValue(I.getArgOperand(0))));
8012 return;
8013 case Intrinsic::gcroot: {
8014 assert(DAG.getMachineFunction().getFunction().hasGC() &&
8015 "only valid in functions with gc specified, enforced by Verifier");
8016 assert(GFI && "implied by previous");
8017 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
8018 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
8019
8020 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
8021 GFI->addStackRoot(FI->getIndex(), TypeMap);
8022 return;
8023 }
8024 case Intrinsic::gcread:
8025 case Intrinsic::gcwrite:
8026 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
8027 case Intrinsic::get_rounding:
8028 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
8029 setValue(&I, Res);
8030 DAG.setRoot(Res.getValue(1));
8031 return;
8032
8033 case Intrinsic::expect:
8034 case Intrinsic::expect_with_probability:
8035 // Just replace __builtin_expect(exp, c) and
8036 // __builtin_expect_with_probability(exp, c, p) with EXP.
8037 setValue(&I, getValue(I.getArgOperand(0)));
8038 return;
8039
8040 case Intrinsic::ubsantrap:
8041 case Intrinsic::debugtrap:
8042 case Intrinsic::trap: {
8043 StringRef TrapFuncName =
8044 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
8045 if (TrapFuncName.empty()) {
8046 switch (Intrinsic) {
8047 case Intrinsic::trap:
8048 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
8049 break;
8050 case Intrinsic::debugtrap:
8051 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
8052 break;
8053 case Intrinsic::ubsantrap:
8054 DAG.setRoot(DAG.getNode(
8055 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
8056 DAG.getTargetConstant(
8057 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
8058 MVT::i32)));
8059 break;
8060 default: llvm_unreachable("unknown trap intrinsic");
8061 }
8062 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
8063 I.hasFnAttr(Attribute::NoMerge));
8064 return;
8065 }
8067 if (Intrinsic == Intrinsic::ubsantrap) {
8068 Value *Arg = I.getArgOperand(0);
8069 Args.emplace_back(Arg, getValue(Arg),
8070 LibInfo->getExtAttrForI8Param(/*Signed=*/false));
8071 }
8072
8073 TargetLowering::CallLoweringInfo CLI(DAG);
8074 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
8075 CallingConv::C, I.getType(),
8076 DAG.getExternalSymbol(TrapFuncName.data(),
8077 TLI.getPointerTy(DAG.getDataLayout())),
8078 std::move(Args));
8079 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
8080 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8081 DAG.setRoot(Result.second);
8082 return;
8083 }
8084
8085 case Intrinsic::allow_runtime_check:
8086 case Intrinsic::allow_ubsan_check:
8087 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
8088 return;
8089
8090 case Intrinsic::uadd_with_overflow:
8091 case Intrinsic::sadd_with_overflow:
8092 case Intrinsic::usub_with_overflow:
8093 case Intrinsic::ssub_with_overflow:
8094 case Intrinsic::umul_with_overflow:
8095 case Intrinsic::smul_with_overflow: {
8097 switch (Intrinsic) {
8098 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8099 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
8100 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
8101 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
8102 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
8103 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
8104 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
8105 }
8106 SDValue Op1 = getValue(I.getArgOperand(0));
8107 SDValue Op2 = getValue(I.getArgOperand(1));
8108
8109 EVT ResultVT = Op1.getValueType();
8110 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
8111
8112 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
8113 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
8114 return;
8115 }
8116 case Intrinsic::prefetch: {
8117 SDValue Ops[5];
8118 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8120 Ops[0] = DAG.getRoot();
8121 Ops[1] = getValue(I.getArgOperand(0));
8122 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
8123 MVT::i32);
8124 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
8125 MVT::i32);
8126 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
8127 MVT::i32);
8128 SDValue Result = DAG.getMemIntrinsicNode(
8129 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
8130 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
8131 /* align */ std::nullopt, Flags);
8132
8133 // Chain the prefetch in parallel with any pending loads, to stay out of
8134 // the way of later optimizations.
8135 PendingLoads.push_back(Result);
8136 Result = getRoot();
8137 DAG.setRoot(Result);
8138 return;
8139 }
8140 case Intrinsic::lifetime_start:
8141 case Intrinsic::lifetime_end: {
8142 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
8143 // Stack coloring is not enabled in O0, discard region information.
8144 if (TM.getOptLevel() == CodeGenOptLevel::None)
8145 return;
8146
8147 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
8148 if (!LifetimeObject)
8149 return;
8150
8151 // First check that the Alloca is static, otherwise it won't have a
8152 // valid frame index.
8153 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
8154 if (SI == FuncInfo.StaticAllocaMap.end())
8155 return;
8156
8157 const int FrameIndex = SI->second;
8158 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
8159 DAG.setRoot(Res);
8160 return;
8161 }
8162 case Intrinsic::pseudoprobe: {
8163 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
8164 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8165 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
8166 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
8167 DAG.setRoot(Res);
8168 return;
8169 }
8170 case Intrinsic::invariant_start:
8171 // Discard region information.
8172 setValue(&I,
8173 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
8174 return;
8175 case Intrinsic::invariant_end:
8176 // Discard region information.
8177 return;
8178 case Intrinsic::clear_cache: {
8179 SDValue InputChain = DAG.getRoot();
8180 SDValue StartVal = getValue(I.getArgOperand(0));
8181 SDValue EndVal = getValue(I.getArgOperand(1));
8182 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
8183 {InputChain, StartVal, EndVal});
8184 setValue(&I, Res);
8185 DAG.setRoot(Res);
8186 return;
8187 }
8188 case Intrinsic::donothing:
8189 case Intrinsic::seh_try_begin:
8190 case Intrinsic::seh_scope_begin:
8191 case Intrinsic::seh_try_end:
8192 case Intrinsic::seh_scope_end:
8193 // ignore
8194 return;
8195 case Intrinsic::experimental_stackmap:
8196 visitStackmap(I);
8197 return;
8198 case Intrinsic::experimental_patchpoint_void:
8199 case Intrinsic::experimental_patchpoint:
8200 visitPatchpoint(I);
8201 return;
8202 case Intrinsic::experimental_gc_statepoint:
8204 return;
8205 case Intrinsic::experimental_gc_result:
8206 visitGCResult(cast<GCResultInst>(I));
8207 return;
8208 case Intrinsic::experimental_gc_relocate:
8209 visitGCRelocate(cast<GCRelocateInst>(I));
8210 return;
8211 case Intrinsic::instrprof_cover:
8212 llvm_unreachable("instrprof failed to lower a cover");
8213 case Intrinsic::instrprof_increment:
8214 llvm_unreachable("instrprof failed to lower an increment");
8215 case Intrinsic::instrprof_timestamp:
8216 llvm_unreachable("instrprof failed to lower a timestamp");
8217 case Intrinsic::instrprof_value_profile:
8218 llvm_unreachable("instrprof failed to lower a value profiling call");
8219 case Intrinsic::instrprof_mcdc_parameters:
8220 llvm_unreachable("instrprof failed to lower mcdc parameters");
8221 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8222 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8223 case Intrinsic::localescape: {
8224 MachineFunction &MF = DAG.getMachineFunction();
8225 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8226
8227 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8228 // is the same on all targets.
8229 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8230 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8231 if (isa<ConstantPointerNull>(Arg))
8232 continue; // Skip null pointers. They represent a hole in index space.
8233 AllocaInst *Slot = cast<AllocaInst>(Arg);
8234 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8235 "can only escape static allocas");
8236 int FI = FuncInfo.StaticAllocaMap[Slot];
8237 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8239 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8240 TII->get(TargetOpcode::LOCAL_ESCAPE))
8241 .addSym(FrameAllocSym)
8242 .addFrameIndex(FI);
8243 }
8244
8245 return;
8246 }
8247
8248 case Intrinsic::localrecover: {
8249 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8250 MachineFunction &MF = DAG.getMachineFunction();
8251
8252 // Get the symbol that defines the frame offset.
8253 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8254 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8255 unsigned IdxVal =
8256 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8257 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8259
8260 Value *FP = I.getArgOperand(1);
8261 SDValue FPVal = getValue(FP);
8262 EVT PtrVT = FPVal.getValueType();
8263
8264 // Create a MCSymbol for the label to avoid any target lowering
8265 // that would make this PC relative.
8266 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8267 SDValue OffsetVal =
8268 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8269
8270 // Add the offset to the FP.
8271 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8272 setValue(&I, Add);
8273
8274 return;
8275 }
8276
8277 case Intrinsic::fake_use: {
8278 Value *V = I.getArgOperand(0);
8279 SDValue Ops[2];
8280 // For Values not declared or previously used in this basic block, the
8281 // NodeMap will not have an entry, and `getValue` will assert if V has no
8282 // valid register value.
8283 auto FakeUseValue = [&]() -> SDValue {
8284 SDValue &N = NodeMap[V];
8285 if (N.getNode())
8286 return N;
8287
8288 // If there's a virtual register allocated and initialized for this
8289 // value, use it.
8290 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8291 return copyFromReg;
8292 // FIXME: Do we want to preserve constants? It seems pointless.
8293 if (isa<Constant>(V))
8294 return getValue(V);
8295 return SDValue();
8296 }();
8297 if (!FakeUseValue || FakeUseValue.isUndef())
8298 return;
8299 Ops[0] = getRoot();
8300 Ops[1] = FakeUseValue;
8301 // Also, do not translate a fake use with an undef operand, or any other
8302 // empty SDValues.
8303 if (!Ops[1] || Ops[1].isUndef())
8304 return;
8305 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8306 return;
8307 }
8308
8309 case Intrinsic::reloc_none: {
8310 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8311 StringRef SymbolName = cast<MDString>(MD)->getString();
8312 SDValue Ops[2] = {
8313 getRoot(),
8314 DAG.getTargetExternalSymbol(
8315 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8316 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8317 return;
8318 }
8319
8320 case Intrinsic::cond_loop: {
8321 SDValue InputChain = DAG.getRoot();
8322 SDValue P = getValue(I.getArgOperand(0));
8323 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8324 {InputChain, P});
8325 setValue(&I, Res);
8326 DAG.setRoot(Res);
8327 return;
8328 }
8329
8330 case Intrinsic::eh_exceptionpointer:
8331 case Intrinsic::eh_exceptioncode: {
8332 // Get the exception pointer vreg, copy from it, and resize it to fit.
8333 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8334 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8335 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8336 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8337 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8338 if (Intrinsic == Intrinsic::eh_exceptioncode)
8339 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8340 setValue(&I, N);
8341 return;
8342 }
8343 case Intrinsic::xray_customevent: {
8344 // Here we want to make sure that the intrinsic behaves as if it has a
8345 // specific calling convention.
8346 const auto &Triple = DAG.getTarget().getTargetTriple();
8347 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8348 Triple.getArch() != Triple::hexagon)
8349 return;
8350
8352
8353 // We want to say that we always want the arguments in registers.
8354 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8355 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8356 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8357 SDValue Chain = getRoot();
8358 Ops.push_back(LogEntryVal);
8359 Ops.push_back(StrSizeVal);
8360 Ops.push_back(Chain);
8361
8362 // We need to enforce the calling convention for the callsite, so that
8363 // argument ordering is enforced correctly, and that register allocation can
8364 // see that some registers may be assumed clobbered and have to preserve
8365 // them across calls to the intrinsic.
8366 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8367 sdl, NodeTys, Ops);
8368 SDValue patchableNode = SDValue(MN, 0);
8369 DAG.setRoot(patchableNode);
8370 setValue(&I, patchableNode);
8371 return;
8372 }
8373 case Intrinsic::xray_typedevent: {
8374 // Here we want to make sure that the intrinsic behaves as if it has a
8375 // specific calling convention.
8376 const auto &Triple = DAG.getTarget().getTargetTriple();
8377 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8378 Triple.getArch() != Triple::hexagon)
8379 return;
8380
8382
8383 // We want to say that we always want the arguments in registers.
8384 // It's unclear to me how manipulating the selection DAG here forces callers
8385 // to provide arguments in registers instead of on the stack.
8386 SDValue LogTypeId = getValue(I.getArgOperand(0));
8387 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8388 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8389 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8390 SDValue Chain = getRoot();
8391 Ops.push_back(LogTypeId);
8392 Ops.push_back(LogEntryVal);
8393 Ops.push_back(StrSizeVal);
8394 Ops.push_back(Chain);
8395
8396 // We need to enforce the calling convention for the callsite, so that
8397 // argument ordering is enforced correctly, and that register allocation can
8398 // see that some registers may be assumed clobbered and have to preserve
8399 // them across calls to the intrinsic.
8400 MachineSDNode *MN = DAG.getMachineNode(
8401 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8402 SDValue patchableNode = SDValue(MN, 0);
8403 DAG.setRoot(patchableNode);
8404 setValue(&I, patchableNode);
8405 return;
8406 }
8407 case Intrinsic::experimental_deoptimize:
8409 return;
8410 case Intrinsic::stepvector:
8411 visitStepVector(I);
8412 return;
8413 case Intrinsic::vector_reduce_fadd:
8414 case Intrinsic::vector_reduce_fmul:
8415 case Intrinsic::vector_reduce_add:
8416 case Intrinsic::vector_reduce_mul:
8417 case Intrinsic::vector_reduce_and:
8418 case Intrinsic::vector_reduce_or:
8419 case Intrinsic::vector_reduce_xor:
8420 case Intrinsic::vector_reduce_smax:
8421 case Intrinsic::vector_reduce_smin:
8422 case Intrinsic::vector_reduce_umax:
8423 case Intrinsic::vector_reduce_umin:
8424 case Intrinsic::vector_reduce_fmax:
8425 case Intrinsic::vector_reduce_fmin:
8426 case Intrinsic::vector_reduce_fmaximum:
8427 case Intrinsic::vector_reduce_fminimum:
8428 case Intrinsic::vector_reduce_fmaximumnum:
8429 case Intrinsic::vector_reduce_fminimumnum:
8430 visitVectorReduce(I, Intrinsic);
8431 return;
8432
8433 case Intrinsic::icall_branch_funnel: {
8435 Ops.push_back(getValue(I.getArgOperand(0)));
8436
8437 int64_t Offset;
8439 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8440 if (!Base)
8442 "llvm.icall.branch.funnel operand must be a GlobalValue");
8443 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8444
8445 struct BranchFunnelTarget {
8446 int64_t Offset;
8448 };
8450
8451 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8453 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8454 if (ElemBase != Base)
8455 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8456 "to the same GlobalValue");
8457
8458 SDValue Val = getValue(I.getArgOperand(Op + 1));
8459 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8460 if (!GA)
8462 "llvm.icall.branch.funnel operand must be a GlobalValue");
8463 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8464 GA->getGlobal(), sdl, Val.getValueType(),
8465 GA->getOffset())});
8466 }
8467 llvm::sort(Targets,
8468 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8469 return T1.Offset < T2.Offset;
8470 });
8471
8472 for (auto &T : Targets) {
8473 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8474 Ops.push_back(T.Target);
8475 }
8476
8477 Ops.push_back(DAG.getRoot()); // Chain
8478 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8479 MVT::Other, Ops),
8480 0);
8481 DAG.setRoot(N);
8482 setValue(&I, N);
8483 HasTailCall = true;
8484 return;
8485 }
8486
8487 case Intrinsic::wasm_landingpad_index:
8488 // Information this intrinsic contained has been transferred to
8489 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8490 // delete it now.
8491 return;
8492
8493 case Intrinsic::aarch64_settag:
8494 case Intrinsic::aarch64_settag_zero: {
8495 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8496 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8498 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8499 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8500 ZeroMemory);
8501 DAG.setRoot(Val);
8502 setValue(&I, Val);
8503 return;
8504 }
8505 case Intrinsic::amdgcn_cs_chain: {
8506 // At this point we don't care if it's amdgpu_cs_chain or
8507 // amdgpu_cs_chain_preserve.
8509
8510 Type *RetTy = I.getType();
8511 assert(RetTy->isVoidTy() && "Should not return");
8512
8513 SDValue Callee = getValue(I.getOperand(0));
8514
8515 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8516 // We'll also tack the value of the EXEC mask at the end.
8518 Args.reserve(3);
8519
8520 for (unsigned Idx : {2, 3, 1}) {
8521 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8522 I.getOperand(Idx)->getType());
8523 Arg.setAttributes(&I, Idx);
8524 Args.push_back(Arg);
8525 }
8526
8527 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8528 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8529 Args[2].IsInReg = true; // EXEC should be inreg
8530
8531 // Forward the flags and any additional arguments.
8532 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8533 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8534 I.getOperand(Idx)->getType());
8535 Arg.setAttributes(&I, Idx);
8536 Args.push_back(Arg);
8537 }
8538
8539 TargetLowering::CallLoweringInfo CLI(DAG);
8540 CLI.setDebugLoc(getCurSDLoc())
8541 .setChain(getRoot())
8542 .setCallee(CC, RetTy, Callee, std::move(Args))
8543 .setNoReturn(true)
8544 .setTailCall(true)
8545 .setConvergent(I.isConvergent());
8546 CLI.CB = &I;
8547 std::pair<SDValue, SDValue> Result =
8548 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8549 (void)Result;
8550 assert(!Result.first.getNode() && !Result.second.getNode() &&
8551 "Should've lowered as tail call");
8552
8553 HasTailCall = true;
8554 return;
8555 }
8556 case Intrinsic::amdgcn_call_whole_wave: {
8558 bool isTailCall = I.isTailCall();
8559
8560 // The first argument is the callee. Skip it when assembling the call args.
8561 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8562 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8563 I.getArgOperand(Idx)->getType());
8564 Arg.setAttributes(&I, Idx);
8565
8566 // If we have an explicit sret argument that is an Instruction, (i.e., it
8567 // might point to function-local memory), we can't meaningfully tail-call.
8568 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8569 isTailCall = false;
8570
8571 Args.push_back(Arg);
8572 }
8573
8574 SDValue ConvControlToken;
8575 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8576 auto *Token = Bundle->Inputs[0].get();
8577 ConvControlToken = getValue(Token);
8578 }
8579
8580 TargetLowering::CallLoweringInfo CLI(DAG);
8581 CLI.setDebugLoc(getCurSDLoc())
8582 .setChain(getRoot())
8583 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8584 getValue(I.getArgOperand(0)), std::move(Args))
8585 .setTailCall(isTailCall && canTailCall(I))
8586 .setIsPreallocated(
8587 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8588 .setConvergent(I.isConvergent())
8589 .setConvergenceControlToken(ConvControlToken);
8590 CLI.CB = &I;
8591
8592 std::pair<SDValue, SDValue> Result =
8593 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8594
8595 if (Result.first.getNode())
8596 setValue(&I, Result.first);
8597 return;
8598 }
8599 case Intrinsic::ptrmask: {
8600 SDValue Ptr = getValue(I.getOperand(0));
8601 SDValue Mask = getValue(I.getOperand(1));
8602
8603 // On arm64_32, pointers are 32 bits when stored in memory, but
8604 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8605 // match the index type, but the pointer is 64 bits, so the mask must be
8606 // zero-extended up to 64 bits to match the pointer.
8607 EVT PtrVT =
8608 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8609 EVT MemVT =
8610 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8611 assert(PtrVT == Ptr.getValueType());
8612 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8613 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8614 // 128-bit, so we have to pad the mask with ones for unused bits.
8615 auto HighOnes = DAG.getNode(
8616 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8617 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8618 PtrVT, sdl));
8619 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8620 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8621 } else if (Mask.getValueType() != PtrVT)
8622 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8623
8624 assert(Mask.getValueType() == PtrVT);
8625 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8626 return;
8627 }
8628 case Intrinsic::threadlocal_address: {
8629 setValue(&I, getValue(I.getOperand(0)));
8630 return;
8631 }
8632 case Intrinsic::get_active_lane_mask: {
8633 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8634 SDValue Index = getValue(I.getOperand(0));
8635 SDValue TripCount = getValue(I.getOperand(1));
8636 EVT ElementVT = Index.getValueType();
8637
8638 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8639 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8640 TripCount));
8641 return;
8642 }
8643
8644 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8645 CCVT.getVectorElementCount());
8646
8647 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8648 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8649 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8650 SDValue VectorInduction = DAG.getNode(
8651 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8652 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8653 VectorTripCount, ISD::CondCode::SETULT);
8654 setValue(&I, SetCC);
8655 return;
8656 }
8657 case Intrinsic::mask_beforefirst: {
8658 SDValue Op = getValue(I.getOperand(0));
8659 setValue(&I,
8660 DAG.getNode(ISD::MASK_BEFOREFIRST, sdl, Op.getValueType(), Op));
8661 return;
8662 }
8663 case Intrinsic::experimental_get_vector_length: {
8664 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8665 "Expected positive VF");
8666 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8667 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8668
8669 SDValue Count = getValue(I.getOperand(0));
8670 EVT CountVT = Count.getValueType();
8671
8672 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8673 visitTargetIntrinsic(I, Intrinsic);
8674 return;
8675 }
8676
8677 // Expand to a umin between the trip count and the maximum elements the type
8678 // can hold.
8679 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8680
8681 // Extend the trip count to at least the result VT.
8682 if (CountVT.bitsLT(VT)) {
8683 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8684 CountVT = VT;
8685 }
8686
8687 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8689
8690 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8691 // Clip to the result type if needed.
8692 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8693
8694 setValue(&I, Trunc);
8695 return;
8696 }
8697 case Intrinsic::vector_partial_reduce_add: {
8698 SDValue Acc = getValue(I.getOperand(0));
8699 SDValue Input = getValue(I.getOperand(1));
8700 setValue(&I,
8701 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8702 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8703 return;
8704 }
8705 case Intrinsic::vector_partial_reduce_fadd: {
8706 SDNodeFlags Flags;
8707 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
8708 Flags.copyFMF(*FPOp);
8709 SDValue Acc = getValue(I.getOperand(0));
8710 SDValue Input = getValue(I.getOperand(1));
8711 setValue(&I, DAG.getNode(ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(),
8712 Acc, Input,
8713 DAG.getConstantFP(1.0, sdl, Input.getValueType()),
8714 Flags));
8715 return;
8716 }
8717 case Intrinsic::experimental_cttz_elts: {
8718 SDValue Op = getValue(I.getOperand(0));
8719 EVT OpVT = Op.getValueType();
8720 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8721 bool ZeroIsPoison =
8722 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8723 if (OpVT.getVectorElementType() != MVT::i1) {
8724 // Compare the input vector elements to zero & use to count trailing
8725 // zeros.
8726 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8727 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8728 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8729 }
8730 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8732 sdl, RetTy, Op));
8733 return;
8734 }
8735 case Intrinsic::vector_insert: {
8736 SDValue Vec = getValue(I.getOperand(0));
8737 SDValue SubVec = getValue(I.getOperand(1));
8738 SDValue Index = getValue(I.getOperand(2));
8739
8740 // The intrinsic's index type is i64, but the SDNode requires an index type
8741 // suitable for the target. Convert the index as required.
8742 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8743 if (Index.getValueType() != VectorIdxTy)
8744 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8745
8746 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8747 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8748 Index));
8749 return;
8750 }
8751 case Intrinsic::vector_extract: {
8752 SDValue Vec = getValue(I.getOperand(0));
8753 SDValue Index = getValue(I.getOperand(1));
8754 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8755
8756 // The intrinsic's index type is i64, but the SDNode requires an index type
8757 // suitable for the target. Convert the index as required.
8758 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8759 if (Index.getValueType() != VectorIdxTy)
8760 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8761
8762 setValue(&I,
8763 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8764 return;
8765 }
8766 case Intrinsic::experimental_vector_match: {
8767 SDValue Op1 = getValue(I.getOperand(0));
8768 SDValue Op2 = getValue(I.getOperand(1));
8769 SDValue Mask = getValue(I.getOperand(2));
8770 EVT ResVT = Mask.getValueType();
8771 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8772 return;
8773 }
8774 case Intrinsic::vector_reverse:
8775 visitVectorReverse(I);
8776 return;
8777 case Intrinsic::vector_splice_left:
8778 case Intrinsic::vector_splice_right:
8779 visitVectorSplice(I);
8780 return;
8781 case Intrinsic::callbr_landingpad:
8782 visitCallBrLandingPad(I);
8783 return;
8784 case Intrinsic::vector_interleave2:
8785 visitVectorInterleave(I, 2);
8786 return;
8787 case Intrinsic::vector_interleave3:
8788 visitVectorInterleave(I, 3);
8789 return;
8790 case Intrinsic::vector_interleave4:
8791 visitVectorInterleave(I, 4);
8792 return;
8793 case Intrinsic::vector_interleave5:
8794 visitVectorInterleave(I, 5);
8795 return;
8796 case Intrinsic::vector_interleave6:
8797 visitVectorInterleave(I, 6);
8798 return;
8799 case Intrinsic::vector_interleave7:
8800 visitVectorInterleave(I, 7);
8801 return;
8802 case Intrinsic::vector_interleave8:
8803 visitVectorInterleave(I, 8);
8804 return;
8805 case Intrinsic::vector_deinterleave2:
8806 visitVectorDeinterleave(I, 2);
8807 return;
8808 case Intrinsic::vector_deinterleave3:
8809 visitVectorDeinterleave(I, 3);
8810 return;
8811 case Intrinsic::vector_deinterleave4:
8812 visitVectorDeinterleave(I, 4);
8813 return;
8814 case Intrinsic::vector_deinterleave5:
8815 visitVectorDeinterleave(I, 5);
8816 return;
8817 case Intrinsic::vector_deinterleave6:
8818 visitVectorDeinterleave(I, 6);
8819 return;
8820 case Intrinsic::vector_deinterleave7:
8821 visitVectorDeinterleave(I, 7);
8822 return;
8823 case Intrinsic::vector_deinterleave8:
8824 visitVectorDeinterleave(I, 8);
8825 return;
8826 case Intrinsic::vector_repeat: {
8827 SDValue Vec = getValue(I.getOperand(0));
8828 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8829 setValue(&I, DAG.getNode(ISD::VECTOR_REPEAT, sdl, ResultVT, Vec));
8830 return;
8831 }
8832 case Intrinsic::experimental_vector_compress:
8833 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8834 getValue(I.getArgOperand(0)).getValueType(),
8835 getValue(I.getArgOperand(0)),
8836 getValue(I.getArgOperand(1)),
8837 getValue(I.getArgOperand(2)), Flags));
8838 return;
8839 case Intrinsic::vector_shuffle:
8840 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE_VAR, sdl,
8841 TLI.getValueType(DAG.getDataLayout(), I.getType()),
8842 getValue(I.getArgOperand(0)),
8843 getValue(I.getArgOperand(1)), Flags));
8844 return;
8845 case Intrinsic::experimental_convergence_anchor:
8846 case Intrinsic::experimental_convergence_entry:
8847 case Intrinsic::experimental_convergence_loop:
8848 visitConvergenceControl(I, Intrinsic);
8849 return;
8850 case Intrinsic::experimental_vector_histogram_add: {
8851 visitVectorHistogram(I, Intrinsic);
8852 return;
8853 }
8854 case Intrinsic::experimental_vector_extract_last_active: {
8855 visitVectorExtractLastActive(I, Intrinsic);
8856 return;
8857 }
8858 case Intrinsic::loop_dependence_war_mask:
8859 setValue(&I,
8861 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8862 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8863 DAG.getConstant(0, sdl, MVT::i64)));
8864 return;
8865 case Intrinsic::loop_dependence_raw_mask:
8866 setValue(&I,
8868 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8869 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8870 DAG.getConstant(0, sdl, MVT::i64)));
8871 return;
8872 case Intrinsic::masked_udiv:
8873 setValue(&I,
8874 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8875 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8876 getValue(I.getOperand(2))));
8877 return;
8878 case Intrinsic::masked_sdiv:
8879 setValue(&I,
8880 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8881 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8882 getValue(I.getOperand(2))));
8883 return;
8884 case Intrinsic::masked_urem:
8885 setValue(&I,
8886 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8887 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8888 getValue(I.getOperand(2))));
8889 return;
8890 case Intrinsic::masked_srem:
8891 setValue(&I,
8892 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8893 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8894 getValue(I.getOperand(2))));
8895 return;
8896 }
8897}
8898
8899void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8901 assert(Result.getNode()->getNumValues() == 2);
8902 SDValue OutChain = Result.getValue(1);
8903 assert(OutChain.getValueType() == MVT::Other);
8904
8905 // Instead of updating the root immediately, push the produced chain to the
8906 // appropriate list, deferring the update until the root is requested. In this
8907 // case, the nodes from the lists are chained using TokenFactor, indicating
8908 // that the operations are independent.
8909 //
8910 // In particular, the root is updated before any call that might access the
8911 // floating-point environment, except for constrained intrinsics.
8912 switch (EB) {
8915 PendingConstrainedFP.push_back(OutChain);
8916 break;
8918 PendingConstrainedFPStrict.push_back(OutChain);
8919 break;
8920 }
8921}
8922
8923void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8924 const ConstrainedFPIntrinsic &FPI) {
8925 SDLoc sdl = getCurSDLoc();
8926
8927 // We do not need to serialize constrained FP intrinsics against
8928 // each other or against (nonvolatile) loads, so they can be
8929 // chained like loads.
8931 SDValue Chain = getFPOperationRoot(EB);
8933 Opers.push_back(Chain);
8934 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8935 Opers.push_back(getValue(FPI.getArgOperand(I)));
8936
8937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8938 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8939 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8940
8941 SDNodeFlags Flags;
8943 Flags.setNoFPExcept(true);
8944
8945 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8946 Flags.copyFMF(*FPOp);
8947
8948 unsigned Opcode;
8949 switch (FPI.getIntrinsicID()) {
8950 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8951#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8952 case Intrinsic::INTRINSIC: \
8953 Opcode = ISD::STRICT_##DAGN; \
8954 break;
8955#include "llvm/IR/ConstrainedOps.def"
8956 case Intrinsic::experimental_constrained_fmuladd: {
8957 Opcode = ISD::STRICT_FMA;
8958 // Break fmuladd into fmul and fadd.
8959 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8960 Opers.pop_back();
8961 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8962 pushFPOpOutChain(Mul, EB);
8963 Opcode = ISD::STRICT_FADD;
8964 Opers.clear();
8965 Opers.push_back(Mul.getValue(1));
8966 Opers.push_back(Mul.getValue(0));
8967 Opers.push_back(getValue(FPI.getArgOperand(2)));
8968 }
8969 break;
8970 }
8971 }
8972
8973 // A few strict DAG nodes carry additional operands that are not
8974 // set up by the default code above.
8975 switch (Opcode) {
8976 default: break;
8978 Opers.push_back(
8979 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8980 break;
8981 case ISD::STRICT_FSETCC:
8982 case ISD::STRICT_FSETCCS: {
8983 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8984 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8985 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8986 Condition = getFCmpCodeWithoutNaN(Condition);
8987 Opers.push_back(DAG.getCondCode(Condition));
8988 break;
8989 }
8990 }
8991
8992 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8993 pushFPOpOutChain(Result, EB);
8994
8995 SDValue FPResult = Result.getValue(0);
8996 setValue(&FPI, FPResult);
8997}
8998
8999static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
9000 std::optional<unsigned> ResOPC;
9001 switch (VPIntrin.getIntrinsicID()) {
9002 case Intrinsic::vp_cttz_elts: {
9003 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
9004 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
9005 break;
9006 }
9007#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
9008 case Intrinsic::VPID: \
9009 ResOPC = ISD::VPSD; \
9010 break;
9011#include "llvm/IR/VPIntrinsics.def"
9012 }
9013
9014 if (!ResOPC)
9016 "Inconsistency: no SDNode available for this VPIntrinsic!");
9017
9018 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
9019 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
9020 if (VPIntrin.getFastMathFlags().allowReassoc())
9021 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
9022 : ISD::VP_REDUCE_FMUL;
9023 }
9024
9025 return *ResOPC;
9026}
9027
9028void SelectionDAGBuilder::visitVPLoad(
9029 const VPIntrinsic &VPIntrin, EVT VT,
9030 const SmallVectorImpl<SDValue> &OpValues) {
9031 SDLoc DL = getCurSDLoc();
9032 Value *PtrOperand = VPIntrin.getArgOperand(0);
9033 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9034 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9035 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9036 SDValue LD;
9037 // Do not serialize variable-length loads of constant memory with
9038 // anything.
9039 if (!Alignment)
9040 Alignment = DAG.getEVTAlign(VT);
9041 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9042 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9043 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9044 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9045 MachineMemOperand::Flags MMOFlags =
9047 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9048 MachinePointerInfo(PtrOperand), MMOFlags,
9050 MMOMetadata(AAInfo, Ranges));
9051 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9052 MMO, false /*IsExpanding */);
9053 if (AddToChain)
9054 PendingLoads.push_back(LD.getValue(1));
9055 setValue(&VPIntrin, LD);
9056}
9057
9058void SelectionDAGBuilder::visitVPLoadFF(
9059 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
9060 const SmallVectorImpl<SDValue> &OpValues) {
9061 assert(OpValues.size() == 3 && "Unexpected number of operands");
9062 SDLoc DL = getCurSDLoc();
9063 Value *PtrOperand = VPIntrin.getArgOperand(0);
9064 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9065 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9066 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
9067 SDValue LD;
9068 // Do not serialize variable-length loads of constant memory with
9069 // anything.
9070 if (!Alignment)
9071 Alignment = DAG.getEVTAlign(VT);
9072 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9073 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9074 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9075 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9076 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
9078 MMOMetadata(AAInfo, Ranges));
9079 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9080 MMO);
9081 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
9082 if (AddToChain)
9083 PendingLoads.push_back(LD.getValue(2));
9084 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
9085}
9086
9087void SelectionDAGBuilder::visitVPGather(
9088 const VPIntrinsic &VPIntrin, EVT VT,
9089 const SmallVectorImpl<SDValue> &OpValues) {
9090 SDLoc DL = getCurSDLoc();
9091 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9092 Value *PtrOperand = VPIntrin.getArgOperand(0);
9093 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9094 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9095 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9096 SDValue LD;
9097 if (!Alignment)
9098 Alignment = DAG.getEVTAlign(VT.getScalarType());
9099 unsigned AS =
9100 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9101 MachineMemOperand::Flags MMOFlags =
9103 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9104 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9105 *Alignment, MMOMetadata(AAInfo, Ranges));
9106 SDValue Base, Index, Scale;
9107 bool UniformBase =
9108 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9109 VT.getScalarStoreSize());
9110 if (!UniformBase) {
9111 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9112 Index = getValue(PtrOperand);
9113 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9114 }
9115 EVT IdxVT = Index.getValueType();
9116 EVT EltTy = IdxVT.getVectorElementType();
9117 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9118 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9119 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9120 }
9121 LD = DAG.getGatherVP(
9122 DAG.getVTList(VT, MVT::Other), VT, DL,
9123 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
9125 PendingLoads.push_back(LD.getValue(1));
9126 setValue(&VPIntrin, LD);
9127}
9128
9129void SelectionDAGBuilder::visitVPStore(
9130 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9131 SDLoc DL = getCurSDLoc();
9132 Value *PtrOperand = VPIntrin.getArgOperand(1);
9133 EVT VT = OpValues[0].getValueType();
9134 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9135 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9136 SDValue ST;
9137 if (!Alignment)
9138 Alignment = DAG.getEVTAlign(VT);
9139 SDValue Ptr = OpValues[1];
9140 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
9141 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9142 MachineMemOperand::Flags MMOFlags =
9144 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9145 MachinePointerInfo(PtrOperand), MMOFlags,
9146 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
9147 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
9148 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
9149 /* IsTruncating */ false, /*IsCompressing*/ false);
9150 DAG.setRoot(ST);
9151 setValue(&VPIntrin, ST);
9152}
9153
9154void SelectionDAGBuilder::visitVPScatter(
9155 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9156 SDLoc DL = getCurSDLoc();
9157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9158 Value *PtrOperand = VPIntrin.getArgOperand(1);
9159 EVT VT = OpValues[0].getValueType();
9160 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9161 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9162 SDValue ST;
9163 if (!Alignment)
9164 Alignment = DAG.getEVTAlign(VT.getScalarType());
9165 unsigned AS =
9166 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9167 MachineMemOperand::Flags MMOFlags =
9169 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9170 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9171 *Alignment, AAInfo);
9172 SDValue Base, Index, Scale;
9173 bool UniformBase =
9174 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9175 VT.getScalarStoreSize());
9176 if (!UniformBase) {
9177 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9178 Index = getValue(PtrOperand);
9179 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9180 }
9181 EVT IdxVT = Index.getValueType();
9182 EVT EltTy = IdxVT.getVectorElementType();
9183 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9184 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9185 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9186 }
9187 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
9188 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9189 OpValues[2], OpValues[3]},
9190 MMO, ISD::SIGNED_SCALED);
9191 DAG.setRoot(ST);
9192 setValue(&VPIntrin, ST);
9193}
9194
9195void SelectionDAGBuilder::visitVPStridedLoad(
9196 const VPIntrinsic &VPIntrin, EVT VT,
9197 const SmallVectorImpl<SDValue> &OpValues) {
9198 SDLoc DL = getCurSDLoc();
9199 Value *PtrOperand = VPIntrin.getArgOperand(0);
9200 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9201 if (!Alignment)
9202 Alignment = DAG.getEVTAlign(VT.getScalarType());
9203 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9204 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9205 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9206 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9207 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9208 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9209 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9210 MachineMemOperand::Flags MMOFlags =
9212 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9213 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9214 *Alignment, MMOMetadata(AAInfo, Ranges));
9215
9216 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
9217 OpValues[2], OpValues[3], MMO,
9218 false /*IsExpanding*/);
9219
9220 if (AddToChain)
9221 PendingLoads.push_back(LD.getValue(1));
9222 setValue(&VPIntrin, LD);
9223}
9224
9225void SelectionDAGBuilder::visitVPStridedStore(
9226 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9227 SDLoc DL = getCurSDLoc();
9228 Value *PtrOperand = VPIntrin.getArgOperand(1);
9229 EVT VT = OpValues[0].getValueType();
9230 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9231 if (!Alignment)
9232 Alignment = DAG.getEVTAlign(VT.getScalarType());
9233 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9234 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9235 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9236 MachineMemOperand::Flags MMOFlags =
9238 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9239 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9240 *Alignment, AAInfo);
9241
9242 SDValue ST = DAG.getStridedStoreVP(
9243 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9244 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9245 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9246 /*IsCompressing*/ false);
9247
9248 DAG.setRoot(ST);
9249 setValue(&VPIntrin, ST);
9250}
9251
9252void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9253 const VPIntrinsic &VPIntrin) {
9254 SDLoc DL = getCurSDLoc();
9255 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9256
9257 auto IID = VPIntrin.getIntrinsicID();
9258
9259 SmallVector<EVT, 4> ValueVTs;
9260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9261 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9262 SDVTList VTs = DAG.getVTList(ValueVTs);
9263
9264 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9265
9266 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9267 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9268 "Unexpected target EVL type");
9269
9270 // Request operands.
9271 SmallVector<SDValue, 7> OpValues;
9272 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9273 auto Op = getValue(VPIntrin.getArgOperand(I));
9274 if (I == EVLParamPos)
9275 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9276 OpValues.push_back(Op);
9277 }
9278
9279 switch (Opcode) {
9280 default: {
9281 SDNodeFlags SDFlags;
9282 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9283 SDFlags.copyFMF(*FPMO);
9284 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9285 setValue(&VPIntrin, Result);
9286 break;
9287 }
9288 case ISD::VP_LOAD:
9289 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9290 break;
9291 case ISD::VP_LOAD_FF:
9292 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9293 break;
9294 case ISD::VP_GATHER:
9295 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9296 break;
9297 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9298 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9299 break;
9300 case ISD::VP_STORE:
9301 visitVPStore(VPIntrin, OpValues);
9302 break;
9303 case ISD::VP_SCATTER:
9304 visitVPScatter(VPIntrin, OpValues);
9305 break;
9306 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9307 visitVPStridedStore(VPIntrin, OpValues);
9308 break;
9309 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9310 case ISD::VP_CTTZ_ELTS: {
9311 SDValue Result =
9312 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9313 setValue(&VPIntrin, Result);
9314 break;
9315 }
9316 }
9317}
9318
9320 const BasicBlock *EHPadBB,
9321 MCSymbol *&BeginLabel) {
9322 MachineFunction &MF = DAG.getMachineFunction();
9323
9324 // Skip emitting EH_LABEL on targets whose exception tables don't reference
9325 // them (32-bit x86 SEH, Wasm).
9327 FuncInfo.ExceptionModel)) {
9328 BeginLabel = nullptr;
9329 return Chain;
9330 }
9331
9332 // Insert a label before the invoke call to mark the try range. This can be
9333 // used to detect deletion of the invoke via the MachineModuleInfo.
9334 BeginLabel = MF.getContext().createTempSymbol();
9335
9336 // For SjLj, keep track of which landing pads go with which invokes
9337 // so as to maintain the ordering of pads in the LSDA.
9338 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9339 if (CallSiteIndex) {
9340 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9341 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9342
9343 // Now that the call site is handled, stop tracking it.
9344 FuncInfo.setCurrentCallSite(0);
9345 }
9346
9347 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9348}
9349
9350SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9351 const BasicBlock *EHPadBB,
9352 MCSymbol *BeginLabel) {
9353 // No labels were emitted.
9354 if (!BeginLabel)
9355 return Chain;
9356
9358
9359 // Insert a label at the end of the invoke call to mark the try range. This
9360 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9361 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9362 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9363
9364 // Inform MachineModuleInfo of range.
9366 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9367 // actually use outlined funclets and their LSDA info style.
9368 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9369 assert(II && "II should've been set");
9370 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9371 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9372 } else if (!isScopedEHPersonality(Pers)) {
9373 assert(EHPadBB);
9374 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9375 }
9376
9377 return Chain;
9378}
9379
9380std::pair<SDValue, SDValue>
9382 const BasicBlock *EHPadBB) {
9383 MCSymbol *BeginLabel = nullptr;
9384
9385 if (EHPadBB) {
9386 // Both PendingLoads and PendingExports must be flushed here;
9387 // this call might not return.
9388 (void)getRoot();
9389 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9390 CLI.setChain(getRoot());
9391 }
9392
9393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9394 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9395
9396 assert((CLI.IsTailCall || Result.second.getNode()) &&
9397 "Non-null chain expected with non-tail call!");
9398 assert((Result.second.getNode() || !Result.first.getNode()) &&
9399 "Null value expected with tail call!");
9400
9401 if (!Result.second.getNode()) {
9402 // As a special case, a null chain means that a tail call has been emitted
9403 // and the DAG root is already updated.
9404 HasTailCall = true;
9405
9406 // Since there's no actual continuation from this block, nothing can be
9407 // relying on us setting vregs for them.
9408 PendingExports.clear();
9409 } else {
9410 DAG.setRoot(Result.second);
9411 }
9412
9413 if (EHPadBB) {
9414 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9415 BeginLabel));
9416 Result.second = getRoot();
9417 }
9418
9419 return Result;
9420}
9421
9423 bool isMustTailCall = CB.isMustTailCall();
9424
9425 // Avoid emitting tail calls in functions with the disable-tail-calls
9426 // attribute.
9427 const Function *Caller = CB.getParent()->getParent();
9428 if (!isMustTailCall &&
9429 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9430 return false;
9431
9432 // We can't tail call inside a function with a swifterror argument. Lowering
9433 // does not support this yet. It would have to move into the swifterror
9434 // register before the call.
9435 if (DAG.hasSwiftErrorArg())
9436 return false;
9437
9438 // Check if target-independent constraints permit a tail call here.
9439 // Target-dependent constraints are checked within TLI->LowerCallTo.
9440 return isInTailCallPosition(CB, DAG.getTarget());
9441}
9442
9444 bool isTailCall, bool isMustTailCall,
9445 const BasicBlock *EHPadBB,
9446 const TargetLowering::PtrAuthInfo *PAI) {
9447 auto &DL = DAG.getDataLayout();
9448 FunctionType *FTy = CB.getFunctionType();
9449 Type *RetTy = CB.getType();
9450
9452 Args.reserve(CB.arg_size());
9453
9454 const Value *SwiftErrorVal = nullptr;
9455 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9456
9457 if (isTailCall)
9458 isTailCall = canTailCall(CB);
9459
9460 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9461 const Value *V = *I;
9462
9463 // Skip empty types
9464 if (V->getType()->isEmptyTy())
9465 continue;
9466
9467 SDValue ArgNode = getValue(V);
9468 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9469 Entry.setAttributes(&CB, I - CB.arg_begin());
9470
9471 // Use swifterror virtual register as input to the call.
9472 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9473 SwiftErrorVal = V;
9474 // We find the virtual register for the actual swifterror argument.
9475 // Instead of using the Value, we use the virtual register instead.
9476 Entry.Node =
9477 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9478 EVT(TLI.getPointerTy(DL)));
9479 }
9480
9481 Args.push_back(Entry);
9482
9483 // If we have an explicit sret argument that is an Instruction, (i.e., it
9484 // might point to function-local memory), we can't meaningfully tail-call.
9485 if (Entry.IsSRet && isa<Instruction>(V))
9486 isTailCall = false;
9487 }
9488
9489 // If call site has a cfguardtarget operand bundle, create and add an
9490 // additional ArgListEntry.
9491 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9492 Value *V = Bundle->Inputs[0];
9494 Entry.IsCFGuardTarget = true;
9495 Args.push_back(Entry);
9496 }
9497
9498 // Disable tail calls if there is an swifterror argument. Targets have not
9499 // been updated to support tail calls.
9500 if (TLI.supportSwiftError() && SwiftErrorVal)
9501 isTailCall = false;
9502
9503 ConstantInt *CFIType = nullptr;
9504 if (CB.isIndirectCall()) {
9505 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9506 if (!TLI.supportKCFIBundles())
9508 "Target doesn't support calls with kcfi operand bundles.");
9509 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9510 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9511 }
9512 }
9513
9514 SDValue ConvControlToken;
9515 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9516 auto *Token = Bundle->Inputs[0].get();
9517 ConvControlToken = getValue(Token);
9518 }
9519
9520 GlobalValue *DeactivationSymbol = nullptr;
9522 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9523 }
9524
9527 .setChain(getRoot())
9528 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9529 .setTailCall(isTailCall)
9533 .setCFIType(CFIType)
9534 .setConvergenceControlToken(ConvControlToken)
9535 .setDeactivationSymbol(DeactivationSymbol);
9536
9537 // Set the pointer authentication info if we have it.
9538 if (PAI) {
9539 if (!TLI.supportPtrAuthBundles())
9541 "This target doesn't support calls with ptrauth operand bundles.");
9542 CLI.setPtrAuth(*PAI);
9543 }
9544
9545 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9546
9547 if (Result.first.getNode()) {
9548 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9550 setValue(&CB, Result.first);
9551 }
9552
9553 // The last element of CLI.InVals has the SDValue for swifterror return.
9554 // Here we copy it to a virtual register and update SwiftErrorMap for
9555 // book-keeping.
9556 if (SwiftErrorVal && TLI.supportSwiftError()) {
9557 // Get the last element of InVals.
9558 SDValue Src = CLI.InVals.back();
9559 Register VReg =
9560 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9561 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9562 DAG.setRoot(CopyNode);
9563 }
9564}
9565
9566static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9567 SelectionDAGBuilder &Builder) {
9568 // Check to see if this load can be trivially constant folded, e.g. if the
9569 // input is from a string literal.
9570 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9571 // Cast pointer to the type we really want to load.
9572 Type *LoadTy =
9573 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9574 if (LoadVT.isVector())
9575 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9576 if (const Constant *LoadCst =
9577 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9578 LoadTy, Builder.DAG.getDataLayout()))
9579 return Builder.getValue(LoadCst);
9580 }
9581
9582 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9583 // still constant memory, the input chain can be the entry node.
9584 SDValue Root;
9585 bool ConstantMemory = false;
9586
9587 // Do not serialize (non-volatile) loads of constant memory with anything.
9588 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9589 Root = Builder.DAG.getEntryNode();
9590 ConstantMemory = true;
9591 } else {
9592 // Do not serialize non-volatile loads against each other.
9593 Root = Builder.DAG.getRoot();
9594 }
9595
9596 SDValue Ptr = Builder.getValue(PtrVal);
9597 SDValue LoadVal =
9598 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9599 MachinePointerInfo(PtrVal), Align(1));
9600
9601 if (!ConstantMemory)
9602 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9603 return LoadVal;
9604}
9605
9606/// Record the value for an instruction that produces an integer result,
9607/// converting the type where necessary.
9608void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9609 SDValue Value,
9610 bool IsSigned) {
9611 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9612 I.getType(), true);
9613 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9614 setValue(&I, Value);
9615}
9616
9617/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9618/// true and lower it. Otherwise return false, and it will be lowered like a
9619/// normal call.
9620/// The caller already checked that \p I calls the appropriate LibFunc with a
9621/// correct prototype.
9622bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9623 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9624 const Value *Size = I.getArgOperand(2);
9625 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9626 if (CSize && CSize->getZExtValue() == 0) {
9627 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9628 I.getType(), true);
9629 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9630 return true;
9631 }
9632
9633 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9634 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9635 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9636 getValue(Size), &I);
9637 if (Res.first.getNode()) {
9638 processIntegerCallValue(I, Res.first, true);
9639 PendingLoads.push_back(Res.second);
9640 return true;
9641 }
9642
9643 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9644 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9645 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9646 return false;
9647
9648 // If the target has a fast compare for the given size, it will return a
9649 // preferred load type for that size. Require that the load VT is legal and
9650 // that the target supports unaligned loads of that type. Otherwise, return
9651 // INVALID.
9652 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9654 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9655 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9656 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9657 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9658 // TODO: Check alignment of src and dest ptrs.
9659 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9660 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9661 if (!TLI.isTypeLegal(LVT) ||
9662 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9665 }
9666
9667 return LVT;
9668 };
9669
9670 // This turns into unaligned loads. We only do this if the target natively
9671 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9672 // we'll only produce a small number of byte loads.
9673 MVT LoadVT;
9674 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9675 switch (NumBitsToCompare) {
9676 default:
9677 return false;
9678 case 16:
9679 LoadVT = MVT::i16;
9680 break;
9681 case 32:
9682 LoadVT = MVT::i32;
9683 break;
9684 case 64:
9685 case 128:
9686 case 256:
9687 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9688 break;
9689 }
9690
9691 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9692 return false;
9693
9694 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9695 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9696
9697 // Bitcast to a wide integer type if the loads are vectors.
9698 if (LoadVT.isVector()) {
9699 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9700 LoadL = DAG.getBitcast(CmpVT, LoadL);
9701 LoadR = DAG.getBitcast(CmpVT, LoadR);
9702 }
9703
9704 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9705 processIntegerCallValue(I, Cmp, false);
9706 return true;
9707}
9708
9709/// See if we can lower a memchr call into an optimized form. If so, return
9710/// true and lower it. Otherwise return false, and it will be lowered like a
9711/// normal call.
9712/// The caller already checked that \p I calls the appropriate LibFunc with a
9713/// correct prototype.
9714bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9715 const Value *Src = I.getArgOperand(0);
9716 const Value *Char = I.getArgOperand(1);
9717 const Value *Length = I.getArgOperand(2);
9718
9719 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9720 std::pair<SDValue, SDValue> Res =
9721 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9722 getValue(Src), getValue(Char), getValue(Length),
9723 MachinePointerInfo(Src));
9724 if (Res.first.getNode()) {
9725 setValue(&I, Res.first);
9726 PendingLoads.push_back(Res.second);
9727 return true;
9728 }
9729
9730 return false;
9731}
9732
9733/// See if we can lower a memccpy call into an optimized form. If so, return
9734/// true and lower it, otherwise return false and it will be lowered like a
9735/// normal call.
9736/// The caller already checked that \p I calls the appropriate LibFunc with a
9737/// correct prototype.
9738bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9739 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9740 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9741 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9742 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9743 getValue(I.getArgOperand(3)), &I);
9744
9745 if (Res.first) {
9746 processIntegerCallValue(I, Res.first, true);
9747 PendingLoads.push_back(Res.second);
9748 return true;
9749 }
9750 return false;
9751}
9752
9753/// See if we can lower a mempcpy call into an optimized form. If so, return
9754/// true and lower it. Otherwise return false, and it will be lowered like a
9755/// normal call.
9756/// The caller already checked that \p I calls the appropriate LibFunc with a
9757/// correct prototype.
9758bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9759 SDValue Dst = getValue(I.getArgOperand(0));
9760 SDValue Src = getValue(I.getArgOperand(1));
9761 SDValue Size = getValue(I.getArgOperand(2));
9762
9763 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9764 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9765
9766 SDLoc sdl = getCurSDLoc();
9767
9768 // In the mempcpy context we need to pass in a false value for isTailCall
9769 // because the return pointer needs to be adjusted by the size of
9770 // the copied memory.
9771 SDValue Root = getMemoryRoot();
9772 SDValue MC = DAG.getMemcpy(
9773 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9774 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9775 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9776 assert(MC.getNode() != nullptr &&
9777 "** memcpy should not be lowered as TailCall in mempcpy context **");
9778 DAG.setRoot(MC);
9779
9780 // Check if Size needs to be truncated or extended.
9781 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9782
9783 // Adjust return pointer to point just past the last dst byte.
9784 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9785 setValue(&I, DstPlusSize);
9786 return true;
9787}
9788
9789/// See if we can lower a strcpy call into an optimized form. If so, return
9790/// true and lower it, otherwise return false and it will be lowered like a
9791/// normal call.
9792/// The caller already checked that \p I calls the appropriate LibFunc with a
9793/// correct prototype.
9794bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9795 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9796
9797 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9798 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9799 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9800 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9801 if (Res.first.getNode()) {
9802 setValue(&I, Res.first);
9803 DAG.setRoot(Res.second);
9804 return true;
9805 }
9806
9807 return false;
9808}
9809
9810/// See if we can lower a strcmp call into an optimized form. If so, return
9811/// true and lower it, otherwise return false and it will be lowered like a
9812/// normal call.
9813/// The caller already checked that \p I calls the appropriate LibFunc with a
9814/// correct prototype.
9815bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9816 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9817
9818 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9819 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9820 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9821 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9822 if (Res.first.getNode()) {
9823 processIntegerCallValue(I, Res.first, true);
9824 PendingLoads.push_back(Res.second);
9825 return true;
9826 }
9827
9828 return false;
9829}
9830
9831/// See if we can lower a strlen call into an optimized form. If so, return
9832/// true and lower it, otherwise return false and it will be lowered like a
9833/// normal call.
9834/// The caller already checked that \p I calls the appropriate LibFunc with a
9835/// correct prototype.
9836bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9837 const Value *Arg0 = I.getArgOperand(0);
9838
9839 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9840 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9841 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9842 if (Res.first.getNode()) {
9843 processIntegerCallValue(I, Res.first, false);
9844 PendingLoads.push_back(Res.second);
9845 return true;
9846 }
9847
9848 return false;
9849}
9850
9851/// See if we can lower a strnlen call into an optimized form. If so, return
9852/// true and lower it, otherwise return false and it will be lowered like a
9853/// normal call.
9854/// The caller already checked that \p I calls the appropriate LibFunc with a
9855/// correct prototype.
9856bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9857 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9858
9859 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9860 std::pair<SDValue, SDValue> Res =
9861 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9862 getValue(Arg0), getValue(Arg1),
9863 MachinePointerInfo(Arg0));
9864 if (Res.first.getNode()) {
9865 processIntegerCallValue(I, Res.first, false);
9866 PendingLoads.push_back(Res.second);
9867 return true;
9868 }
9869
9870 return false;
9871}
9872
9873/// See if we can lower a Strstr call into an optimized form. If so, return
9874/// true and lower it, otherwise return false and it will be lowered like a
9875/// normal call.
9876/// The caller already checked that \p I calls the appropriate LibFunc with a
9877/// correct prototype.
9878bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9879 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9880 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9881 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9882 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9883 if (Res.first) {
9884 processIntegerCallValue(I, Res.first, false);
9885 PendingLoads.push_back(Res.second);
9886 return true;
9887 }
9888 return false;
9889}
9890
9891/// See if we can lower a unary floating-point operation into an SDNode with
9892/// the specified Opcode. If so, return true and lower it, otherwise return
9893/// false and it will be lowered like a normal call.
9894/// The caller already checked that \p I calls the appropriate LibFunc with a
9895/// correct prototype.
9896bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9897 unsigned Opcode) {
9898 // We already checked this call's prototype; verify it doesn't modify errno.
9899 // Do not perform optimizations for call sites that require strict
9900 // floating-point semantics.
9901 if (!I.onlyReadsMemory() || I.isStrictFP())
9902 return false;
9903
9904 SDNodeFlags Flags;
9905 Flags.copyFMF(cast<FPMathOperator>(I));
9906
9907 SDValue Tmp = getValue(I.getArgOperand(0));
9908 setValue(&I,
9909 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9910 return true;
9911}
9912
9913/// See if we can lower a binary floating-point operation into an SDNode with
9914/// the specified Opcode. If so, return true and lower it. Otherwise return
9915/// false, and it will be lowered like a normal call.
9916/// The caller already checked that \p I calls the appropriate LibFunc with a
9917/// correct prototype.
9918bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9919 unsigned Opcode) {
9920 // We already checked this call's prototype; verify it doesn't modify errno.
9921 // Do not perform optimizations for call sites that require strict
9922 // floating-point semantics.
9923 if (!I.onlyReadsMemory() || I.isStrictFP())
9924 return false;
9925
9926 SDNodeFlags Flags;
9927 Flags.copyFMF(cast<FPMathOperator>(I));
9928
9929 SDValue Tmp0 = getValue(I.getArgOperand(0));
9930 SDValue Tmp1 = getValue(I.getArgOperand(1));
9931 EVT VT = Tmp0.getValueType();
9932 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9933 return true;
9934}
9935
9936void SelectionDAGBuilder::visitCall(const CallInst &I) {
9937 // Handle inline assembly differently.
9938 if (I.isInlineAsm()) {
9939 visitInlineAsm(I);
9940 return;
9941 }
9942
9944
9945 if (Function *F = I.getCalledFunction()) {
9946 if (F->isDeclaration()) {
9947 // Is this an LLVM intrinsic?
9948 if (unsigned IID = F->getIntrinsicID()) {
9949 visitIntrinsicCall(I, IID);
9950 return;
9951 }
9952 }
9953
9954 // Check for well-known libc/libm calls. If the function is internal, it
9955 // can't be a library call. Don't do the check if marked as nobuiltin for
9956 // some reason.
9957 // This code should not handle libcalls that are already canonicalized to
9958 // intrinsics by the middle-end.
9959 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9960 ? LibInfo->getLibFunc(*F)
9961 : NotLibFunc;
9962 if (LibInfo->hasOptimizedCodeGen(Func)) {
9963 switch (Func) {
9964 default: break;
9965 case LibFunc_bcmp:
9966 if (visitMemCmpBCmpCall(I))
9967 return;
9968 break;
9969 case LibFunc_sin:
9970 case LibFunc_sinf:
9971 case LibFunc_sinl:
9972 if (visitUnaryFloatCall(I, ISD::FSIN))
9973 return;
9974 break;
9975 case LibFunc_cos:
9976 case LibFunc_cosf:
9977 case LibFunc_cosl:
9978 if (visitUnaryFloatCall(I, ISD::FCOS))
9979 return;
9980 break;
9981 case LibFunc_tan:
9982 case LibFunc_tanf:
9983 case LibFunc_tanl:
9984 if (visitUnaryFloatCall(I, ISD::FTAN))
9985 return;
9986 break;
9987 case LibFunc_asin:
9988 case LibFunc_asinf:
9989 case LibFunc_asinl:
9990 if (visitUnaryFloatCall(I, ISD::FASIN))
9991 return;
9992 break;
9993 case LibFunc_acos:
9994 case LibFunc_acosf:
9995 case LibFunc_acosl:
9996 if (visitUnaryFloatCall(I, ISD::FACOS))
9997 return;
9998 break;
9999 case LibFunc_atan:
10000 case LibFunc_atanf:
10001 case LibFunc_atanl:
10002 if (visitUnaryFloatCall(I, ISD::FATAN))
10003 return;
10004 break;
10005 case LibFunc_atan2:
10006 case LibFunc_atan2f:
10007 case LibFunc_atan2l:
10008 if (visitBinaryFloatCall(I, ISD::FATAN2))
10009 return;
10010 break;
10011 case LibFunc_sinh:
10012 case LibFunc_sinhf:
10013 case LibFunc_sinhl:
10014 if (visitUnaryFloatCall(I, ISD::FSINH))
10015 return;
10016 break;
10017 case LibFunc_cosh:
10018 case LibFunc_coshf:
10019 case LibFunc_coshl:
10020 if (visitUnaryFloatCall(I, ISD::FCOSH))
10021 return;
10022 break;
10023 case LibFunc_tanh:
10024 case LibFunc_tanhf:
10025 case LibFunc_tanhl:
10026 if (visitUnaryFloatCall(I, ISD::FTANH))
10027 return;
10028 break;
10029 case LibFunc_sqrt:
10030 case LibFunc_sqrtf:
10031 case LibFunc_sqrtl:
10032 case LibFunc_sqrt_finite:
10033 case LibFunc_sqrtf_finite:
10034 case LibFunc_sqrtl_finite:
10035 if (visitUnaryFloatCall(I, ISD::FSQRT))
10036 return;
10037 break;
10038 case LibFunc_log2:
10039 case LibFunc_log2f:
10040 case LibFunc_log2l:
10041 if (visitUnaryFloatCall(I, ISD::FLOG2))
10042 return;
10043 break;
10044 case LibFunc_exp2:
10045 case LibFunc_exp2f:
10046 case LibFunc_exp2l:
10047 if (visitUnaryFloatCall(I, ISD::FEXP2))
10048 return;
10049 break;
10050 case LibFunc_exp10:
10051 case LibFunc_exp10f:
10052 case LibFunc_exp10l:
10053 if (visitUnaryFloatCall(I, ISD::FEXP10))
10054 return;
10055 break;
10056 case LibFunc_strstr:
10057 if (visitStrstrCall(I))
10058 return;
10059 break;
10060 case LibFunc_memcmp:
10061 if (visitMemCmpBCmpCall(I))
10062 return;
10063 break;
10064 case LibFunc_memccpy:
10065 if (visitMemCCpyCall(I))
10066 return;
10067 break;
10068 case LibFunc_mempcpy:
10069 if (visitMemPCpyCall(I))
10070 return;
10071 break;
10072 case LibFunc_memchr:
10073 if (visitMemChrCall(I))
10074 return;
10075 break;
10076 case LibFunc_strcpy:
10077 if (visitStrCpyCall(I, false))
10078 return;
10079 break;
10080 case LibFunc_stpcpy:
10081 if (visitStrCpyCall(I, true))
10082 return;
10083 break;
10084 case LibFunc_strcmp:
10085 if (visitStrCmpCall(I))
10086 return;
10087 break;
10088 case LibFunc_strlen:
10089 if (visitStrLenCall(I))
10090 return;
10091 break;
10092 case LibFunc_strnlen:
10093 if (visitStrNLenCall(I))
10094 return;
10095 break;
10096 }
10097 }
10098 }
10099
10100 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
10101 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
10102 return;
10103 }
10104
10105 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
10106 // have to do anything here to lower funclet bundles.
10107 // CFGuardTarget bundles are lowered in LowerCallTo.
10109 I, "calls",
10114
10115 SDValue Callee = getValue(I.getCalledOperand());
10116
10117 if (I.hasDeoptState())
10118 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
10119 else
10120 // Check if we can potentially perform a tail call. More detailed checking
10121 // is be done within LowerCallTo, after more information about the call is
10122 // known.
10123 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
10124}
10125
10127 const CallBase &CB, const BasicBlock *EHPadBB) {
10128 auto PAB = CB.getOperandBundle("ptrauth");
10129 const Value *CalleeV = CB.getCalledOperand();
10130
10131 // Gather the call ptrauth data from the operand bundle:
10132 // [ i32 <key>, i64 <discriminator> ]
10133 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
10134 const Value *Discriminator = PAB->Inputs[1];
10135
10136 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
10137 assert(Discriminator->getType()->isIntegerTy(64) &&
10138 "Invalid ptrauth discriminator");
10139
10140 // Look through ptrauth constants to find the raw callee.
10141 // Do a direct unauthenticated call if we found it and everything matches.
10142 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
10143 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
10144 DAG.getDataLayout()))
10145 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
10146 CB.isMustTailCall(), EHPadBB);
10147
10148 // Functions should never be ptrauth-called directly.
10149 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
10150
10151 // Otherwise, do an authenticated indirect call.
10152 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
10153 getValue(Discriminator)};
10154
10155 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
10156 EHPadBB, &PAI);
10157}
10158
10159namespace {
10160
10161/// AsmOperandInfo - This contains information for each constraint that we are
10162/// lowering.
10163class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
10164public:
10165 /// CallOperand - If this is the result output operand or a clobber
10166 /// this is null, otherwise it is the incoming operand to the CallInst.
10167 /// This gets modified as the asm is processed.
10168 SDValue CallOperand;
10169
10170 /// AssignedRegs - If this is a register or register class operand, this
10171 /// contains the set of register corresponding to the operand.
10172 RegsForValue AssignedRegs;
10173
10174 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
10175 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
10176 }
10177
10178 /// Whether or not this operand accesses memory
10179 bool hasMemory(const TargetLowering &TLI) const {
10180 // Indirect operand accesses access memory.
10181 if (isIndirect)
10182 return true;
10183
10184 for (const auto &Code : Codes)
10185 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
10186 return true;
10187
10188 return false;
10189 }
10190};
10191
10192
10193} // end anonymous namespace
10194
10195/// Make sure that the output operand \p OpInfo and its corresponding input
10196/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10197/// out).
10198static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10199 SDISelAsmOperandInfo &MatchingOpInfo,
10200 SelectionDAG &DAG) {
10201 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10202 return;
10203
10205 const auto &TLI = DAG.getTargetLoweringInfo();
10206
10207 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10208 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
10209 OpInfo.ConstraintVT);
10210 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10211 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
10212 MatchingOpInfo.ConstraintVT);
10213 const bool OutOpIsIntOrFP =
10214 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10215 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10216 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10217 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10218 // FIXME: error out in a more elegant fashion
10219 report_fatal_error("Unsupported asm: input constraint"
10220 " with a matching output constraint of"
10221 " incompatible type!");
10222 }
10223 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10224}
10225
10226/// Get a direct memory input to behave well as an indirect operand.
10227/// This may introduce stores, hence the need for a \p Chain.
10228/// \return The (possibly updated) chain.
10229static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10230 SDISelAsmOperandInfo &OpInfo,
10231 SelectionDAG &DAG) {
10233
10234 // If we don't have an indirect input, put it in the constpool if we can,
10235 // otherwise spill it to a stack slot.
10236 // TODO: This isn't quite right. We need to handle these according to
10237 // the addressing mode that the constraint wants. Also, this may take
10238 // an additional register for the computation and we don't want that
10239 // either.
10240
10241 // If the operand is a float, integer, or vector constant, spill to a
10242 // constant pool entry to get its address.
10243 const Value *OpVal = OpInfo.CallOperandVal;
10244 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10246 OpInfo.CallOperand = DAG.getConstantPool(
10247 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10248 return Chain;
10249 }
10250
10251 // Otherwise, create a stack slot and emit a store to it before the asm.
10252 Type *Ty = OpVal->getType();
10253 auto &DL = DAG.getDataLayout();
10254 TypeSize TySize = DL.getTypeAllocSize(Ty);
10257 int StackID = 0;
10258 if (TySize.isScalable())
10259 StackID = TFI->getStackIDForScalableVectors();
10260 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10261 DL.getPrefTypeAlign(Ty), false,
10262 nullptr, StackID);
10263 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10264 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10266 TLI.getMemValueType(DL, Ty));
10267 OpInfo.CallOperand = StackSlot;
10268
10269 return Chain;
10270}
10271
10272/// GetRegistersForValue - Assign registers (virtual or physical) for the
10273/// specified operand. We prefer to assign virtual registers, to allow the
10274/// register allocator to handle the assignment process. However, if the asm
10275/// uses features that we can't model on machineinstrs, we have SDISel do the
10276/// allocation. This produces generally horrible, but correct, code.
10277///
10278/// OpInfo describes the operand
10279/// RefOpInfo describes the matching operand if any, the operand otherwise
10280static std::optional<unsigned>
10282 SDISelAsmOperandInfo &OpInfo,
10283 SDISelAsmOperandInfo &RefOpInfo) {
10284 LLVMContext &Context = *DAG.getContext();
10286
10290
10291 // No work to do for memory/address operands.
10292 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10293 OpInfo.ConstraintType == TargetLowering::C_Address)
10294 return std::nullopt;
10295
10296 // If this is a constraint for a single physreg, or a constraint for a
10297 // register class, find it.
10298 unsigned AssignedReg;
10299 const TargetRegisterClass *RC;
10300 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10301 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10302 // RC is unset only on failure. Return immediately.
10303 if (!RC)
10304 return std::nullopt;
10305
10306 // Get the actual register value type. This is important, because the user
10307 // may have asked for (e.g.) the AX register in i32 type. We need to
10308 // remember that AX is actually i16 to get the right extension.
10309 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10310
10311 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10312 // If this is an FP operand in an integer register (or visa versa), or more
10313 // generally if the operand value disagrees with the register class we plan
10314 // to stick it in, fix the operand type.
10315 //
10316 // If this is an input value, the bitcast to the new type is done now.
10317 // Bitcast for output value is done at the end of visitInlineAsm().
10318 if ((OpInfo.Type == InlineAsm::isOutput ||
10319 OpInfo.Type == InlineAsm::isInput) &&
10320 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10321 // Try to convert to the first EVT that the reg class contains. If the
10322 // types are identical size, use a bitcast to convert (e.g. two differing
10323 // vector types). Note: output bitcast is done at the end of
10324 // visitInlineAsm().
10325 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10326 // Exclude indirect inputs while they are unsupported because the code
10327 // to perform the load is missing and thus OpInfo.CallOperand still
10328 // refers to the input address rather than the pointed-to value.
10329 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10330 OpInfo.CallOperand =
10331 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10332 OpInfo.ConstraintVT = RegVT;
10333 // If the operand is an FP value and we want it in integer registers,
10334 // use the corresponding integer type. This turns an f64 value into
10335 // i64, which can be passed with two i32 values on a 32-bit machine.
10336 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10337 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10338 // No integer type of that size to bitcast to (e.g. f80).
10339 if (!VT.isValid())
10340 return std::nullopt;
10341 if (OpInfo.Type == InlineAsm::isInput)
10342 OpInfo.CallOperand =
10343 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10344 OpInfo.ConstraintVT = VT;
10345 }
10346 }
10347 }
10348
10349 // No need to allocate a matching input constraint since the constraint it's
10350 // matching to has already been allocated.
10351 if (OpInfo.isMatchingInputConstraint())
10352 return std::nullopt;
10353
10354 EVT ValueVT = OpInfo.ConstraintVT;
10355 if (OpInfo.ConstraintVT == MVT::Other)
10356 ValueVT = RegVT;
10357
10358 // Initialize NumRegs.
10359 unsigned NumRegs = 1;
10360 if (OpInfo.ConstraintVT != MVT::Other)
10361 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10362
10363 // If this is a constraint for a specific physical register, like {r17},
10364 // assign it now.
10365
10366 // If this associated to a specific register, initialize iterator to correct
10367 // place. If virtual, make sure we have enough registers
10368
10369 // Initialize iterator if necessary
10372
10373 // Do not check for single registers.
10374 if (AssignedReg) {
10375 I = std::find(I, RC->end(), AssignedReg);
10376 if (I == RC->end()) {
10377 // RC does not contain the selected register, which indicates a
10378 // mismatch between the register and the required type/bitwidth.
10379 return {AssignedReg};
10380 }
10381 }
10382
10383 for (; NumRegs; --NumRegs, ++I) {
10384 assert(I != RC->end() && "Ran out of registers to allocate!");
10385 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10386 Regs.push_back(R);
10387 }
10388
10389 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10390 return std::nullopt;
10391}
10392
10393static unsigned
10395 const std::vector<SDValue> &AsmNodeOperands) {
10396 // Scan until we find the definition we already emitted of this operand.
10397 unsigned CurOp = InlineAsm::Op_FirstOperand;
10398 for (; OperandNo; --OperandNo) {
10399 // Advance to the next operand.
10400 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10401 const InlineAsm::Flag F(OpFlag);
10402 assert(
10403 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10404 "Skipped past definitions?");
10405 CurOp += F.getNumOperandRegisters() + 1;
10406 }
10407 return CurOp;
10408}
10409
10410namespace {
10411
10412class ExtraFlags {
10413 unsigned Flags = 0;
10414
10415public:
10416 explicit ExtraFlags(const CallBase &Call) {
10417 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10418 if (IA->hasSideEffects())
10420 if (IA->isAlignStack())
10422 if (IA->canThrow())
10424 if (Call.isConvergent())
10426 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10427 }
10428
10429 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10430 // Ideally, we would only check against memory constraints. However, the
10431 // meaning of an Other constraint can be target-specific and we can't easily
10432 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10433 // for Other constraints as well.
10436 if (OpInfo.Type == InlineAsm::isInput)
10438 else if (OpInfo.Type == InlineAsm::isOutput)
10440 else if (OpInfo.Type == InlineAsm::isClobber)
10442 }
10443 }
10444
10445 unsigned get() const { return Flags; }
10446};
10447
10448} // end anonymous namespace
10449
10450static bool isFunction(SDValue Op) {
10451 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10452 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10453 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10454
10455 // In normal "call dllimport func" instruction (non-inlineasm) it force
10456 // indirect access by specifing call opcode. And usually specially print
10457 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10458 // not do in this way now. (In fact, this is similar with "Data Access"
10459 // action). So here we ignore dllimport function.
10460 if (Fn && !Fn->hasDLLImportStorageClass())
10461 return true;
10462 }
10463 }
10464 return false;
10465}
10466
10467namespace {
10468
10469struct ConstraintDecisionInfo {
10470 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10471 std::vector<SDValue> AsmNodeOperands;
10472 SDValue Glue, Chain;
10473 bool HasSideEffect = false;
10474 MCSymbol *BeginLabel = nullptr;
10475
10476 SmallVector<char> Buffer;
10477 raw_svector_ostream ErrorMsg;
10478
10479 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10480};
10481
10482} // end anonymous namespace
10483
10484/// Construct operand info objects.
10485static bool
10486constructOperandInfo(ConstraintDecisionInfo &Info,
10487 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10488 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10489 ExtraFlags &ExtraInfo) {
10490 for (auto &T : TargetConstraints) {
10491 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10492 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10493
10494 if (OpInfo.CallOperandVal)
10495 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10496
10497 if (!Info.HasSideEffect)
10498 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10499
10500 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10501 // FIXME: Could we compute this on OpInfo rather than T?
10502
10503 // Compute the constraint code and ConstraintType to use.
10504 TLI.ComputeConstraintToUse(T, SDValue());
10505
10506 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10507 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10508 // We've delayed emitting a diagnostic like the "n" constraint because
10509 // inlining could cause an integer showing up.
10510 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10511 << "' expects an integer constant expression";
10512 return true;
10513 }
10514
10515 ExtraInfo.update(T);
10516 }
10517
10518 return false;
10519}
10520
10521/// Compute which constraint option to use for each operand.
10522static void
10523computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10524 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10525 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10526 const TargetMachine &TM, SelectionDAG &DAG) {
10527 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10529 IA->collectAsmStrs(AsmStrs);
10530
10531 int OpNo = -1;
10532 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10533 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10534 OpNo++;
10535
10536 // If this is an output operand with a matching input operand, look up the
10537 // matching input. If their types mismatch, e.g. one is an integer, the
10538 // other is floating point, or their sizes are different, flag it as an
10539 // error.
10540 if (OpInfo.hasMatchingInput()) {
10541 SDISelAsmOperandInfo &Input =
10542 Info.ConstraintOperands[OpInfo.MatchingInput];
10543 patchMatchingInput(OpInfo, Input, DAG);
10544 }
10545
10546 // Compute the constraint code and ConstraintType to use.
10547 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10548
10549 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10550 OpInfo.Type == InlineAsm::isClobber) ||
10551 OpInfo.ConstraintType == TargetLowering::C_Address)
10552 continue;
10553
10554 // In Linux PIC model, there are 4 cases about value/label addressing:
10555 //
10556 // 1: Function call or Label jmp inside the module.
10557 // 2: Data access (such as global variable, static variable) inside module.
10558 // 3: Function call or Label jmp outside the module.
10559 // 4: Data access (such as global variable) outside the module.
10560 //
10561 // Due to current llvm inline asm architecture designed to not "recognize"
10562 // the asm code, there are quite troubles for us to treat mem addressing
10563 // differently for same value/adress used in different instructions.
10564 // For example, in pic model, call a func may in plt way or direclty
10565 // pc-related, but lea/mov a function adress may use got.
10566 //
10567 // Here we try to "recognize" function call for the case 1 and case 3 in
10568 // inline asm. And try to adjust the constraint for them.
10569 //
10570 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10571 // label, so here we don't handle jmp function label now, but we need to
10572 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10573 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10574 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10576 OpInfo.isIndirect = false;
10577 OpInfo.ConstraintType = TargetLowering::C_Address;
10578 }
10579
10580 // If this is a memory input, and if the operand is not indirect, do what we
10581 // need to provide an address for the memory input.
10582 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10583 !OpInfo.isIndirect) {
10584 assert((OpInfo.isMultipleAlternative ||
10585 (OpInfo.Type == InlineAsm::isInput)) &&
10586 "Can only indirectify direct input operands!");
10587
10588 // Memory operands really want the address of the value.
10589 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10590 OpInfo, DAG);
10591
10592 // There is no longer a Value* corresponding to this operand.
10593 OpInfo.CallOperandVal = nullptr;
10594
10595 // It is now an indirect operand.
10596 OpInfo.isIndirect = true;
10597 }
10598 }
10599}
10600
10601/// Prepare DAG-level operands. As part of this, assign virtual and physical
10602/// registers for inputs and output.
10603static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10604 const CallBase &Call,
10605 SelectionDAGBuilder &Builder,
10606 const TargetLowering &TLI,
10607 SelectionDAG &DAG) {
10608 SDLoc DL = Builder.getCurSDLoc();
10609 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10610 // Assign Registers.
10611 SDISelAsmOperandInfo &RefOpInfo =
10612 OpInfo.isMatchingInputConstraint()
10613 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10614 : OpInfo;
10615 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10616 if (RegError) {
10617 const MachineFunction &MF = DAG.getMachineFunction();
10619 const char *RegName = TRI.getName(*RegError);
10620 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10621 << OpInfo.ConstraintCode
10622 << "' does not match required type";
10623 return true;
10624 }
10625
10626 auto DetectWriteToReservedRegister = [&]() {
10627 const MachineFunction &MF = DAG.getMachineFunction();
10629
10630 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10631 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10632 Info.ErrorMsg << "write to reserved register '"
10633 << TRI.getRegAsmName(Reg) << "'";
10634 return true;
10635 }
10636 }
10637
10638 return false;
10639 };
10640 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10641 (OpInfo.Type == InlineAsm::isInput &&
10642 !OpInfo.isMatchingInputConstraint())) &&
10643 "Only address as input operand is allowed.");
10644
10645 switch (OpInfo.Type) {
10647 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10648 const InlineAsm::ConstraintCode ConstraintID =
10649 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10651 "Failed to convert memory constraint code to constraint id.");
10652
10653 // Add information to the INLINEASM node to know about this output.
10655 OpFlags.setMemConstraint(ConstraintID);
10656 Info.AsmNodeOperands.push_back(
10657 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10658 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10659 } else {
10660 // Otherwise, this outputs to a register (directly for C_Register /
10661 // C_RegisterClass, and a target-defined fashion for
10662 // C_Immediate/C_Other). Find a register that we can use.
10663 if (OpInfo.AssignedRegs.Regs.empty()) {
10664 Info.ErrorMsg << "could not allocate output register for "
10665 << "constraint '" << OpInfo.ConstraintCode << "'";
10666 return true;
10667 }
10668
10669 if (DetectWriteToReservedRegister())
10670 return true;
10671
10672 // Add information to the INLINEASM node to know that this register is
10673 // set.
10674 OpInfo.AssignedRegs.AddInlineAsmOperands(
10675 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10677 false, 0, DL, DAG, Info.AsmNodeOperands);
10678 }
10679 break;
10680
10681 case InlineAsm::isInput:
10682 case InlineAsm::isLabel: {
10683 SDValue InOperandVal = OpInfo.CallOperand;
10684
10685 if (OpInfo.isMatchingInputConstraint()) {
10686 // If this is required to match an output register we have already set,
10687 // just use its register.
10688 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10689 Info.AsmNodeOperands);
10690 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10691 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10692 if (OpInfo.isIndirect) {
10693 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10694 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10695 << "tied indirect register inputs";
10696 return true;
10697 }
10698
10703 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10704 Register TiedReg = R->getReg();
10705 MVT RegVT = R->getSimpleValueType(0);
10706 const TargetRegisterClass *RC;
10707 if (TiedReg.isVirtual()) {
10708 RC = MRI.getRegClass(TiedReg);
10709 } else if (RegVT == MVT::Untyped) {
10710 RC = TRI.getMinimalPhysRegClass(TiedReg);
10711 } else {
10712 RC = TLI.getRegClassFor(RegVT);
10713 if (!RC->contains(TiedReg)) {
10714 const TargetRegisterClass *PhysRC =
10715 TRI.getMinimalPhysRegClass(TiedReg);
10716 if (PhysRC->isAllocatable())
10717 RC = PhysRC;
10718 }
10719 }
10720
10721 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10722 Regs.push_back(MRI.createVirtualRegister(RC));
10723
10724 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10725
10726 // Use the produced MatchedRegs object to
10727 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10728 &Info.Glue, &Call);
10730 OpInfo.getMatchedOperand(), DL, DAG,
10731 Info.AsmNodeOperands);
10732 break;
10733 }
10734
10735 assert(Flag.isMemKind() && "Unknown matching constraint!");
10736 assert(Flag.getNumOperandRegisters() == 1 &&
10737 "Unexpected number of operands");
10738
10739 // Add information to the INLINEASM node to know about this input.
10740 // See InlineAsm.h isUseOperandTiedToDef.
10741 Flag.clearMemConstraint();
10742 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10743 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10744 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10745 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10746 break;
10747 }
10748
10749 // Treat indirect 'X' constraint as memory.
10750 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10751 OpInfo.isIndirect)
10752 OpInfo.ConstraintType = TargetLowering::C_Memory;
10753
10754 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10755 OpInfo.ConstraintType == TargetLowering::C_Other) {
10756 std::vector<SDValue> Ops;
10757 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10758 Ops, DAG);
10759 if (Ops.empty()) {
10760 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10761 if (isa<ConstantSDNode>(InOperandVal)) {
10762 Info.ErrorMsg << "value out of range for constraint '"
10763 << OpInfo.ConstraintCode << "'";
10764 return true;
10765 }
10766
10767 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10768 << OpInfo.ConstraintCode << "'";
10769 return true;
10770 }
10771
10772 // Add information to the INLINEASM node to know about this input.
10773 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10774 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10775 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10776 llvm::append_range(Info.AsmNodeOperands, Ops);
10777 break;
10778 }
10779
10780 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10781 assert((OpInfo.isIndirect ||
10782 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10783 "Operand must be indirect to be a mem!");
10784
10785 assert(InOperandVal.getValueType() ==
10786 TLI.getPointerTy(
10787 DAG.getDataLayout(),
10788 OpInfo.CallOperandVal
10789 ? cast<PointerType>(OpInfo.CallOperandVal->getType())
10790 ->getAddressSpace()
10791 : 0) &&
10792 "Memory operands expect pointer values");
10793
10794 const InlineAsm::ConstraintCode ConstraintID =
10795 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10797 "Failed to convert memory constraint code to constraint id.");
10798
10799 // Add information to the INLINEASM node to know about this input.
10801 ResOpType.setMemConstraint(ConstraintID);
10802 Info.AsmNodeOperands.push_back(
10803 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10804 Info.AsmNodeOperands.push_back(InOperandVal);
10805 break;
10806 }
10807
10808 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10809 const InlineAsm::ConstraintCode ConstraintID =
10810 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10812 "Failed to convert memory constraint code to constraint id.");
10813
10815
10816 SDValue AsmOp = InOperandVal;
10817 if (TLI.supportsInlineAsmFuncOperands() && isFunction(InOperandVal)) {
10818 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10819 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10820 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10821 InOperandVal.getValueType(),
10822 GA->getOffset());
10823 }
10824
10825 // Add information to the INLINEASM node to know about this input.
10826 ResOpType.setMemConstraint(ConstraintID);
10827
10828 Info.AsmNodeOperands.push_back(
10829 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10830 Info.AsmNodeOperands.push_back(AsmOp);
10831 break;
10832 }
10833
10834 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10835 OpInfo.ConstraintType != TargetLowering::C_Register) {
10836 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10837 << "'";
10838 return true;
10839 }
10840
10841 // TODO: Support this.
10842 if (OpInfo.isIndirect) {
10843 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10844 << "constraint '" << OpInfo.ConstraintCode << "'";
10845 return true;
10846 }
10847
10848 // Copy the input into the appropriate registers.
10849 if (OpInfo.AssignedRegs.Regs.empty()) {
10850 Info.ErrorMsg << "could not allocate input reg for constraint '"
10851 << OpInfo.ConstraintCode << "'";
10852 return true;
10853 }
10854
10855 if (DetectWriteToReservedRegister())
10856 return true;
10857
10858 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10859 &Info.Glue, &Call);
10860 OpInfo.AssignedRegs.AddInlineAsmOperands(
10861 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10862 break;
10863 }
10864
10866 // Add the clobbered value to the operand list, so that the register
10867 // allocator is aware that the physreg got clobbered.
10868 if (!OpInfo.AssignedRegs.Regs.empty())
10869 OpInfo.AssignedRegs.AddInlineAsmOperands(
10870 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10871 break;
10872 }
10873 }
10874
10875 return false;
10876}
10877
10878/// DetermineConstraints - Find the constraints to use for inline asm operands.
10879static bool
10880determineConstraints(ConstraintDecisionInfo &Info,
10881 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10882 const CallBase &Call, SelectionDAGBuilder &Builder,
10883 const TargetLowering &TLI, const TargetMachine &TM,
10884 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10885 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10886 ExtraFlags ExtraInfo(Call);
10887
10888 // First pass: Construct operand info objects.
10889 Info.HasSideEffect = IA->hasSideEffects();
10890 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10891 return true;
10892
10893 // We won't need to flush pending loads if this asm doesn't touch
10894 // memory and is nonvolatile.
10895 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10896
10897 bool IsCallBr = isa<CallBrInst>(Call);
10898 bool EmitEHLabels = isa<InvokeInst>(Call);
10899 if (IsCallBr || EmitEHLabels)
10900 // If this is a callbr or invoke we need to flush pending exports since
10901 // inlineasm_br and invoke are terminators.
10902 // We need to do this before nodes are glued to the inlineasm_br node.
10903 Info.Chain = Builder.getControlRoot();
10904
10905 if (EmitEHLabels)
10906 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10907
10908 // Second pass: Compute which constraint option to use.
10909 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10910
10911 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10912 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10913 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10914 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10915
10916 // If we have a !srcloc metadata node associated with it, we want to attach
10917 // this to the ultimately generated inline asm machineinstr. To do this, we
10918 // pass in the third operand as this (potentially null) inline asm MDNode.
10919 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10920 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10921
10922 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10923 // bits as operand 3.
10924 Info.AsmNodeOperands.push_back(
10925 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10926 TLI.getPointerTy(DAG.getDataLayout())));
10927
10928 // Third pass: Prepare DAG-level operands
10929 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10930}
10931
10932/// Return the result of inline asm call \p Call from \p Outputs, the values of
10933/// its direct outputs in order, each converted to the type of its result.
10935 ArrayRef<SDValue> Outputs, const SDLoc &DL,
10936 SelectionDAG &DAG) {
10938 llvm::Type *CallResultType = Call.getType();
10939 ArrayRef<Type *> ResultTypes;
10940 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10941 ResultTypes = StructResult->elements();
10942 else if (!CallResultType->isVoidTy())
10943 ResultTypes = ArrayRef(CallResultType);
10944
10945 SmallVector<EVT, 1> ResultVTs;
10946 SmallVector<SDValue, 1> ResultValues;
10947 auto CurResultType = ResultTypes.begin();
10948 auto handleRegAssign = [&](SDValue V) {
10949 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10950 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10951 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10952 ++CurResultType;
10953 // If the type of the inline asm call site return value is different but has
10954 // same size as the type of the asm output bitcast it. One example of this
10955 // is for vectors with different width / number of elements. This can
10956 // happen for register classes that can contain multiple different value
10957 // types. The preg or vreg allocated may not have the same VT as was
10958 // expected.
10959 //
10960 // This can also happen for a return value that disagrees with the register
10961 // class it is put in, eg. a double in a general-purpose register on a
10962 // 32-bit machine.
10963 if (ResultVT != V.getValueType() &&
10964 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10965 V = DAG.getNode(ISD::BITCAST, DL, ResultVT, V);
10966 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10967 V.getValueType().isInteger()) {
10968 // If a result value was tied to an input value, the computed result
10969 // may have a wider width than the expected result. Extract the
10970 // relevant portion.
10971 V = DAG.getNode(ISD::TRUNCATE, DL, ResultVT, V);
10972 }
10973 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10974 ResultVTs.push_back(ResultVT);
10975 ResultValues.push_back(V);
10976 };
10977
10978 for (SDValue Val : Outputs) {
10979 if (Val.getOpcode() == ISD::MERGE_VALUES) {
10980 for (const SDValue &V : Val->op_values())
10981 handleRegAssign(V);
10982 } else
10983 handleRegAssign(Val);
10984 }
10985
10986 assert(CurResultType == ResultTypes.end() &&
10987 "Mismatch in number of ResultTypes");
10988 assert(ResultValues.size() == ResultTypes.size() &&
10989 "Mismatch in number of output operands in asm result");
10990 return DAG.getNode(ISD::MERGE_VALUES, DL, DAG.getVTList(ResultVTs),
10991 ResultValues);
10992}
10993
10994/// Read output operand \p OpInfo of inline asm call \p Call from \p Regs, the
10995/// registers that the asm defines it in. If \p Glue is set, the reads are glued
10996/// to it.
10998 const RegsForValue &Regs,
10999 const CallBase &Call, SDValue &Chain,
11000 SDValue &Glue, const SDLoc &DL,
11001 FunctionLoweringInfo &FuncInfo,
11002 SelectionDAG &DAG) {
11003 switch (OpInfo.ConstraintType) {
11006 return Regs.getCopyFromRegs(DAG, FuncInfo, DL, Chain,
11007 Glue.getNode() ? &Glue : nullptr, &Call);
11011 Chain, Glue, DL, OpInfo, DAG);
11013 break; // Already handled.
11015 break; // Silence warning.
11017 llvm_unreachable("Unexpected unknown constraint");
11018 }
11019 return SDValue();
11020}
11021
11022/// visitInlineAsm - Handle a call to an InlineAsm object.
11023void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
11024 const BasicBlock *EHPadBB) {
11025 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11027 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
11028
11029 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
11030 "InvokeInst must have an EHPadBB");
11031
11032 ConstraintDecisionInfo Info;
11033 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
11034 EHPadBB))
11035 return emitInlineAsmError(Call, Info.ErrorMsg.str());
11036
11037 SDValue Glue = Info.Glue;
11038 SDValue Chain = Info.Chain;
11039
11040 // Finish up input operands. Set the input chain and add the flag last.
11041 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
11042 if (Glue.getNode())
11043 Info.AsmNodeOperands.push_back(Glue);
11044
11045 bool IsCallBr = isa<CallBrInst>(Call);
11046 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
11047 Chain =
11048 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
11049 Info.AsmNodeOperands);
11050 Glue = Chain.getValue(1);
11051
11052 // Do additional work to generate outputs.
11053
11054 SmallVector<SDValue, 1> OutputValues;
11055 SmallVector<SDValue, 8> OutChains;
11056
11057 // The indirect targets of a callbr read its outputs again, from the
11058 // registers that the INLINEASM_BR defines them in.
11059 SmallVectorImpl<CallBrOutput> *CallBrOuts =
11060 IsCallBr ? &CallBrOutputs[cast<CallBrInst>(&Call)] : nullptr;
11061
11062 // Deal with output operands.
11063 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
11064 if (OpInfo.Type == InlineAsm::isOutput) {
11065 // Skip trivial output operands.
11066 if (OpInfo.AssignedRegs.Regs.empty())
11067 continue;
11068
11069 SDValue Val = getInlineAsmOutput(OpInfo, OpInfo.AssignedRegs, Call, Chain,
11070 Glue, getCurSDLoc(), FuncInfo, DAG);
11071
11072 // Indirect output manifest as stores. Record output chains.
11073 if (OpInfo.isIndirect) {
11074 // The store is only on the path to a callbr's default target, since
11075 // the asm can branch to an indirect target before it.
11076 if (IsCallBr && cast<CallBrInst>(Call).getNumIndirectDests()) {
11077 DAG.getContext()->diagnose(DiagnosticInfoInlineAsm(
11078 Call, "callbr cannot store indirect output for constraint '" +
11079 Twine(OpInfo.ConstraintCode) +
11080 "' on its indirect paths"));
11081 }
11082
11083 const Value *Ptr = OpInfo.CallOperandVal;
11084 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
11085 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
11086 MachinePointerInfo(Ptr));
11087 OutChains.push_back(Store);
11088 } else {
11089 // generate CopyFromRegs to associated registers.
11090 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
11091 OutputValues.push_back(Val);
11092 if (CallBrOuts) {
11093 // Nothing reads OpInfo after this, so move what the indirect targets
11094 // need instead of copying it.
11095 RegsForValue &Regs = OpInfo.AssignedRegs;
11096 assert(Regs.ValueVTs.size() == 1 && "Expected one value per operand");
11097 CallBrOuts->push_back({std::move(OpInfo), std::move(Regs.Regs),
11098 Regs.RegVTs.front(), Regs.ValueVTs.front()});
11099 }
11100 }
11101 }
11102 }
11103
11104 // Set results.
11105 if (!OutputValues.empty())
11106 setValue(&Call, getInlineAsmResult(Call, OutputValues, getCurSDLoc(), DAG));
11107
11108 // Collect store chains.
11109 if (!OutChains.empty())
11110 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
11111
11112 if (const auto *II = dyn_cast<InvokeInst>(&Call))
11113 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
11114
11115 // Only Update Root if inline assembly has a memory effect.
11116 if (OutputValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
11117 IsCallBr || isa<InvokeInst>(Call))
11118 DAG.setRoot(Chain);
11119}
11120
11121void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
11122 const Twine &Message) {
11123 LLVMContext &Ctx = *DAG.getContext();
11124 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
11125
11126 // Make sure we leave the DAG in a valid state
11127 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11128 SmallVector<EVT, 1> ValueVTs;
11129 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
11130
11131 if (ValueVTs.empty())
11132 return;
11133
11135 for (const EVT &VT : ValueVTs)
11136 Ops.push_back(DAG.getUNDEF(VT));
11137
11138 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
11139}
11140
11141void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
11142 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
11143 MVT::Other, getRoot(),
11144 getValue(I.getArgOperand(0)),
11145 DAG.getSrcValue(I.getArgOperand(0))));
11146}
11147
11148void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
11149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11150 const DataLayout &DL = DAG.getDataLayout();
11151 SDValue V = DAG.getVAArg(
11152 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
11153 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
11154 DL.getABITypeAlign(I.getType()).value());
11155 DAG.setRoot(V.getValue(1));
11156
11157 if (I.getType()->isPointerTy())
11158 V = DAG.getPtrExtOrTrunc(
11159 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
11160 setValue(&I, V);
11161}
11162
11163void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
11164 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
11165 MVT::Other, getRoot(),
11166 getValue(I.getArgOperand(0)),
11167 DAG.getSrcValue(I.getArgOperand(0))));
11168}
11169
11170void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
11171 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
11172 MVT::Other, getRoot(),
11173 getValue(I.getArgOperand(0)),
11174 getValue(I.getArgOperand(1)),
11175 DAG.getSrcValue(I.getArgOperand(0)),
11176 DAG.getSrcValue(I.getArgOperand(1))));
11177}
11178
11180 const Instruction &I,
11181 SDValue Op) {
11182 std::optional<ConstantRange> CR = getRange(I);
11183
11184 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
11185 return Op;
11186
11187 APInt Hi = CR->getUnsignedMax();
11188 unsigned Bits = std::max(Hi.getActiveBits(),
11189 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
11190
11191 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11192
11193 SDLoc SL = getCurSDLoc();
11194
11195 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
11196 DAG.getValueType(SmallVT));
11197 unsigned NumVals = Op.getNode()->getNumValues();
11198 if (NumVals == 1)
11199 return ZExt;
11200
11202
11203 Ops.push_back(ZExt);
11204 for (unsigned I = 1; I != NumVals; ++I)
11205 Ops.push_back(Op.getValue(I));
11206
11207 return DAG.getMergeValues(Ops, SL);
11208}
11209
11211 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
11212 FPClassTest Classes = getNoFPClass(I);
11213 if (Classes == fcNone)
11214 return Op;
11215
11216 SDLoc SL = getCurSDLoc();
11217 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
11218
11219 if (Op.getOpcode() != ISD::MERGE_VALUES) {
11220 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
11221 TestConst);
11222 }
11223
11224 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
11225 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
11226 SDValue MergeOp = Op.getOperand(I);
11227 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
11228 MergeOp, TestConst);
11229 }
11230
11231 return DAG.getMergeValues(Ops, SL);
11232}
11233
11234/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
11235/// the call being lowered.
11236///
11237/// This is a helper for lowering intrinsics that follow a target calling
11238/// convention or require stack pointer adjustment. Only a subset of the
11239/// intrinsic's operands need to participate in the calling convention.
11242 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11243 AttributeSet RetAttrs, bool IsPatchPoint) {
11245 Args.reserve(NumArgs);
11246
11247 // Populate the argument list.
11248 // Attributes for args start at offset 1, after the return attribute.
11249 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11250 ArgI != ArgE; ++ArgI) {
11251 const Value *V = Call->getOperand(ArgI);
11252
11253 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11254
11255 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11256 Entry.setAttributes(Call, ArgI);
11257 Args.push_back(Entry);
11258 }
11259
11261 .setChain(getRoot())
11262 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
11263 RetAttrs)
11264 .setDiscardResult(Call->use_empty())
11265 .setIsPatchPoint(IsPatchPoint)
11267 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
11268}
11269
11270/// Add a stack map intrinsic call's live variable operands to a stackmap
11271/// or patchpoint target node's operand list.
11272///
11273/// Constants are converted to TargetConstants purely as an optimization to
11274/// avoid constant materialization and register allocation.
11275///
11276/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11277/// generate addess computation nodes, and so FinalizeISel can convert the
11278/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11279/// address materialization and register allocation, but may also be required
11280/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11281/// alloca in the entry block, then the runtime may assume that the alloca's
11282/// StackMap location can be read immediately after compilation and that the
11283/// location is valid at any point during execution (this is similar to the
11284/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11285/// only available in a register, then the runtime would need to trap when
11286/// execution reaches the StackMap in order to read the alloca's location.
11287static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11289 SelectionDAGBuilder &Builder) {
11290 SelectionDAG &DAG = Builder.DAG;
11291 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11292 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11293
11294 // Things on the stack are pointer-typed, meaning that they are already
11295 // legal and can be emitted directly to target nodes.
11297 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11298 } else {
11299 // Otherwise emit a target independent node to be legalised.
11300 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11301 }
11302 }
11303}
11304
11305/// Lower llvm.experimental.stackmap.
11306void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11307 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11308 // [live variables...])
11309
11310 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11311
11312 SDValue Chain, InGlue, Callee;
11314
11315 SDLoc DL = getCurSDLoc();
11317
11318 // The stackmap intrinsic only records the live variables (the arguments
11319 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11320 // intrinsic, this won't be lowered to a function call. This means we don't
11321 // have to worry about calling conventions and target specific lowering code.
11322 // Instead we perform the call lowering right here.
11323 //
11324 // chain, flag = CALLSEQ_START(chain, 0, 0)
11325 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11326 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11327 //
11328 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11329 InGlue = Chain.getValue(1);
11330
11331 // Add the STACKMAP operands, starting with DAG house-keeping.
11332 Ops.push_back(Chain);
11333 Ops.push_back(InGlue);
11334
11335 // Add the <id>, <numShadowBytes> operands.
11336 //
11337 // These do not require legalisation, and can be emitted directly to target
11338 // constant nodes.
11340 assert(ID.getValueType() == MVT::i64);
11341 SDValue IDConst =
11342 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11343 Ops.push_back(IDConst);
11344
11345 SDValue Shad = getValue(CI.getArgOperand(1));
11346 assert(Shad.getValueType() == MVT::i32);
11347 SDValue ShadConst =
11348 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11349 Ops.push_back(ShadConst);
11350
11351 // Add the live variables.
11352 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11353
11354 // Create the STACKMAP node.
11355 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11356 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11357 InGlue = Chain.getValue(1);
11358
11359 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11360
11361 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11362
11363 // Set the root to the target-lowered call chain.
11364 DAG.setRoot(Chain);
11365
11366 // Inform the Frame Information that we have a stackmap in this function.
11367 FuncInfo.MF->getFrameInfo().setHasStackMap();
11368}
11369
11370/// Lower llvm.experimental.patchpoint directly to its target opcode.
11371void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11372 const BasicBlock *EHPadBB) {
11373 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11374 // i32 <numBytes>,
11375 // i8* <target>,
11376 // i32 <numArgs>,
11377 // [Args...],
11378 // [live variables...])
11379
11381 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11382 bool HasDef = !CB.getType()->isVoidTy();
11383 SDLoc dl = getCurSDLoc();
11385
11386 // Handle immediate and symbolic callees.
11387 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11388 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11389 /*isTarget=*/true);
11390 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11391 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11392 SDLoc(SymbolicCallee),
11393 SymbolicCallee->getValueType(0));
11394
11395 // Get the real number of arguments participating in the call <numArgs>
11397 unsigned NumArgs = NArgVal->getAsZExtVal();
11398
11399 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11400 // Intrinsics include all meta-operands up to but not including CC.
11401 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11402 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11403 "Not enough arguments provided to the patchpoint intrinsic");
11404
11405 // For AnyRegCC the arguments are lowered later on manually.
11406 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11407 Type *ReturnTy =
11408 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11409
11410 TargetLowering::CallLoweringInfo CLI(DAG);
11411 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11412 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11413 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11414
11415 SDNode *CallEnd = Result.second.getNode();
11416 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11417 CallEnd = CallEnd->getOperand(0).getNode();
11418 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11419 CallEnd = CallEnd->getOperand(0).getNode();
11420
11421 /// Get a call instruction from the call sequence chain.
11422 /// Tail calls are not allowed.
11423 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11424 "Expected a callseq node.");
11425 SDNode *Call = CallEnd->getOperand(0).getNode();
11426 bool HasGlue = Call->getGluedNode();
11427
11428 // Replace the target specific call node with the patchable intrinsic.
11430
11431 // Push the chain.
11432 Ops.push_back(*(Call->op_begin()));
11433
11434 // Optionally, push the glue (if any).
11435 if (HasGlue)
11436 Ops.push_back(*(Call->op_end() - 1));
11437
11438 // Push the register mask info.
11439 if (HasGlue)
11440 Ops.push_back(*(Call->op_end() - 2));
11441 else
11442 Ops.push_back(*(Call->op_end() - 1));
11443
11444 // Add the <id> and <numBytes> constants.
11446 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11448 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11449
11450 // Add the callee.
11451 Ops.push_back(Callee);
11452
11453 // Adjust <numArgs> to account for any arguments that have been passed on the
11454 // stack instead.
11455 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11456 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11457 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11458 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11459
11460 // Add the calling convention
11461 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11462
11463 // Add the arguments we omitted previously. The register allocator should
11464 // place these in any free register.
11465 if (IsAnyRegCC)
11466 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11467 Ops.push_back(getValue(CB.getArgOperand(i)));
11468
11469 // Push the arguments from the call instruction.
11470 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11471 Ops.append(Call->op_begin() + 2, e);
11472
11473 // Push live variables for the stack map.
11474 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11475
11476 SDVTList NodeTys;
11477 if (IsAnyRegCC && HasDef) {
11478 // Create the return types based on the intrinsic definition
11479 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11480 SmallVector<EVT, 3> ValueVTs;
11481 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11482 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11483
11484 // There is always a chain and a glue type at the end
11485 ValueVTs.push_back(MVT::Other);
11486 ValueVTs.push_back(MVT::Glue);
11487 NodeTys = DAG.getVTList(ValueVTs);
11488 } else
11489 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11490
11491 // Replace the target specific call node with a PATCHPOINT node.
11492 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11493
11494 // Update the NodeMap.
11495 if (HasDef) {
11496 if (IsAnyRegCC)
11497 setValue(&CB, SDValue(PPV.getNode(), 0));
11498 else
11499 setValue(&CB, Result.first);
11500 }
11501
11502 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11503 // call sequence. Furthermore the location of the chain and glue can change
11504 // when the AnyReg calling convention is used and the intrinsic returns a
11505 // value.
11506 if (IsAnyRegCC && HasDef) {
11507 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11508 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11509 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11510 } else
11511 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11512 DAG.DeleteNode(Call);
11513
11514 // Inform the Frame Information that we have a patchpoint in this function.
11515 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11516}
11517
11518void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11519 unsigned Intrinsic) {
11520 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11521 SDValue Op1 = getValue(I.getArgOperand(0));
11522 SDValue Op2;
11523 if (I.arg_size() > 1)
11524 Op2 = getValue(I.getArgOperand(1));
11525 SDLoc dl = getCurSDLoc();
11526 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11527 SDValue Res;
11528 SDNodeFlags SDFlags;
11529 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11530 SDFlags.copyFMF(*FPMO);
11531
11532 switch (Intrinsic) {
11533 case Intrinsic::vector_reduce_fadd:
11534 if (SDFlags.hasAllowReassociation())
11535 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11536 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11537 SDFlags);
11538 else
11539 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11540 break;
11541 case Intrinsic::vector_reduce_fmul:
11542 if (SDFlags.hasAllowReassociation())
11543 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11544 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11545 SDFlags);
11546 else
11547 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11548 break;
11549 case Intrinsic::vector_reduce_add:
11550 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11551 break;
11552 case Intrinsic::vector_reduce_mul:
11553 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11554 break;
11555 case Intrinsic::vector_reduce_and:
11556 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11557 break;
11558 case Intrinsic::vector_reduce_or:
11559 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11560 break;
11561 case Intrinsic::vector_reduce_xor:
11562 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11563 break;
11564 case Intrinsic::vector_reduce_smax:
11565 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11566 break;
11567 case Intrinsic::vector_reduce_smin:
11568 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11569 break;
11570 case Intrinsic::vector_reduce_umax:
11571 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11572 break;
11573 case Intrinsic::vector_reduce_umin:
11574 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11575 break;
11576 case Intrinsic::vector_reduce_fmax:
11577 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11578 break;
11579 case Intrinsic::vector_reduce_fmin:
11580 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11581 break;
11582 case Intrinsic::vector_reduce_fmaximum:
11583 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11584 break;
11585 case Intrinsic::vector_reduce_fminimum:
11586 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11587 break;
11588 case Intrinsic::vector_reduce_fmaximumnum:
11589 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11590 break;
11591 case Intrinsic::vector_reduce_fminimumnum:
11592 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11593 break;
11594 default:
11595 llvm_unreachable("Unhandled vector reduce intrinsic");
11596 }
11597 setValue(&I, Res);
11598}
11599
11600/// Returns an AttributeList representing the attributes applied to the return
11601/// value of the given call.
11604 if (CLI.RetSExt)
11605 Attrs.push_back(Attribute::SExt);
11606 if (CLI.RetZExt)
11607 Attrs.push_back(Attribute::ZExt);
11608 if (CLI.IsInReg)
11609 Attrs.push_back(Attribute::InReg);
11610
11611 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11612 Attrs);
11613}
11614
11615/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11616/// implementation, which just calls LowerCall.
11617/// FIXME: When all targets are
11618/// migrated to using LowerCall, this hook should be integrated into SDISel.
11619std::pair<SDValue, SDValue>
11622
11623 // Handle the incoming return values from the call.
11624 CLI.Ins.clear();
11625 SmallVector<Type *, 4> RetOrigTys;
11627 auto &DL = CLI.DAG.getDataLayout();
11628 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11629
11630 SmallVector<EVT, 4> RetVTs;
11631 if (CLI.RetTy != CLI.OrigRetTy) {
11632 assert(RetOrigTys.size() == 1 &&
11633 "Only supported for non-aggregate returns");
11634 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11635 } else {
11636 for (Type *Ty : RetOrigTys)
11637 RetVTs.push_back(getValueType(DL, Ty));
11638 }
11639
11640 if (CLI.IsPostTypeLegalization) {
11641 // If we are lowering a libcall after legalization, split the return type.
11642 SmallVector<Type *, 4> OldRetOrigTys;
11643 SmallVector<EVT, 4> OldRetVTs;
11644 SmallVector<TypeSize, 4> OldOffsets;
11645 RetOrigTys.swap(OldRetOrigTys);
11646 RetVTs.swap(OldRetVTs);
11647 Offsets.swap(OldOffsets);
11648
11649 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11650 EVT RetVT = OldRetVTs[i];
11651 uint64_t Offset = OldOffsets[i];
11652 MVT RegisterVT = getRegisterType(Context, RetVT);
11653 unsigned NumRegs = getNumRegisters(Context, RetVT);
11654 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11655 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11656 RetVTs.append(NumRegs, RegisterVT);
11657 for (unsigned j = 0; j != NumRegs; ++j)
11658 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11659 }
11660 }
11661
11663 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11664
11665 bool CanLowerReturn =
11667 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11668
11669 SDValue DemoteStackSlot;
11670 int DemoteStackIdx = -100;
11671 if (!CanLowerReturn) {
11672 // FIXME: equivalent assert?
11673 // assert(!CS.hasInAllocaArgument() &&
11674 // "sret demotion is incompatible with inalloca");
11675 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11676 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11678 DemoteStackIdx =
11679 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11680 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11681
11682 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11683 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11684 Entry.IsSRet = true;
11685 Entry.Alignment = Alignment;
11686 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11687 CLI.NumFixedArgs += 1;
11688 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11690
11691 // sret demotion isn't compatible with tail-calls, since the sret argument
11692 // points into the callers stack frame.
11693 CLI.IsTailCall = false;
11694 } else {
11695 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11696 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11697 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11698 ISD::ArgFlagsTy Flags;
11699 if (NeedsRegBlock) {
11700 Flags.setInConsecutiveRegs();
11701 if (I == RetVTs.size() - 1)
11702 Flags.setInConsecutiveRegsLast();
11703 }
11704 EVT VT = RetVTs[I];
11705 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11706 unsigned NumRegs =
11708 for (unsigned i = 0; i != NumRegs; ++i) {
11709 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11711 if (CLI.RetTy->isPointerTy()) {
11712 Ret.Flags.setPointer();
11714 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11715 }
11716 if (CLI.RetSExt)
11717 Ret.Flags.setSExt();
11718 if (CLI.RetZExt)
11719 Ret.Flags.setZExt();
11720 if (CLI.IsInReg)
11721 Ret.Flags.setInReg();
11722 CLI.Ins.push_back(Ret);
11723 }
11724 }
11725 }
11726
11727 // We push in swifterror return as the last element of CLI.Ins.
11728 ArgListTy &Args = CLI.getArgs();
11729 if (supportSwiftError()) {
11730 for (const ArgListEntry &Arg : Args) {
11731 if (Arg.IsSwiftError) {
11732 ISD::ArgFlagsTy Flags;
11733 Flags.setSwiftError();
11736 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11737 CLI.Ins.push_back(Ret);
11738 }
11739 }
11740 }
11741
11742 // Handle all of the outgoing arguments.
11743 CLI.Outs.clear();
11744 CLI.OutVals.clear();
11745 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11746 SmallVector<Type *, 4> OrigArgTys;
11747 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11748 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11749 Type *FinalType = Args[i].Ty;
11750 if (Args[i].IsByVal)
11751 FinalType = Args[i].IndirectType;
11752 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11753 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11754 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11755 ++Value) {
11756 Type *OrigArgTy = OrigArgTys[Value];
11757 Type *ArgTy = OrigArgTy;
11758 if (Args[i].Ty != Args[i].OrigTy) {
11759 assert(Value == 0 && "Only supported for non-aggregate arguments");
11760 ArgTy = Args[i].Ty;
11761 }
11762
11763 EVT VT = getValueType(DL, ArgTy);
11764 SDValue Op = SDValue(Args[i].Node.getNode(),
11765 Args[i].Node.getResNo() + Value);
11766 ISD::ArgFlagsTy Flags;
11767
11768 // Certain targets (such as MIPS), may have a different ABI alignment
11769 // for a type depending on the context. Give the target a chance to
11770 // specify the alignment it wants.
11771 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11772 Flags.setOrigAlign(OriginalAlignment);
11773
11774 if (i >= CLI.NumFixedArgs)
11775 Flags.setVarArg();
11776 if (ArgTy->isPointerTy()) {
11777 Flags.setPointer();
11778 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11779 }
11780 if (Args[i].IsZExt)
11781 Flags.setZExt();
11782 if (Args[i].IsSExt)
11783 Flags.setSExt();
11784 if (Args[i].IsNoExt)
11785 Flags.setNoExt();
11786 if (Args[i].IsInReg) {
11787 // If we are using vectorcall calling convention, a structure that is
11788 // passed InReg - is surely an HVA
11790 isa<StructType>(FinalType)) {
11791 // The first value of a structure is marked
11792 if (0 == Value)
11793 Flags.setHvaStart();
11794 Flags.setHva();
11795 }
11796 // Set InReg Flag
11797 Flags.setInReg();
11798 }
11799 if (Args[i].IsSRet)
11800 Flags.setSRet();
11801 if (Args[i].IsSwiftSelf)
11802 Flags.setSwiftSelf();
11803 if (Args[i].IsSwiftAsync)
11804 Flags.setSwiftAsync();
11805 if (Args[i].IsSwiftError)
11806 Flags.setSwiftError();
11807 if (Args[i].IsCFGuardTarget)
11808 Flags.setCFGuardTarget();
11809 if (Args[i].IsByVal)
11810 Flags.setByVal();
11811 if (Args[i].IsByRef)
11812 Flags.setByRef();
11813 if (Args[i].IsPreallocated) {
11814 Flags.setPreallocated();
11815 // Set the byval flag for CCAssignFn callbacks that don't know about
11816 // preallocated. This way we can know how many bytes we should've
11817 // allocated and how many bytes a callee cleanup function will pop. If
11818 // we port preallocated to more targets, we'll have to add custom
11819 // preallocated handling in the various CC lowering callbacks.
11820 Flags.setByVal();
11821 }
11822 if (Args[i].IsInAlloca) {
11823 Flags.setInAlloca();
11824 // Set the byval flag for CCAssignFn callbacks that don't know about
11825 // inalloca. This way we can know how many bytes we should've allocated
11826 // and how many bytes a callee cleanup function will pop. If we port
11827 // inalloca to more targets, we'll have to add custom inalloca handling
11828 // in the various CC lowering callbacks.
11829 Flags.setByVal();
11830 }
11831 Align MemAlign;
11832 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11833 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11834 Flags.setByValSize(FrameSize);
11835
11836 // info is not there but there are cases it cannot get right.
11837 if (auto MA = Args[i].Alignment)
11838 MemAlign = *MA;
11839 else
11840 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11841 } else if (auto MA = Args[i].Alignment) {
11842 MemAlign = *MA;
11843 } else {
11844 MemAlign = OriginalAlignment;
11845 }
11846 Flags.setMemAlign(MemAlign);
11847 if (Args[i].IsNest)
11848 Flags.setNest();
11849 if (NeedsRegBlock)
11850 Flags.setInConsecutiveRegs();
11851
11853 unsigned NumParts =
11857
11858 if (Args[i].IsSExt)
11860 else if (Args[i].IsZExt)
11862
11863 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11864 // for now.
11865 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11867 assert((CLI.RetTy == Args[i].Ty ||
11868 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11870 Args[i].Ty->getPointerAddressSpace())) &&
11871 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11872 // Before passing 'returned' to the target lowering code, ensure that
11873 // either the register MVT and the actual EVT are the same size or that
11874 // the return value and argument are extended in the same way; in these
11875 // cases it's safe to pass the argument register value unchanged as the
11876 // return register value (although it's at the target's option whether
11877 // to do so)
11878 // TODO: allow code generation to take advantage of partially preserved
11879 // registers rather than clobbering the entire register when the
11880 // parameter extension method is not compatible with the return
11881 // extension method
11882 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11883 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11884 CLI.RetZExt == Args[i].IsZExt))
11885 Flags.setReturned();
11886 }
11887
11888 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11889 CLI.CallConv, ExtendKind);
11890
11891 for (unsigned j = 0; j != NumParts; ++j) {
11892 // if it isn't first piece, alignment must be 1
11893 // For scalable vectors the scalable part is currently handled
11894 // by individual targets, so we just use the known minimum size here.
11895 ISD::OutputArg MyFlags(
11896 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11897 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11898 if (NumParts > 1 && j == 0)
11899 MyFlags.Flags.setSplit();
11900 else if (j != 0) {
11901 MyFlags.Flags.setOrigAlign(Align(1));
11902 if (j == NumParts - 1)
11903 MyFlags.Flags.setSplitEnd();
11904 }
11905
11906 CLI.Outs.push_back(MyFlags);
11907 CLI.OutVals.push_back(Parts[j]);
11908 }
11909
11910 if (NeedsRegBlock && Value == NumValues - 1)
11911 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11912 }
11913 }
11914
11916 CLI.Chain = LowerCall(CLI, InVals);
11917
11918 // Update CLI.InVals to use outside of this function.
11919 CLI.InVals = InVals;
11920
11921 // Verify that the target's LowerCall behaved as expected.
11922 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11923 "LowerCall didn't return a valid chain!");
11924 assert((!CLI.IsTailCall || InVals.empty()) &&
11925 "LowerCall emitted a return value for a tail call!");
11926 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11927 "LowerCall didn't emit the correct number of values!");
11928
11929 // For a tail call, the return value is merely live-out and there aren't
11930 // any nodes in the DAG representing it. Return a special value to
11931 // indicate that a tail call has been emitted and no more Instructions
11932 // should be processed in the current block.
11933 if (CLI.IsTailCall) {
11934 CLI.DAG.setRoot(CLI.Chain);
11935 return std::make_pair(SDValue(), SDValue());
11936 }
11937
11938#ifndef NDEBUG
11939 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11940 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11941 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11942 "LowerCall emitted a value with the wrong type!");
11943 }
11944#endif
11945
11946 SmallVector<SDValue, 4> ReturnValues;
11947 if (!CanLowerReturn) {
11948 // The instruction result is the result of loading from the
11949 // hidden sret parameter.
11950 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11951
11952 unsigned NumValues = RetVTs.size();
11953 ReturnValues.resize(NumValues);
11954 SmallVector<SDValue, 4> Chains(NumValues);
11955
11956 // An aggregate return value cannot wrap around the address space, so
11957 // offsets to its parts don't wrap either.
11959 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11960 for (unsigned i = 0; i < NumValues; ++i) {
11962 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11964 SDValue L = CLI.DAG.getLoad(
11965 RetVTs[i], CLI.DL, CLI.Chain, Add,
11967 DemoteStackIdx, Offsets[i]),
11968 HiddenSRetAlign);
11969 ReturnValues[i] = L;
11970 Chains[i] = L.getValue(1);
11971 }
11972
11973 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11974 } else {
11975 // Collect the legal value parts into potentially illegal values
11976 // that correspond to the original function's return values.
11977 std::optional<ISD::NodeType> AssertOp;
11978 if (CLI.RetSExt)
11979 AssertOp = ISD::AssertSext;
11980 else if (CLI.RetZExt)
11981 AssertOp = ISD::AssertZext;
11982 unsigned CurReg = 0;
11983 for (EVT VT : RetVTs) {
11984 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11985 unsigned NumRegs =
11987
11988 ReturnValues.push_back(getCopyFromParts(
11989 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11990 CLI.Chain, CLI.CallConv, AssertOp));
11991 CurReg += NumRegs;
11992 }
11993
11994 // For a function returning void, there is no return value. We can't create
11995 // such a node, so we just return a null return value in that case. In
11996 // that case, nothing will actually look at the value.
11997 if (ReturnValues.empty())
11998 return std::make_pair(SDValue(), CLI.Chain);
11999 }
12000
12001 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
12002 CLI.DAG.getVTList(RetVTs), ReturnValues);
12003 return std::make_pair(Res, CLI.Chain);
12004}
12005
12006/// Places new result values for the node in Results (their number
12007/// and types must exactly match those of the original return values of
12008/// the node), or leaves Results empty, which indicates that the node is not
12009/// to be custom lowered after all.
12012 SelectionDAG &DAG) const {
12013 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
12014
12015 if (!Res.getNode())
12016 return;
12017
12018 // If the original node has one result, take the return value from
12019 // LowerOperation as is. It might not be result number 0.
12020 if (N->getNumValues() == 1) {
12021 Results.push_back(Res);
12022 return;
12023 }
12024
12025 // If the original node has multiple results, then the return node should
12026 // have the same number of results.
12027 assert((N->getNumValues() == Res->getNumValues()) &&
12028 "Lowering returned the wrong number of results!");
12029
12030 // Places new result values base on N result number.
12031 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
12032 Results.push_back(Res.getValue(I));
12033}
12034
12036 llvm_unreachable("LowerOperation not implemented for this target!");
12037}
12038
12040 Register Reg,
12041 ISD::NodeType ExtendType) {
12043 assert((Op.getOpcode() != ISD::CopyFromReg ||
12044 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
12045 "Copy from a reg to the same reg!");
12046 assert(!Reg.isPhysical() && "Is a physreg");
12047
12048 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12049 // If this is an InlineAsm we have to match the registers required, not the
12050 // notional registers required by the type.
12051
12052 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
12053 std::nullopt); // This is not an ABI copy.
12054 SDValue Chain = DAG.getEntryNode();
12055
12056 if (ExtendType == ISD::ANY_EXTEND) {
12057 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
12058 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
12059 ExtendType = PreferredExtendIt->second;
12060 }
12061 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
12062 PendingExports.push_back(Chain);
12063}
12064
12066
12067/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
12068/// entry block, return true. This includes arguments used by switches, since
12069/// the switch may expand into multiple basic blocks.
12070static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
12071 // With FastISel active, we may be splitting blocks, so force creation
12072 // of virtual registers for all non-dead arguments.
12073 if (FastISel)
12074 return A->use_empty();
12075
12076 const BasicBlock &Entry = A->getParent()->front();
12077 for (const User *U : A->users())
12078 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
12079 return false; // Use not in entry block.
12080
12081 return true;
12082}
12083
12085 DenseMap<const Argument *,
12086 std::pair<const AllocaInst *, const StoreInst *>>;
12087
12088/// Scan the entry block of the function in FuncInfo for arguments that look
12089/// like copies into a local alloca. Record any copied arguments in
12090/// ArgCopyElisionCandidates.
12091static void
12093 FunctionLoweringInfo *FuncInfo,
12094 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
12095 // Record the state of every static alloca used in the entry block. Argument
12096 // allocas are all used in the entry block, so we need approximately as many
12097 // entries as we have arguments.
12098 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
12100 unsigned NumArgs = FuncInfo->Fn->arg_size();
12101 StaticAllocas.reserve(NumArgs * 2);
12102
12103 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
12104 if (!V)
12105 return nullptr;
12106 V = V->stripPointerCasts();
12107 const auto *AI = dyn_cast<AllocaInst>(V);
12108 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
12109 return nullptr;
12110 auto Iter = StaticAllocas.insert({AI, Unknown});
12111 return &Iter.first->second;
12112 };
12113
12114 // Look for stores of arguments to static allocas. Look through bitcasts and
12115 // GEPs to handle type coercions, as long as the alloca is fully initialized
12116 // by the store. Any non-store use of an alloca escapes it and any subsequent
12117 // unanalyzed store might write it.
12118 // FIXME: Handle structs initialized with multiple stores.
12119 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
12120 // Look for stores, and handle non-store uses conservatively.
12121 const auto *SI = dyn_cast<StoreInst>(&I);
12122 if (!SI) {
12123 // We will look through cast uses, so ignore them completely.
12124 if (I.isCast())
12125 continue;
12126 // Ignore pseudo op intrinsics, they don't escape or store to allocas.
12128 continue;
12129 // This is an unknown instruction. Assume it escapes or writes to all
12130 // static alloca operands.
12131 for (const Use &U : I.operands()) {
12132 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
12133 *Info = StaticAllocaInfo::Clobbered;
12134 }
12135 continue;
12136 }
12137
12138 // If the stored value is a static alloca, mark it as escaped.
12139 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
12140 *Info = StaticAllocaInfo::Clobbered;
12141
12142 // Check if the destination is a static alloca.
12143 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
12144 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
12145 if (!Info)
12146 continue;
12147 const AllocaInst *AI = cast<AllocaInst>(Dst);
12148
12149 // Skip allocas that have been initialized or clobbered.
12150 if (*Info != StaticAllocaInfo::Unknown)
12151 continue;
12152
12153 // Check if the stored value is an argument, and that this store fully
12154 // initializes the alloca.
12155 // If the argument type has padding bits we can't directly forward a pointer
12156 // as the upper bits may contain garbage.
12157 // Don't elide copies from the same argument twice.
12158 const Value *Val = SI->getValueOperand()->stripPointerCasts();
12159 const auto *Arg = dyn_cast<Argument>(Val);
12160 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
12161 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
12162 Arg->getType()->isEmptyTy() || !AllocaSize ||
12163 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
12164 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
12165 ArgCopyElisionCandidates.count(Arg)) {
12166 *Info = StaticAllocaInfo::Clobbered;
12167 continue;
12168 }
12169
12170 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
12171 << '\n');
12172
12173 // Mark this alloca and store for argument copy elision.
12174 *Info = StaticAllocaInfo::Elidable;
12175 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
12176
12177 // Stop scanning if we've seen all arguments. This will happen early in -O0
12178 // builds, which is useful, because -O0 builds have large entry blocks and
12179 // many allocas.
12180 if (ArgCopyElisionCandidates.size() == NumArgs)
12181 break;
12182 }
12183}
12184
12185/// Try to elide argument copies from memory into a local alloca. Succeeds if
12186/// ArgVal is a load from a suitable fixed stack object.
12189 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
12190 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
12191 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
12192 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
12193 // Check if this is a load from a fixed stack object.
12194 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
12195 if (!LNode)
12196 return;
12197 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
12198 if (!FINode)
12199 return;
12200
12201 // Check that the fixed stack object is the right size and alignment.
12202 // Look at the alignment that the user wrote on the alloca instead of looking
12203 // at the stack object.
12204 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
12205 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
12206 const AllocaInst *AI = ArgCopyIter->second.first;
12207 int FixedIndex = FINode->getIndex();
12208 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
12209 int OldIndex = AllocaIndex;
12210 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
12211 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
12212 LLVM_DEBUG(
12213 dbgs() << " argument copy elision failed due to bad fixed stack "
12214 "object size\n");
12215 return;
12216 }
12217 Align RequiredAlignment = AI->getAlign();
12218 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
12219 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
12220 "greater than stack argument alignment ("
12221 << DebugStr(RequiredAlignment) << " vs "
12222 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
12223 return;
12224 }
12225
12226 // Perform the elision. Delete the old stack object and replace its only use
12227 // in the variable info map. Mark the stack object as mutable and aliased.
12228 LLVM_DEBUG({
12229 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
12230 << " Replacing frame index " << OldIndex << " with " << FixedIndex
12231 << '\n';
12232 });
12233 MFI.RemoveStackObject(OldIndex);
12234 MFI.setIsImmutableObjectIndex(FixedIndex, false);
12235 MFI.setIsAliasedObjectIndex(FixedIndex, true);
12236 AllocaIndex = FixedIndex;
12237 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
12238 for (SDValue ArgVal : ArgVals)
12239 Chains.push_back(ArgVal.getValue(1));
12240
12241 // Avoid emitting code for the store implementing the copy.
12242 const StoreInst *SI = ArgCopyIter->second.second;
12243 ElidedArgCopyInstrs.insert(SI);
12244
12245 // Check for uses of the argument again so that we can avoid exporting ArgVal
12246 // if it is't used by anything other than the store.
12247 for (const Value *U : Arg.users()) {
12248 if (U != SI) {
12249 ArgHasUses = true;
12250 break;
12251 }
12252 }
12253}
12254
12255void SelectionDAGISel::LowerArguments(const Function &F, bool FastISel) {
12256 SelectionDAG &DAG = SDB->DAG;
12257 SDLoc dl = SDB->getCurSDLoc();
12258 const DataLayout &DL = DAG.getDataLayout();
12260
12261 // In Naked functions we aren't going to save any registers.
12262 if (F.hasFnAttribute(Attribute::Naked))
12263 return;
12264
12265 if (!FuncInfo->CanLowerReturn) {
12266 // Put in an sret pointer parameter before all the other parameters.
12267 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12268
12269 ISD::ArgFlagsTy Flags;
12270 Flags.setSRet();
12271 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
12272 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12274 Ins.push_back(RetArg);
12275 }
12276
12277 // Look for stores of arguments to static allocas. Mark such arguments with a
12278 // flag to ask the target to give us the memory location of that argument if
12279 // available.
12280 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12282 ArgCopyElisionCandidates);
12283
12284 // Set up the incoming argument description vector.
12285 for (const Argument &Arg : F.args()) {
12286 unsigned ArgNo = Arg.getArgNo();
12288 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12289 bool isArgValueUsed = !Arg.use_empty();
12290 Type *FinalType = Arg.getType();
12291 if (Arg.hasAttribute(Attribute::ByVal))
12292 FinalType = Arg.getParamByValType();
12293 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12294 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12295 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12296 ++Value) {
12297 Type *ArgTy = Types[Value];
12298 EVT VT = TLI->getValueType(DL, ArgTy);
12299 ISD::ArgFlagsTy Flags;
12300
12301 if (ArgTy->isPointerTy()) {
12302 Flags.setPointer();
12303 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12304 }
12305 if (Arg.hasAttribute(Attribute::ZExt))
12306 Flags.setZExt();
12307 if (Arg.hasAttribute(Attribute::SExt))
12308 Flags.setSExt();
12309 if (Arg.hasAttribute(Attribute::InReg)) {
12310 // If we are using vectorcall calling convention, a structure that is
12311 // passed InReg - is surely an HVA
12312 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12313 isa<StructType>(Arg.getType())) {
12314 // The first value of a structure is marked
12315 if (0 == Value)
12316 Flags.setHvaStart();
12317 Flags.setHva();
12318 }
12319 // Set InReg Flag
12320 Flags.setInReg();
12321 }
12322 if (Arg.hasAttribute(Attribute::StructRet))
12323 Flags.setSRet();
12324 if (Arg.hasAttribute(Attribute::SwiftSelf))
12325 Flags.setSwiftSelf();
12326 if (Arg.hasAttribute(Attribute::SwiftAsync))
12327 Flags.setSwiftAsync();
12328 if (Arg.hasAttribute(Attribute::SwiftError))
12329 Flags.setSwiftError();
12330 if (Arg.hasAttribute(Attribute::ByVal))
12331 Flags.setByVal();
12332 if (Arg.hasAttribute(Attribute::ByRef))
12333 Flags.setByRef();
12334 if (Arg.hasAttribute(Attribute::InAlloca)) {
12335 Flags.setInAlloca();
12336 // Set the byval flag for CCAssignFn callbacks that don't know about
12337 // inalloca. This way we can know how many bytes we should've allocated
12338 // and how many bytes a callee cleanup function will pop. If we port
12339 // inalloca to more targets, we'll have to add custom inalloca handling
12340 // in the various CC lowering callbacks.
12341 Flags.setByVal();
12342 }
12343 if (Arg.hasAttribute(Attribute::Preallocated)) {
12344 Flags.setPreallocated();
12345 // Set the byval flag for CCAssignFn callbacks that don't know about
12346 // preallocated. This way we can know how many bytes we should've
12347 // allocated and how many bytes a callee cleanup function will pop. If
12348 // we port preallocated to more targets, we'll have to add custom
12349 // preallocated handling in the various CC lowering callbacks.
12350 Flags.setByVal();
12351 }
12352
12353 // Certain targets (such as MIPS), may have a different ABI alignment
12354 // for a type depending on the context. Give the target a chance to
12355 // specify the alignment it wants.
12356 const Align OriginalAlignment(
12357 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12358 Flags.setOrigAlign(OriginalAlignment);
12359
12360 Align MemAlign;
12361 Type *ArgMemTy = nullptr;
12362 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12363 Flags.isByRef()) {
12364 if (!ArgMemTy)
12365 ArgMemTy = Arg.getPointeeInMemoryValueType();
12366
12367 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12368
12369 // For in-memory arguments, size and alignment should be passed from FE.
12370 // BE will guess if this info is not there but there are cases it cannot
12371 // get right.
12372 if (auto ParamAlign = Arg.getParamStackAlign())
12373 MemAlign = *ParamAlign;
12374 else if ((ParamAlign = Arg.getParamAlign()))
12375 MemAlign = *ParamAlign;
12376 else
12377 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12378 if (Flags.isByRef())
12379 Flags.setByRefSize(MemSize);
12380 else
12381 Flags.setByValSize(MemSize);
12382 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12383 MemAlign = *ParamAlign;
12384 } else {
12385 MemAlign = OriginalAlignment;
12386 }
12387 Flags.setMemAlign(MemAlign);
12388
12389 if (Arg.hasAttribute(Attribute::Nest))
12390 Flags.setNest();
12391 if (NeedsRegBlock)
12392 Flags.setInConsecutiveRegs();
12393 if (ArgCopyElisionCandidates.count(&Arg))
12394 Flags.setCopyElisionCandidate();
12395 if (Arg.hasAttribute(Attribute::Returned))
12396 Flags.setReturned();
12397
12398 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12399 *CurDAG->getContext(), F.getCallingConv(), VT);
12400 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12401 *CurDAG->getContext(), F.getCallingConv(), VT);
12402 for (unsigned i = 0; i != NumRegs; ++i) {
12403 // For scalable vectors, use the minimum size; individual targets
12404 // are responsible for handling scalable vector arguments and
12405 // return values.
12406 ISD::InputArg MyFlags(
12407 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12408 i * RegisterVT.getStoreSize().getKnownMinValue());
12409 if (NumRegs > 1 && i == 0)
12410 MyFlags.Flags.setSplit();
12411 // if it isn't first piece, alignment must be 1
12412 else if (i > 0) {
12413 MyFlags.Flags.setOrigAlign(Align(1));
12414 if (i == NumRegs - 1)
12415 MyFlags.Flags.setSplitEnd();
12416 }
12417 Ins.push_back(MyFlags);
12418 }
12419 if (NeedsRegBlock && Value == NumValues - 1)
12420 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12421 }
12422 }
12423
12424 // Call the target to set up the argument values.
12426 SDValue NewRoot = TLI->LowerFormalArguments(
12427 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12428
12429 // Verify that the target's LowerFormalArguments behaved as expected.
12430 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12431 "LowerFormalArguments didn't return a valid chain!");
12432 assert(InVals.size() == Ins.size() &&
12433 "LowerFormalArguments didn't emit the correct number of values!");
12434 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12435 "LowerFormalArguments emitted a null value!");
12436
12437 // Update the DAG with the new chain value resulting from argument lowering.
12438 DAG.setRoot(NewRoot);
12439
12440 // Set up the argument values.
12441 unsigned i = 0;
12442 if (!FuncInfo->CanLowerReturn) {
12443 // Create a virtual register for the sret pointer, and put in a copy
12444 // from the sret argument into it.
12445 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12446 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12447 std::optional<ISD::NodeType> AssertOp;
12448 SDValue ArgValue =
12449 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12450 F.getCallingConv(), AssertOp);
12451
12452 MachineFunction& MF = SDB->DAG.getMachineFunction();
12453 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12454 Register SRetReg =
12455 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12456 FuncInfo->DemoteRegister = SRetReg;
12457 NewRoot =
12458 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12459 DAG.setRoot(NewRoot);
12460
12461 // i indexes lowered arguments. Bump it past the hidden sret argument.
12462 ++i;
12463 }
12464
12466 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12467 for (const Argument &Arg : F.args()) {
12468 SmallVector<SDValue, 4> ArgValues;
12469 SmallVector<EVT, 4> ValueVTs;
12470 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12471 unsigned NumValues = ValueVTs.size();
12472 if (NumValues == 0)
12473 continue;
12474
12475 bool ArgHasUses = !Arg.use_empty();
12476
12477 // Elide the copying store if the target loaded this argument from a
12478 // suitable fixed stack object.
12479 if (Ins[i].Flags.isCopyElisionCandidate()) {
12480 unsigned NumParts = 0;
12481 for (EVT VT : ValueVTs)
12482 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12483 F.getCallingConv(), VT);
12484
12485 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12486 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12487 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12488 }
12489
12490 // If this argument is unused then remember its value. It is used to generate
12491 // debugging information.
12492 bool isSwiftErrorArg =
12493 TLI->supportSwiftError() &&
12494 Arg.hasAttribute(Attribute::SwiftError);
12495 if (!ArgHasUses && !isSwiftErrorArg) {
12496 SDB->setUnusedArgValue(&Arg, InVals[i]);
12497
12498 // Also remember any frame index for use in FastISel.
12499 if (FrameIndexSDNode *FI =
12501 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12502 }
12503
12504 for (unsigned Val = 0; Val != NumValues; ++Val) {
12505 EVT VT = ValueVTs[Val];
12506 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12507 F.getCallingConv(), VT);
12508 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12509 *CurDAG->getContext(), F.getCallingConv(), VT);
12510
12511 // Even an apparent 'unused' swifterror argument needs to be returned. So
12512 // we do generate a copy for it that can be used on return from the
12513 // function.
12514 if (ArgHasUses || isSwiftErrorArg) {
12515 std::optional<ISD::NodeType> AssertOp;
12516 if (Arg.hasAttribute(Attribute::SExt))
12517 AssertOp = ISD::AssertSext;
12518 else if (Arg.hasAttribute(Attribute::ZExt))
12519 AssertOp = ISD::AssertZext;
12520
12521 SDValue OutVal =
12522 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12523 NewRoot, F.getCallingConv(), AssertOp);
12524
12525 FPClassTest NoFPClass = Arg.getNoFPClass();
12526 if (NoFPClass != fcNone) {
12527 SDValue SDNoFPClass = DAG.getTargetConstant(
12528 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12529 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12530 OutVal, SDNoFPClass);
12531 }
12532 ArgValues.push_back(OutVal);
12533 }
12534
12535 i += NumParts;
12536 }
12537
12538 // We don't need to do anything else for unused arguments.
12539 if (ArgValues.empty())
12540 continue;
12541
12542 // Note down frame index.
12543 if (FrameIndexSDNode *FI =
12544 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12545 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12546
12547 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12548 SDB->getCurSDLoc());
12549
12550 SDB->setValue(&Arg, Res);
12551 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12552 // We want to associate the argument with the frame index, among
12553 // involved operands, that correspond to the lowest address. The
12554 // getCopyFromParts function, called earlier, is swapping the order of
12555 // the operands to BUILD_PAIR depending on endianness. The result of
12556 // that swapping is that the least significant bits of the argument will
12557 // be in the first operand of the BUILD_PAIR node, and the most
12558 // significant bits will be in the second operand.
12559 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12560 if (LoadSDNode *LNode =
12561 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12562 if (FrameIndexSDNode *FI =
12563 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12564 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12565 }
12566
12567 // Analyses past this point are naive and don't expect an assertion.
12568 if (Res.getOpcode() == ISD::AssertZext)
12569 Res = Res.getOperand(0);
12570
12571 // Update the SwiftErrorVRegDefMap.
12572 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12573 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12574 if (Reg.isVirtual())
12575 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12576 Reg);
12577 }
12578
12579 // If this argument is live outside of the entry block, insert a copy from
12580 // wherever we got it to the vreg that other BB's will reference it as.
12581 if (Res.getOpcode() == ISD::CopyFromReg) {
12582 // If we can, though, try to skip creating an unnecessary vreg.
12583 // FIXME: This isn't very clean... it would be nice to make this more
12584 // general.
12585 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12586 if (Reg.isVirtual()) {
12587 FuncInfo->ValueMap[&Arg] = Reg;
12588 continue;
12589 }
12590 }
12591 if (!isOnlyUsedInEntryBlock(&Arg, FastISel)) {
12592 FuncInfo->InitializeRegForValue(&Arg);
12593 SDB->CopyToExportRegsIfNeeded(&Arg);
12594 }
12595 }
12596
12597 if (!Chains.empty()) {
12598 Chains.push_back(NewRoot);
12599 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12600 }
12601
12602 DAG.setRoot(NewRoot);
12603
12604 assert(i == InVals.size() && "Argument register count mismatch!");
12605
12606 // If any argument copy elisions occurred and we have debug info, update the
12607 // stale frame indices used in the dbg.declare variable info table.
12608 if (!ArgCopyElisionFrameIndexMap.empty()) {
12609 for (MachineFunction::VariableDbgInfo &VI :
12610 MF->getInStackSlotVariableDbgInfo()) {
12611 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12612 if (I != ArgCopyElisionFrameIndexMap.end())
12613 VI.updateStackSlot(I->second);
12614 }
12615 }
12616
12617 // Finally, if the target has anything special to do, allow it to do so.
12619}
12620
12621/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12622/// ensure constants are generated when needed. Remember the virtual registers
12623/// that need to be added to the Machine PHI nodes as input. We cannot just
12624/// directly add them, because expansion might result in multiple MBB's for one
12625/// BB. As such, the start of the BB might correspond to a different MBB than
12626/// the end.
12627void
12628SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12630
12631 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12632
12633 // Check PHI nodes in successors that expect a value to be available from this
12634 // block.
12635 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12636 if (!isa<PHINode>(SuccBB->begin())) continue;
12637 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12638
12639 // If this terminator has multiple identical successors (common for
12640 // switches), only handle each succ once.
12641 if (!SuccsHandled.insert(SuccMBB).second)
12642 continue;
12643
12645
12646 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12647 // nodes and Machine PHI nodes, but the incoming operands have not been
12648 // emitted yet.
12649 for (const PHINode &PN : SuccBB->phis()) {
12650 // Ignore dead phi's.
12651 if (PN.use_empty())
12652 continue;
12653
12654 // Skip empty types
12655 if (PN.getType()->isEmptyTy())
12656 continue;
12657
12658 Register Reg;
12659 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12660
12661 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12662 Register &RegOut = ConstantsOut[C];
12663 if (!RegOut) {
12664 RegOut = FuncInfo.CreateRegs(PHIOp);
12665 // We need to zero/sign extend ConstantInt phi operands to match
12666 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12667 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12668 if (auto *CI = dyn_cast<ConstantInt>(C))
12669 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12671 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12672 }
12673 Reg = RegOut;
12674 } else {
12675 auto I = FuncInfo.ValueMap.find(PHIOp);
12676 if (I != FuncInfo.ValueMap.end())
12677 Reg = I->second;
12678 else {
12679 assert(isa<AllocaInst>(PHIOp) &&
12680 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12681 "Didn't codegen value into a register!??");
12682 Reg = FuncInfo.CreateRegs(PHIOp);
12684 }
12685 }
12686
12687 // Remember that this register needs to added to the machine PHI node as
12688 // the input for this MBB.
12689 SmallVector<EVT, 4> ValueVTs;
12690 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12691 for (EVT VT : ValueVTs) {
12692 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12693 for (unsigned i = 0; i != NumRegisters; ++i)
12694 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12695 Reg += NumRegisters;
12696 }
12697 }
12698 }
12699
12700 ConstantsOut.clear();
12701}
12702
12703MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12705 if (++I == FuncInfo.MF->end())
12706 return nullptr;
12707 return &*I;
12708}
12709
12710/// During lowering new call nodes can be created (such as memset, etc.).
12711/// Those will become new roots of the current DAG, but complications arise
12712/// when they are tail calls. In such cases, the call lowering will update
12713/// the root, but the builder still needs to know that a tail call has been
12714/// lowered in order to avoid generating an additional return.
12715void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12716 // If the node is null, we do have a tail call.
12717 if (MaybeTC.getNode() != nullptr)
12718 DAG.setRoot(MaybeTC);
12719 else
12720 HasTailCall = true;
12721}
12722
12723void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12724 MachineBasicBlock *SwitchMBB,
12725 MachineBasicBlock *DefaultMBB) {
12726 MachineFunction *CurMF = FuncInfo.MF;
12727 MachineBasicBlock *NextMBB = nullptr;
12729 if (++BBI != FuncInfo.MF->end())
12730 NextMBB = &*BBI;
12731
12732 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12733
12734 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12735
12736 if (Size == 2 && W.MBB == SwitchMBB) {
12737 // If any two of the cases has the same destination, and if one value
12738 // is the same as the other, but has one bit unset that the other has set,
12739 // use bit manipulation to do two compares at once. For example:
12740 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12741 // TODO: This could be extended to merge any 2 cases in switches with 3
12742 // cases.
12743 // TODO: Handle cases where W.CaseBB != SwitchBB.
12744 CaseCluster &Small = *W.FirstCluster;
12745 CaseCluster &Big = *W.LastCluster;
12746
12747 if (Small.Low == Small.High && Big.Low == Big.High &&
12748 Small.MBB == Big.MBB) {
12749 const APInt &SmallValue = Small.Low->getValue();
12750 const APInt &BigValue = Big.Low->getValue();
12751
12752 // Check that there is only one bit different.
12753 APInt CommonBit = BigValue ^ SmallValue;
12754 if (CommonBit.isPowerOf2()) {
12755 SDValue CondLHS = getValue(Cond);
12756 EVT VT = CondLHS.getValueType();
12757 SDLoc DL = getCurSDLoc();
12758
12759 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12760 DAG.getConstant(CommonBit, DL, VT));
12761 SDValue Cond = DAG.getSetCC(
12762 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12763 ISD::SETEQ);
12764
12765 // Update successor info.
12766 // Both Small and Big will jump to Small.BB, so we sum up the
12767 // probabilities.
12768 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12769 if (BPI)
12770 addSuccessorWithProb(
12771 SwitchMBB, DefaultMBB,
12772 // The default destination is the first successor in IR.
12773 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12774 else
12775 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12776
12777 // Insert the true branch.
12778 SDValue BrCond =
12779 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12780 DAG.getBasicBlock(Small.MBB));
12781 // Insert the false branch.
12782 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12783 DAG.getBasicBlock(DefaultMBB));
12784
12785 DAG.setRoot(BrCond);
12786 return;
12787 }
12788 }
12789 }
12790
12791 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12792 // Here, we order cases by probability so the most likely case will be
12793 // checked first. However, two clusters can have the same probability in
12794 // which case their relative ordering is non-deterministic. So we use Low
12795 // as a tie-breaker as clusters are guaranteed to never overlap.
12796 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12797 [](const CaseCluster &a, const CaseCluster &b) {
12798 return a.Prob != b.Prob ?
12799 a.Prob > b.Prob :
12800 a.Low->getValue().slt(b.Low->getValue());
12801 });
12802
12803 // Rearrange the case blocks so that the last one falls through if possible
12804 // without changing the order of probabilities.
12805 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12806 --I;
12807 if (I->Prob > W.LastCluster->Prob)
12808 break;
12809 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12810 std::swap(*I, *W.LastCluster);
12811 break;
12812 }
12813 }
12814 }
12815
12816 // Compute total probability.
12817 BranchProbability DefaultProb = W.DefaultProb;
12818 BranchProbability UnhandledProbs = DefaultProb;
12819 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12820 UnhandledProbs += I->Prob;
12821
12822 MachineBasicBlock *CurMBB = W.MBB;
12823 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12824 bool FallthroughUnreachable = false;
12825 MachineBasicBlock *Fallthrough;
12826 if (I == W.LastCluster) {
12827 // For the last cluster, fall through to the default destination.
12828 Fallthrough = DefaultMBB;
12829 FallthroughUnreachable =
12831 } else {
12832 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12833 CurMF->insert(BBI, Fallthrough);
12834 // Put Cond in a virtual register to make it available from the new blocks.
12836 }
12837 UnhandledProbs -= I->Prob;
12838
12839 switch (I->Kind) {
12840 case CC_JumpTable: {
12841 // FIXME: Optimize away range check based on pivot comparisons.
12842 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12843 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12844
12845 // The jump block hasn't been inserted yet; insert it here.
12846 MachineBasicBlock *JumpMBB = JT->MBB;
12847 CurMF->insert(BBI, JumpMBB);
12848
12849 auto JumpProb = I->Prob;
12850 auto FallthroughProb = UnhandledProbs;
12851
12852 // If the default statement is a target of the jump table, we evenly
12853 // distribute the default probability to successors of CurMBB. Also
12854 // update the probability on the edge from JumpMBB to Fallthrough.
12855 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12856 SE = JumpMBB->succ_end();
12857 SI != SE; ++SI) {
12858 if (*SI == DefaultMBB) {
12859 JumpProb += DefaultProb / 2;
12860 FallthroughProb -= DefaultProb / 2;
12861 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12862 JumpMBB->normalizeSuccProbs();
12863 break;
12864 }
12865 }
12866
12867 // If the default clause is unreachable, propagate that knowledge into
12868 // JTH->FallthroughUnreachable which will use it to suppress the range
12869 // check.
12870 //
12871 // However, don't do this if we're doing branch target enforcement
12872 // (e.g. Arm BTI, or the cf-protection-branch module flag used by
12873 // RISC-V Zicfilp and X86 IBT), because a table branch _without_ a
12874 // range check can be a tempting JOP gadget - out-of-bounds inputs
12875 // that are impossible in correct execution become possible again if
12876 // an attacker can influence the control flow. So if an attacker
12877 // doesn't already have a branch target enforcement bypass available,
12878 // we don't want them to be able to get one out of this table branch.
12879 if (FallthroughUnreachable) {
12880 Function &CurFunc = CurMF->getFunction();
12881 bool HasCFBranch = false;
12882 if (auto *CFBranch = mdconst::extract_or_null<ConstantInt>(
12883 CurFunc.getParent()->getModuleFlag("cf-protection-branch")))
12884 HasCFBranch = !CFBranch->isZero();
12885 if (!HasCFBranch &&
12886 !CurFunc.hasFnAttribute("branch-target-enforcement"))
12887 JTH->FallthroughUnreachable = true;
12888 }
12889
12890 if (!JTH->FallthroughUnreachable)
12891 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12892 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12893 CurMBB->normalizeSuccProbs();
12894
12895 // The jump table header will be inserted in our current block, do the
12896 // range check, and fall through to our fallthrough block.
12897 JTH->HeaderBB = CurMBB;
12898 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12899
12900 // If we're in the right place, emit the jump table header right now.
12901 if (CurMBB == SwitchMBB) {
12902 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12903 JTH->Emitted = true;
12904 }
12905 break;
12906 }
12907 case CC_BitTests: {
12908 // FIXME: Optimize away range check based on pivot comparisons.
12909 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12910
12911 // The bit test blocks haven't been inserted yet; insert them here.
12912 for (BitTestCase &BTC : BTB->Cases)
12913 CurMF->insert(BBI, BTC.ThisBB);
12914
12915 // Fill in fields of the BitTestBlock.
12916 BTB->Parent = CurMBB;
12917 BTB->Default = Fallthrough;
12918
12919 BTB->DefaultProb = UnhandledProbs;
12920 // If the cases in bit test don't form a contiguous range, we evenly
12921 // distribute the probability on the edge to Fallthrough to two
12922 // successors of CurMBB.
12923 if (!BTB->ContiguousRange) {
12924 BTB->Prob += DefaultProb / 2;
12925 BTB->DefaultProb -= DefaultProb / 2;
12926 }
12927
12928 if (FallthroughUnreachable)
12929 BTB->FallthroughUnreachable = true;
12930
12931 // If we're in the right place, emit the bit test header right now.
12932 if (CurMBB == SwitchMBB) {
12933 visitBitTestHeader(*BTB, SwitchMBB);
12934 BTB->Emitted = true;
12935 }
12936 break;
12937 }
12938 case CC_Range: {
12939 const Value *RHS, *LHS, *MHS;
12941 if (I->Low == I->High) {
12942 // Check Cond == I->Low.
12943 CC = ISD::SETEQ;
12944 LHS = Cond;
12945 RHS=I->Low;
12946 MHS = nullptr;
12947 } else {
12948 // Check I->Low <= Cond <= I->High.
12949 CC = ISD::SETLE;
12950 LHS = I->Low;
12951 MHS = Cond;
12952 RHS = I->High;
12953 }
12954
12955 // If Fallthrough is unreachable, fold away the comparison.
12956 if (FallthroughUnreachable)
12957 CC = ISD::SETTRUE;
12958
12959 // The false probability is the sum of all unhandled cases.
12960 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12961 getCurSDLoc(), I->Prob, UnhandledProbs);
12962
12963 if (CurMBB == SwitchMBB)
12964 visitSwitchCase(CB, SwitchMBB);
12965 else
12966 SL->SwitchCases.push_back(CB);
12967
12968 break;
12969 }
12970 }
12971 CurMBB = Fallthrough;
12972 }
12973}
12974
12975void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12976 const SwitchWorkListItem &W,
12977 Value *Cond,
12978 MachineBasicBlock *SwitchMBB) {
12979 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12980 "Clusters not sorted?");
12981 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12982
12983 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12984 SL->computeSplitWorkItemInfo(W);
12985
12986 // Use the first element on the right as pivot since we will make less-than
12987 // comparisons against it.
12988 CaseClusterIt PivotCluster = FirstRight;
12989 assert(PivotCluster > W.FirstCluster);
12990 assert(PivotCluster <= W.LastCluster);
12991
12992 CaseClusterIt FirstLeft = W.FirstCluster;
12993 CaseClusterIt LastRight = W.LastCluster;
12994
12995 const ConstantInt *Pivot = PivotCluster->Low;
12996
12997 // New blocks will be inserted immediately after the current one.
12999 ++BBI;
13000
13001 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
13002 // we can branch to its destination directly if it's squeezed exactly in
13003 // between the known lower bound and Pivot - 1.
13004 MachineBasicBlock *LeftMBB;
13005 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
13006 FirstLeft->Low == W.GE &&
13007 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
13008 LeftMBB = FirstLeft->MBB;
13009 } else {
13010 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
13011 FuncInfo.MF->insert(BBI, LeftMBB);
13012 WorkList.push_back(
13013 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
13014 // Put Cond in a virtual register to make it available from the new blocks.
13016 }
13017
13018 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
13019 // single cluster, RHS.Low == Pivot, and we can branch to its destination
13020 // directly if RHS.High equals the current upper bound.
13021 MachineBasicBlock *RightMBB;
13022 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
13023 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
13024 RightMBB = FirstRight->MBB;
13025 } else {
13026 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
13027 FuncInfo.MF->insert(BBI, RightMBB);
13028 WorkList.push_back(
13029 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
13030 // Put Cond in a virtual register to make it available from the new blocks.
13032 }
13033
13034 // Create the CaseBlock record that will be used to lower the branch.
13035 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
13036 getCurSDLoc(), LeftProb, RightProb);
13037
13038 if (W.MBB == SwitchMBB)
13039 visitSwitchCase(CB, SwitchMBB);
13040 else
13041 SL->SwitchCases.push_back(CB);
13042}
13043
13044// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
13045// from the swith statement.
13047 BranchProbability PeeledCaseProb) {
13048 if (PeeledCaseProb == BranchProbability::getOne())
13050 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
13051
13052 uint32_t Numerator = CaseProb.getNumerator();
13053 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
13054 return BranchProbability(Numerator, std::max(Numerator, Denominator));
13055}
13056
13057// Try to peel the top probability case if it exceeds the threshold.
13058// Return current MachineBasicBlock for the switch statement if the peeling
13059// does not occur.
13060// If the peeling is performed, return the newly created MachineBasicBlock
13061// for the peeled switch statement. Also update Clusters to remove the peeled
13062// case. PeeledCaseProb is the BranchProbability for the peeled case.
13063MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
13064 const SwitchInst &SI, CaseClusterVector &Clusters,
13065 BranchProbability &PeeledCaseProb) {
13066 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13067 // Don't perform if there is only one cluster or optimizing for size.
13068 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
13069 TM.getOptLevel() == CodeGenOptLevel::None ||
13070 SwitchMBB->getParent()->getFunction().hasMinSize())
13071 return SwitchMBB;
13072
13073 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
13074 unsigned PeeledCaseIndex = 0;
13075 bool SwitchPeeled = false;
13076 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
13077 CaseCluster &CC = Clusters[Index];
13078 if (CC.Prob < TopCaseProb)
13079 continue;
13080 TopCaseProb = CC.Prob;
13081 PeeledCaseIndex = Index;
13082 SwitchPeeled = true;
13083 }
13084 if (!SwitchPeeled)
13085 return SwitchMBB;
13086
13087 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
13088 << TopCaseProb << "\n");
13089
13090 // Record the MBB for the peeled switch statement.
13091 MachineFunction::iterator BBI(SwitchMBB);
13092 ++BBI;
13093 MachineBasicBlock *PeeledSwitchMBB =
13094 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
13095 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
13096
13097 ExportFromCurrentBlock(SI.getCondition());
13098 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
13099 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
13100 nullptr, nullptr, TopCaseProb.getCompl()};
13101 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
13102
13103 Clusters.erase(PeeledCaseIt);
13104 for (CaseCluster &CC : Clusters) {
13105 LLVM_DEBUG(
13106 dbgs() << "Scale the probablity for one cluster, before scaling: "
13107 << CC.Prob << "\n");
13108 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
13109 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
13110 }
13111 PeeledCaseProb = TopCaseProb;
13112 return PeeledSwitchMBB;
13113}
13114
13115void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
13116 // Extract cases from the switch.
13117 BranchProbabilityInfo *BPI = FuncInfo.BPI;
13118 CaseClusterVector Clusters;
13119 Clusters.reserve(SI.getNumCases());
13120 for (auto I : SI.cases()) {
13121 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
13122 const ConstantInt *CaseVal = I.getCaseValue();
13123 BranchProbability Prob =
13124 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
13125 : BranchProbability(1, SI.getNumCases() + 1);
13126 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
13127 }
13128
13129 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
13130
13131 // Cluster adjacent cases with the same destination. We do this at all
13132 // optimization levels because it's cheap to do and will make codegen faster
13133 // if there are many clusters.
13134 sortAndRangeify(Clusters);
13135
13136 // The branch probablity of the peeled case.
13137 BranchProbability PeeledCaseProb = BranchProbability::getZero();
13138 MachineBasicBlock *PeeledSwitchMBB =
13139 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
13140
13141 // If there is only the default destination, jump there directly.
13142 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13143 if (Clusters.empty()) {
13144 assert(PeeledSwitchMBB == SwitchMBB);
13145 SwitchMBB->addSuccessor(DefaultMBB);
13146 if (DefaultMBB != NextBlock(SwitchMBB)) {
13147 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
13148 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
13149 }
13150 return;
13151 }
13152
13153 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
13154 DAG.getBFI());
13155 SL->findBitTestClusters(Clusters, &SI);
13156
13157 LLVM_DEBUG({
13158 dbgs() << "Case clusters: ";
13159 for (const CaseCluster &C : Clusters) {
13160 if (C.Kind == CC_JumpTable)
13161 dbgs() << "JT:";
13162 if (C.Kind == CC_BitTests)
13163 dbgs() << "BT:";
13164
13165 C.Low->getValue().print(dbgs(), true);
13166 if (C.Low != C.High) {
13167 dbgs() << '-';
13168 C.High->getValue().print(dbgs(), true);
13169 }
13170 dbgs() << ' ';
13171 }
13172 dbgs() << '\n';
13173 });
13174
13175 assert(!Clusters.empty());
13176 SwitchWorkList WorkList;
13177 CaseClusterIt First = Clusters.begin();
13178 CaseClusterIt Last = Clusters.end() - 1;
13179 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
13180 // Scale the branchprobability for DefaultMBB if the peel occurs and
13181 // DefaultMBB is not replaced.
13182 if (PeeledCaseProb != BranchProbability::getZero() &&
13183 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
13184 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
13185 WorkList.push_back(
13186 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
13187
13188 while (!WorkList.empty()) {
13189 SwitchWorkListItem W = WorkList.pop_back_val();
13190 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
13191
13192 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
13193 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
13194 // For optimized builds, lower large range as a balanced binary tree.
13195 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
13196 continue;
13197 }
13198
13199 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
13200 }
13201}
13202
13203void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
13204 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13205 auto DL = getCurSDLoc();
13206 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13207 setValue(&I, DAG.getStepVector(DL, ResultVT));
13208}
13209
13210void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
13211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13212 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13213
13214 SDLoc DL = getCurSDLoc();
13215 SDValue V = getValue(I.getOperand(0));
13216 assert(VT == V.getValueType() && "Malformed vector.reverse!");
13217
13218 if (VT.isScalableVector()) {
13219 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
13220 return;
13221 }
13222
13223 // Use VECTOR_SHUFFLE for the fixed-length vector
13224 // to maintain existing behavior.
13225 SmallVector<int, 8> Mask;
13226 unsigned NumElts = VT.getVectorMinNumElements();
13227 for (unsigned i = 0; i != NumElts; ++i)
13228 Mask.push_back(NumElts - 1 - i);
13229
13230 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
13231}
13232
13233void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
13234 unsigned Factor) {
13235 auto DL = getCurSDLoc();
13236 SDValue InVec = getValue(I.getOperand(0));
13237
13238 SmallVector<EVT, 4> ValueVTs;
13239 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13240 ValueVTs);
13241
13242 EVT OutVT = ValueVTs[0];
13243 unsigned OutNumElts = OutVT.getVectorMinNumElements();
13244
13245 SmallVector<SDValue, 4> SubVecs(Factor);
13246 for (unsigned i = 0; i != Factor; ++i) {
13247 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13248 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
13249 DAG.getVectorIdxConstant(OutNumElts * i, DL));
13250 }
13251
13252 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
13253 DAG.getVTList(ValueVTs), SubVecs);
13254 setValue(&I, Res);
13255}
13256
13257void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13258 unsigned Factor) {
13259 auto DL = getCurSDLoc();
13260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13261 EVT InVT = getValue(I.getOperand(0)).getValueType();
13262 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13263
13264 SmallVector<SDValue, 8> InVecs(Factor);
13265 for (unsigned i = 0; i < Factor; ++i) {
13266 InVecs[i] = getValue(I.getOperand(i));
13267 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13268 "Expected VTs to be the same");
13269 }
13270
13271 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13272 SDValue Res =
13273 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13274
13276 for (unsigned i = 0; i < Factor; ++i)
13277 Results[i] = Res.getValue(i);
13278
13279 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13280 setValue(&I, Res);
13281}
13282
13283void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13284 SmallVector<EVT, 4> ValueVTs;
13285 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13286 ValueVTs);
13287 unsigned NumValues = ValueVTs.size();
13288 if (NumValues == 0) return;
13289
13291 SDValue Op = getValue(I.getOperand(0));
13292
13293 for (unsigned i = 0; i != NumValues; ++i)
13294 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13295 SDValue(Op.getNode(), Op.getResNo() + i));
13296
13298 DAG.getVTList(ValueVTs), Values));
13299}
13300
13301void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13302 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13303 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13304
13305 SDLoc DL = getCurSDLoc();
13306 SDValue V1 = getValue(I.getOperand(0));
13307 SDValue V2 = getValue(I.getOperand(1));
13308 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13309
13310 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13311 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13312 SDValue Offset = DAG.getZExtOrTrunc(
13313 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13314 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13316 DL, VT, V1, V2, Offset));
13317 return;
13318 }
13319 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13320
13321 unsigned NumElts = VT.getVectorNumElements();
13322
13323 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13324
13325 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13326 SmallVector<int, 8> Mask;
13327 for (unsigned i = 0; i < NumElts; ++i)
13328 Mask.push_back(Idx + i);
13329 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13330}
13331
13332// Read the outputs again from the registers that the INLINEASM_BR defines them
13333// in, as visitInlineAsm() did, rather than with the simpler
13334// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13335// otherwise we will end up with copies of virtregs only valid along direct
13336// edges.
13337void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13338 const auto *CBR =
13339 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13340 auto It = CallBrOutputs.find(CBR);
13341 assert(It != CallBrOutputs.end() && "callbr asm wasn't lowered");
13342
13343 SDValue Chain = DAG.getRoot();
13344 SmallVector<SDValue, 8> OutputValues;
13345 for (const CallBrOutput &Output : It->second) {
13346 RegsForValue Regs(Output.Regs, Output.RegVT, Output.ValueVT);
13347 for (Register Reg : Regs.Regs)
13348 if (Reg.isPhysical() && !FuncInfo.MBB->isLiveIn(Reg))
13349 FuncInfo.MBB->addLiveIn(Reg);
13350
13351 SDValue Glue;
13352 OutputValues.push_back(getInlineAsmOutput(
13353 Output.OpInfo, Regs, *CBR, Chain, Glue, getCurSDLoc(), FuncInfo, DAG));
13354 }
13355
13356 setValue(&I, getInlineAsmResult(*CBR, OutputValues, getCurSDLoc(), DAG));
13357}
unsigned NumParts
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
bool IsScalable
const TargetLowering & TLI
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
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 & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI)
Returns an AttributeList representing the attributes applied to the return value of the given call.
Definition FastISel.cpp:947
#define Check(C,...)
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static void getRegistersForValue(MachineFunction &MF, MachineIRBuilder &MIRBuilder, GISelAsmOperandInfo &OpInfo, GISelAsmOperandInfo &RefOpInfo)
Assign virtual/physical registers for the specified register operand.
static void computeConstraintToUse(const TargetLowering *TLI, TargetLowering::AsmOperandInfo &OpInfo)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
return Result
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const MachineInstr &MI)
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file provides utility analysis objects describing memory locations.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
#define T
#define T1
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
This file contains the declarations for profiling metadata utility functions.
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file contains some templates that are useful if you are working with the STL at all.
static bool hasOnlySelectUsers(const Value *Cond)
static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, SDValue &Chain)
Create a LOAD_STACK_GUARD node, and let it carry the target specific global variable if there exists ...
static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, SDValue &Scale, SelectionDAGBuilder *SDB, const BasicBlock *CurBB, uint64_t ElemSize)
static void failForInvalidBundles(const CallBase &I, StringRef Name, ArrayRef< uint32_t > AllowedBundles)
static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, const SDLoc &DL, SmallVectorImpl< SDValue > &Ops, SelectionDAGBuilder &Builder)
Add a stack map intrinsic call's live variable operands to a stackmap or patchpoint target node's ope...
static const unsigned MaxParallelChains
static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
visitPow - Lower a pow intrinsic.
static const CallBase * FindPreallocatedCall(const Value *PreallocatedSetup)
Given a @llvm.call.preallocated.setup, return the corresponding preallocated call.
static cl::opt< unsigned > SwitchPeelThreshold("switch-peel-threshold", cl::Hidden, cl::init(66), cl::desc("Set the case probability threshold for peeling the case from a " "switch statement. A value greater than 100 will void this " "optimization"))
static cl::opt< bool > InsertAssertAlign("insert-assert-align", cl::init(true), cl::desc("Insert the experimental `assertalign` node."), cl::ReallyHidden)
static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin)
static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, DILocalVariable *Variable, DebugLoc DL, unsigned Order, SmallVectorImpl< Value * > &Values, DIExpression *Expression)
static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info, const CallBase &Call, SelectionDAGBuilder &Builder, const TargetLowering &TLI, SelectionDAG &DAG)
Prepare DAG-level operands.
static unsigned findMatchingInlineAsmOperand(unsigned OperandNo, const std::vector< SDValue > &AsmNodeOperands)
static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, SDISelAsmOperandInfo &MatchingOpInfo, SelectionDAG &DAG)
Make sure that the output operand OpInfo and its corresponding input operand MatchingOpInfo have comp...
static void findUnwindDestinations(FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, BranchProbability Prob, SmallVectorImpl< std::pair< MachineBasicBlock *, BranchProbability > > &UnwindDests)
When an invoke or a cleanupret unwinds to the next EH pad, there are many places it could ultimately ...
static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic)
static BranchProbability scaleCaseProbality(BranchProbability CaseProb, BranchProbability PeeledCaseProb)
static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandExp2 - Lower an exp2 intrinsic.
static void getUnderlyingArgRegs(SmallVectorImpl< std::pair< Register, TypeSize > > &Regs, const SDValue &N, const DataLayout &DL)
static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue Scale, SelectionDAG &DAG, const TargetLowering &TLI)
static const GlobalValue * getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx, const MachineFunction &MF)
If V is the address of a describable global, possibly displaced by a constant, return the global and ...
static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, const SDLoc &dl)
getF32Constant - Get 32-bit floating point constant.
static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, const SDLoc &DL, EVT PartVT)
static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog10 - Lower a log10 intrinsic.
DenseMap< const Argument *, std::pair< const AllocaInst *, const StoreInst * > > ArgCopyElisionMapTy
static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, const Value *V, std::optional< CallingConv::ID > CallConv)
getCopyToPartsVector - Create a series of nodes that contain the specified value split into legal par...
static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, const Value *V, std::optional< CallingConv::ID > CallConv=std::nullopt, ISD::NodeType ExtendKind=ISD::ANY_EXTEND)
getCopyToParts - Create a series of nodes that contain the specified value split into legal parts.
static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, SelectionDAGBuilder &Builder)
static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog2 - Lower a log2 intrinsic.
static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, SDISelAsmOperandInfo &OpInfo, SelectionDAG &DAG)
Get a direct memory input to behave well as an indirect operand.
static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel)
isOnlyUsedInEntryBlock - If the specified argument is only used in the entry block,...
static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, const Twine &ErrMsg)
static SDValue getInlineAsmResult(const CallBase &Call, ArrayRef< SDValue > Outputs, const SDLoc &DL, SelectionDAG &DAG)
Return the result of inline asm call Call from Outputs, the values of its direct outputs in order,...
static bool collectInstructionDeps(SmallMapVector< const Instruction *, bool, 8 > *Deps, const Value *V, SmallMapVector< const Instruction *, bool, 8 > *Necessary=nullptr, unsigned Depth=0)
static void findArgumentCopyElisionCandidates(const DataLayout &DL, FunctionLoweringInfo *FuncInfo, ArgCopyElisionMapTy &ArgCopyElisionCandidates)
Scan the entry block of the function in FuncInfo for arguments that look like copies into a local all...
static bool isFunction(SDValue Op)
static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, const SDLoc &dl)
GetExponent - Get the exponent:
static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, SelectionDAG &DAG)
ExpandPowI - Expand a llvm.powi intrinsic.
static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog - Lower a log intrinsic.
static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, SDValue InChain, std::optional< CallingConv::ID > CC=std::nullopt, std::optional< ISD::NodeType > AssertOp=std::nullopt)
getCopyFromParts - Create a value that contains the specified legal parts combined into the value the...
static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, SelectionDAG &DAG)
static bool determineConstraints(ConstraintDecisionInfo &Info, TargetLowering::AsmOperandInfoVector &TargetConstraints, const CallBase &Call, SelectionDAGBuilder &Builder, const TargetLowering &TLI, const TargetMachine &TM, SelectionDAG &DAG, const BasicBlock *EHPadBB)
DetermineConstraints - Find the constraints to use for inline asm operands.
static bool constructOperandInfo(ConstraintDecisionInfo &Info, TargetLowering::AsmOperandInfoVector &TargetConstraints, SelectionDAGBuilder &Builder, const TargetLowering &TLI, ExtraFlags &ExtraInfo)
Construct operand info objects.
static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl)
GetSignificand - Get the significand and build it into a floating-point number with exponent of 1:
static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandExp - Lower an exp intrinsic.
static const MDNode * getRangeMetadata(const Instruction &I)
static cl::opt< unsigned, true > LimitFPPrecision("limit-float-precision", cl::desc("Generate low-precision inline sequences " "for some float libcalls"), cl::location(LimitFloatPrecision), cl::Hidden, cl::init(0))
static SDValue getInlineAsmOutput(const TargetLowering::AsmOperandInfo &OpInfo, const RegsForValue &Regs, const CallBase &Call, SDValue &Chain, SDValue &Glue, const SDLoc &DL, FunctionLoweringInfo &FuncInfo, SelectionDAG &DAG)
Read output operand OpInfo of inline asm call Call from Regs, the registers that the asm defines it i...
static void tryToElideArgumentCopy(FunctionLoweringInfo &FuncInfo, SmallVectorImpl< SDValue > &Chains, DenseMap< int, int > &ArgCopyElisionFrameIndexMap, SmallPtrSetImpl< const Instruction * > &ElidedArgCopyInstrs, ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, ArrayRef< SDValue > ArgVals, bool &ArgHasUses)
Try to elide argument copies from memory into a local alloca.
static void ensureMatchedVecRegParts(unsigned NumRegs, unsigned NumParts, MVT RegisterVT, MVT PartVT)
Emit a fatal error if the broken down registers don't match part type or count.
static unsigned LimitFloatPrecision
LimitFloatPrecision - Generate low-precision inline sequences for some float libcalls (6,...
static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, SDValue InChain, std::optional< CallingConv::ID > CC)
getCopyFromPartsVector - Create a value that contains the specified legal parts combined into the val...
static bool InBlock(const Value *V, const BasicBlock *BB)
static FPClassTest getNoFPClass(const Instruction &I)
static LLVM_ATTRIBUTE_ALWAYS_INLINE MVT::SimpleValueType getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex)
getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value, use GetVBR to decode it.
This file defines the SmallPtrSet class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
TTI::PartialReductionExtendKind ExtendKind
uint16_t RegSizeInBits(const MCRegisterInfo &MRI, MCRegister RegNo)
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:459
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6398
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:332
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:445
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:170
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
This class represents a no-op cast from one type to another.
The address of a basic block.
Definition Constants.h:1088
Analysis providing branch probability information.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
static constexpr BranchProbability getOne()
static uint32_t getDenominator()
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
LLVM_ABI uint64_t scale(uint64_t Num) const
Scale a large integer.
BranchProbability getCompl() const
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
CallingConv::ID getCallingConv() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Conditional Branch instruction.
Class for constant bytes.
Definition Constants.h:281
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
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 APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A signed pointer, in the ptrauth sense.
Definition Constants.h:1223
uint64_t getZExtValue() const
Constant Vector Declarations.
Definition Constants.h:674
This is an important base class in LLVM.
Definition Constant.h:44
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI const DIExpression * convertToUndefExpression(const DIExpression *Expr)
Removes all elements from Expr that do not apply to an undef debug value, which includes every operat...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
Base class for variables.
LLVM_ABI std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
bool isBigEndian() const
Definition DataLayout.h:220
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
A debug info location.
Definition DebugLoc.h:126
LLVM_ABI DILocation * getInlinedAt() const
Definition DebugLoc.cpp:58
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Diagnostic information for inline asm reporting.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
This instruction compares its operands according to the predicate given to the constructor.
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
An instruction for ordering other memory operations.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
BranchProbabilityInfo * BPI
MachineBasicBlock * getMBB(const BasicBlock *BB) const
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
const LiveOutInfo * GetLiveOutRegInfo(Register Reg)
GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the register is a PHI destinat...
MachineBasicBlock * MBB
MBB - The current block.
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
Data structure describing the variable locations in a function.
const BasicBlock & getEntryBlock() const
Definition Function.h:803
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition Function.h:247
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
Definition Function.cpp:743
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
Constant * getPersonalityFn() const
Get the personality function associated with this function.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
size_t arg_size() const
Definition Function.h:895
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Garbage collection metadata for a single function.
Definition GCMetadata.h:80
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void setMemConstraint(ConstraintCode C)
setMemConstraint - Augment an existing flag with the constraint code for a memory constraint.
Definition InlineAsm.h:433
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
iterator_range< user_iterator > users()
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
static LocationSize upperBound(uint64_t Value)
bool usesPerInvokeEHLabels(ExceptionHandling EH) const
Returns true if the exception tables reference the per-invoke EH labels emitted around invokes.
Definition MCAsmInfo.h:714
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
LLVM_ABI MCSymbol * getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen.
const MCAsmInfo & getAsmInfo() const
Definition MCContext.h:409
unsigned getID() const
getID() - Return the register class ID number.
bool isAllocatable() const
isAllocatable - Return true if this register class may be used to create virtual registers.
const MCPhysReg * iterator
iterator begin() const
begin/end - Return all of the registers in this class.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
iterator end() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
uint64_t getScalarSizeInBits() const
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.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
std::string getString() const
Return the value type as a string, e.g. i32.
ElementCount getVectorElementCount() const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
bool bitsGE(MVT VT) const
Return true if this has no less bits than VT.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
static MVT getVectorVT(MVT VT, unsigned NumElements)
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void setIsEHContTarget(bool V=true)
Indicates if this is a target of Windows EH Continuation Guard.
void setIsEHFuncletEntry(bool V=true)
Indicates if this is the entry block of an EH funclet.
MachineInstrBundleIterator< MachineInstr > iterator
void setIsEHScopeEntry(bool V=true)
Indicates if this is the entry block of an EH scope, i.e., the block that that used to have a catchpa...
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setIsImmutableObjectIndex(int ObjectIdx, bool IsImmutable)
Marks the immutability of an object.
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.
bool hasOpaqueSPAdjustment() const
Returns true if the function contains opaque dynamic stack adjustments.
int getStackProtectorIndex() const
Return the index for the stack protector object.
void setIsAliasedObjectIndex(int ObjectIdx, bool IsAliased)
Set "maybe pointed to by an LLVM IR value" for an object.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
void setFunctionContextIndex(int I)
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site)
Map the begin label for a call site.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD)
Record annotations associated with a particular label.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
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.
void setHasEHContTarget(bool V)
void addInvoke(MachineBasicBlock *LandingPad, MCSymbol *BeginLabel, MCSymbol *EndLabel)
Provide the begin and end labels of an invoke style call and associate it with a try landing pad bloc...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
An SDNode that represents everything that will be needed to construct a MachineInstr.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
bool contains(const KeyT &Key) const
Definition MapVector.h:149
static MemoryLocation getAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location after Ptr, while remaining within the underlying objec...
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:185
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:377
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Resume the propagation of an exception.
Return a value (possibly void), from a function.
Holds the information from a dbg_label node through SDISel.
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
static SDDbgOperand fromGlobalAddr(const GlobalValue *GV)
Holds the information from a dbg_value node through SDISel.
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.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
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.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
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.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) 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
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
bool shouldKeepJumpConditionsTogether(const FunctionLoweringInfo &FuncInfo, const CondBrInst &I, Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, TargetLoweringBase::CondMergingParams Params) const
DenseMap< const Constant *, Register > ConstantsOut
void addDanglingDebugInfo(SmallVectorImpl< Value * > &Values, DILocalVariable *Var, DIExpression *Expr, bool IsVariadic, DebugLoc DL, unsigned Order)
Register a dbg_value which relies on a Value which we have not yet seen.
void visitDbgInfo(const Instruction &I)
void clearDanglingDebugInfo()
Clear the dangling debug information map.
SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB, MCSymbol *&BeginLabel)
void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, bool IsMustTailCall, const BasicBlock *EHPadBB=nullptr, const TargetLowering::PtrAuthInfo *PAI=nullptr)
DenseMap< const CallBrInst *, SmallVector< CallBrOutput, 2 > > CallBrOutputs
The direct outputs, in order, of each callbr whose asm was lowered.
void clear()
Clear out the current SelectionDAG and the associated state and prepare this SelectionDAGBuilder obje...
void visitBitTestHeader(SwitchCG::BitTestBlock &B, MachineBasicBlock *SwitchBB)
visitBitTestHeader - This function emits necessary code to produce value suitable for "bit tests"
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
std::unique_ptr< SDAGSwitchLowering > SL
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
bool HasTailCall
This is set to true if a call in the current block has been translated as a tail call.
bool ShouldEmitAsBranches(const std::vector< SwitchCG::CaseBlock > &Cases)
If the set of cases should be emitted as a series of branches, return true.
void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
EmitBranchForMergedCondition - Helper method for FindMergedConditions.
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
SwiftErrorValueTracking & SwiftError
Information about the swifterror values used throughout the function.
SDValue getNonRegisterValue(const Value *V)
getNonRegisterValue - Return an SDValue for the given Value, but don't look in FuncInfo....
const TargetTransformInfo * TTI
DenseMap< MachineBasicBlock *, SmallVector< unsigned, 4 > > LPadToCallSiteMap
Map a landing pad to the call site indexes.
SDValue lowerNoFPClassToAssertNoFPClass(SelectionDAG &DAG, const Instruction &I, SDValue Op)
void handleDebugDeclare(Value *Address, DILocalVariable *Variable, DIExpression *Expression, DebugLoc DL)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void setValueToPoison(const Value *V, const SDLoc &dl)
void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, BranchProbability BranchProbToNext, Register Reg, SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB)
visitBitTestCase - this function produces one "bit test"
bool canTailCall(const CallBase &CB) const
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, AttributeSet RetAttrs, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
void CopyValueToVirtualRegister(const Value *V, Register Reg, ISD::NodeType ExtendType=ISD::ANY_EXTEND)
void salvageUnresolvedDbgValue(const Value *V, DanglingDebugInfo &DDI)
For the given dangling debuginfo record, perform last-ditch efforts to resolve the debuginfo to somet...
SmallVector< SDValue, 8 > PendingLoads
Loads are not emitted to the program immediately.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
void init(GCFunctionInfo *gfi, BatchAAResults *BatchAA, AssumptionCache *AC, const TargetLibraryInfo *li, const TargetTransformInfo &TTI)
SDValue getRoot()
Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) items.
void ExportFromCurrentBlock(const Value *V)
ExportFromCurrentBlock - If this condition isn't known to be exported from the current basic block,...
void resolveOrClearDbgInfo()
Evict any dangling debug information, attempting to salvage it first.
std::pair< SDValue, SDValue > lowerInvokable(TargetLowering::CallLoweringInfo &CLI, const BasicBlock *EHPadBB=nullptr)
SDValue getMemoryRoot()
Return the current virtual root of the Selection DAG, flushing any PendingLoad items.
void resolveDanglingDebugInfo(const Value *V, SDValue Val)
If we saw an earlier dbg_value referring to V, generate the debug data structures now that we've seen...
void visit(const Instruction &I)
void dropDanglingDebugInfo(const DILocalVariable *Variable, const DIExpression *Expr)
If we have dangling debug info that describes Variable, or an overlapping part of variable considerin...
SDValue getCopyFromRegs(const Value *V, Type *Ty)
If there was virtual register allocated for the value V emit CopyFromReg of the specified type Ty.
void CopyToExportRegsIfNeeded(const Value *V)
CopyToExportRegsIfNeeded - If the given value has virtual registers created for it,...
void handleKillDebugValue(DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order)
Create a record for a kill location debug intrinsic.
void visitJumpTable(SwitchCG::JumpTable &JT)
visitJumpTable - Emit JumpTable node in the current MBB
SDValue getFPOperationRoot(fp::ExceptionBehavior EB)
Return the current virtual root of the Selection DAG, flushing PendingConstrainedFP or PendingConstra...
void visitJumpTableHeader(SwitchCG::JumpTable &JT, SwitchCG::JumpTableHeader &JTH, MachineBasicBlock *SwitchBB)
visitJumpTableHeader - This function emits necessary code to produce index in the JumpTable from swit...
void LowerCallSiteWithPtrAuthBundle(const CallBase &CB, const BasicBlock *EHPadBB)
static const unsigned LowestSDNodeOrder
Lowest valid SDNodeOrder.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, Instruction::BinaryOps Opc, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
const TargetLibraryInfo * LibInfo
bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB)
void visitSPDescriptorParent(StackProtectorDescriptor &SPD, MachineBasicBlock *ParentBB)
Codegen a new tail for a stack protector check ParentMBB which has had its tail spliced into a stack ...
bool handleDebugValue(ArrayRef< const Value * > Values, DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order, bool IsVariadic)
For a given list of Values, attempt to create and record a SDDbgValue in the SelectionDAG.
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last)
When an MBB was split during scheduling, update the references that need to refer to the last resulti...
SDValue getValueImpl(const Value *V)
getValueImpl - Helper function for getValue and getNonRegisterValue.
void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB)
visitSwitchCase - Emits the necessary code to represent a single node in the binary search tree resul...
void visitSPDescriptorFailure(StackProtectorDescriptor &SPD)
Codegen the failure basic block for a stack protector check.
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
const TargetLowering * TLI
MachineRegisterInfo * RegInfo
std::unique_ptr< SwiftErrorValueTracking > SwiftError
virtual void emitFunctionEntryCode()
std::unique_ptr< SelectionDAGBuilder > SDB
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemccpy(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI) const
Emit target-specific code that performs a memccpy, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrnlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, SDValue MaxLength, MachinePointerInfo SrcPtrInfo) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, const CallInst *CI) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrstr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, const CallInst *CI) const
Emit target-specific code that performs a strstr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemchr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Src, SDValue Char, SDValue Length, MachinePointerInfo SrcPtrInfo) const
Emit target-specific code that performs a memchr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, MachinePointerInfo Op1PtrInfo, MachinePointerInfo Op2PtrInfo, const CallInst *CI) const
Emit target-specific code that performs a strcmp, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, SDValue Op3, const CallInst *CI) const
Emit target-specific code that performs a memcmp/bcmp, in cases where that is faster than a libcall.
virtual SDValue EmitTargetCodeForSetTag(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Addr, SDValue Size, MachinePointerInfo DstPtrInfo, bool ZeroData) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcpy(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Dest, SDValue Src, MachinePointerInfo DestPtrInfo, MachinePointerInfo SrcPtrInfo, bool isStpcpy, const CallInst *CI) const
Emit target-specific code that performs a strcpy or stpcpy, in cases where that is faster than a libc...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
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 MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
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 getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
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 getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
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 getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
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...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
MachineFunction & getMachineFunction() const
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...
LLVMContext * getContext() const
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void swap(SmallVectorImpl &RHS)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
MachineBasicBlock * getSuccessMBB()
MachineBasicBlock * getFailureMBB()
MachineBasicBlock * getParentMBB()
bool shouldEmitFunctionBasedCheckStackProtector() const
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Class to represent struct types.
Multiway switch.
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Provides information about what library functions are available for the current target.
virtual Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const
Returns the desired alignment for ByVal or InAlloca aggregate function arguments in the caller parame...
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
EVT getMemValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
virtual bool isAtomicAlignmentSupported(Align Alignment, uint64_t SizeInBytes) const
Return true if the target supports an atomic access of SizeInBytes bytes at the given Alignment.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
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...
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const
This callback is used to inspect load/store instructions and add target-specific MachineMemOperand fl...
virtual Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception typeid on entry to a la...
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
virtual bool useStackGuardMixFP() const
If this function returns true, stack protection checks should mix the frame pointer (or whichever poi...
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI, const DataLayout &DL, AssumptionCache *AC=nullptr, const TargetLibraryInfo *LibInfo=nullptr, CodeGenOptLevel OptLevel=CodeGenOptLevel::Default) const
virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const
Returns true if the index type for a masked gather/scatter requires extending.
MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI, const DataLayout &DL) const
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
virtual Align getABIAlignmentForCallingConv(Type *ArgTy, const DataLayout &DL) const
Certain targets have context sensitive alignment requirements, where one type has the alignment requi...
MachineMemOperand::Flags getVPIntrinsicMemOperandFlags(const VPIntrinsic &VPIntrin) const
virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const
Return true if the @llvm.get.active.lane.mask intrinsic should be expanded using generic code in Sele...
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
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 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.
virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const
virtual MVT getFenceOperandTy(const DataLayout &DL) const
Return the type for operands of fence.
virtual bool shouldExpandGetVectorLength(EVT CountVT, unsigned VF, bool IsScalable) const
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 MVT hasFastEqualityCompare(unsigned NumBits) const
Return the preferred operand type if the target has a quick way to compare integer values of the give...
MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI, const DataLayout &DL) const
virtual void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
virtual bool signExtendConstant(const ConstantInt *C) const
Return true if this constant should be sign extended when promoting to a larger type.
virtual Value * getSDagStackGuard(const Module &M, const LibcallLoweringInfo &Libcalls) const
Return the variable that's previously inserted by insertSSPDeclarations, if any, otherwise return nul...
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 ...
std::vector< ArgListEntry > ArgListTy
virtual Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
bool isBeneficialToExpandPowI(int64_t Exponent, bool OptForSize) const
Return true if it is beneficial to expand an @llvm.powi.
MVT getFrameIndexTy(const DataLayout &DL) const
Return the type for frame index, which is determined by the alloca address space specified through th...
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
virtual MVT getVPExplicitVectorLengthTy() const
Returns the type to be used for the EVL/AVL operand of VP nodes: ISD::VP_UDIV, ISD::VP_SDIV,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool supportSwiftError() const
Return true if the target supports swifterror attribute.
virtual SDValue visitMaskedLoad(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue &NewLoad, SDValue Ptr, SDValue PassThru, SDValue Mask) const
virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
virtual Register getRegisterByName(const char *RegName, LLT Ty, const MachineFunction &MF) const
Return the register ID of the name passed in.
std::vector< AsmOperandInfo > AsmOperandInfoVector
SDValue expandIS_FPCLASS(EVT ResultVT, SDValue Op, FPClassTest Test, SDNodeFlags Flags, const SDLoc &DL, SelectionDAG &DAG) const
Expand check for floating point class.
virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const
This callback is used to prepare for a volatile or atomic load.
virtual SDValue emitStackGuardMixFP(SelectionDAG &DAG, SDValue Val, const SDLoc &DL) const
virtual SDValue LowerCall(CallLoweringInfo &, SmallVectorImpl< SDValue > &) const
This hook must be implemented to lower calls into the specified DAG.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Glue, const SDLoc &DL, const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
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...
virtual bool functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv, bool isVarArg, const DataLayout &DL) const
For some targets, an LLVM struct type must be broken down into multiple simple types,...
virtual void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const
virtual SDValue visitMaskedStore(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, MachineMemOperand *MMO, SDValue Ptr, SDValue Val, SDValue Mask) const
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
SDValue annotateStackObjectPointer(SDValue Ptr, SelectionDAG &DAG, const SDLoc &DL, Align Alignment) const
Annotate a stack object pointer with known-bits assertions.
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
virtual bool CanLowerReturn(CallingConv::ID, MachineFunction &, bool, const SmallVectorImpl< ISD::OutputArg > &, LLVMContext &, const Type *RetTy) const
This hook should be implemented to check whether the return values described by the Outs array can fi...
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
CodeModel::Model getCodeModel() const
Returns the code model.
unsigned NoTrapAfterNoreturn
Do not emit a trap instruction for 'unreachable' IR instructions behind noreturn calls,...
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_Latency
The latency of instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:170
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Unconditional Branch instruction.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_iterator op_begin()
Definition User.h:259
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
This is the common base class for vector predication intrinsics.
static LLVM_ABI std::optional< unsigned > getVectorLengthParamPos(Intrinsic::ID IntrinsicID)
LLVM_ABI MaybeAlign getPointerAlignment() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
Base class of all SIMD vector types.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
const ParentTy * getParent() const
Definition ilist_node.h:34
A raw_ostream that writes to an std::string.
CallInst * Call
#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 char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ CONVERGENCECTRL_ANCHOR
The llvm.experimental.convergence.* intrinsics.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ SET_FPENV
Sets the current floating-point environment.
@ LOOP_DEPENDENCE_RAW_MASK
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ COND_LOOP
COND_LOOP is a conditional branch to self, used for implementing efficient conditional traps.
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ VECREDUCE_FMINIMUMNUM
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:129
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ RESET_FPENV
Set floating-point environment to default state.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ VECTOR_FIND_LAST_ACTIVE
Finds the index of the last active mask element Operands: Mask.
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:174
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ VECTOR_SHUFFLE_VAR
VECTOR_SHUFFLE_VAR(VEC, MASK) - Returns VEC permuted by MASK, an integer vector with the same number ...
Definition ISDOpcodes.h:665
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ RESET_FPMODE
Sets default dynamic floating-point control modes.
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ FPTRUNC_ROUND
FPTRUNC_ROUND - This corresponds to the fptrunc_round intrinsic.
Definition ISDOpcodes.h:520
@ FAKE_USE
FAKE_USE represents a use of the operand but does not do anything.
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:802
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ CONVERT_FROM_ARBITRARY_FP
CONVERT_FROM_ARBITRARY_FP - This operator converts from an arbitrary floating-point represented as an...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:158
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ SET_ROUNDING
Set rounding mode.
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ PREALLOCATED_SETUP
PREALLOCATED_SETUP - This has 2 operands: an input chain and a SRCVALUE with the preallocated call Va...
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ ADDROFRETURNADDR
ADDROFRETURNADDR - Represents the llvm.addressofreturnaddress intrinsic.
Definition ISDOpcodes.h:119
@ CONVERGENCECTRL_ENTRY
@ BR
Control flow instructions. These all have token chains.
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PARTIAL_REDUCE_FMLA
@ 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.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ PREALLOCATED_ARG
PREALLOCATED_ARG - This has 3 operands: an input chain, a SRCVALUE with the preallocated call Value,...
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ 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 ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ CLEANUPRET
CLEANUPRET - Represents a return from a cleanup block funclet.
@ GET_FPMODE
Reads the current dynamic floating-point control modes.
@ GET_FPENV
Gets the current floating-point environment.
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ PtrAuthGlobalAddress
A ptrauth constant.
Definition ISDOpcodes.h:102
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
@ LOCAL_RECOVER
LOCAL_RECOVER - Represents the llvm.localrecover intrinsic.
Definition ISDOpcodes.h:137
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ UBSANTRAP
UBSANTRAP - Trap with an immediate describing the kind of sanitizer failure.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:669
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ VECTOR_REVERSE
VECTOR_REVERSE(VECTOR) - Returns a vector, of the same type as VECTOR, whose elements are shuffled us...
Definition ISDOpcodes.h:650
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ PCMARKER
PCMARKER - This corresponds to the pcmarker intrinsic.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ RELOC_NONE
Issue a no-op relocation against a given symbol at the current location.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:759
@ VECTOR_MATCH
VECTOR_MATCH - this corresponds to the llvm.experimental.vector.match intrinsic.
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:673
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ STACKMAP
The llvm.experimental.stackmap intrinsic.
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:715
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:124
@ CLEAR_CACHE
llvm.clear_cache intrinsic Operands: Input Chain, Start Addres, End Address Outputs: Output Chain
@ CONVERGENCECTRL_LOOP
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:977
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ 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,...
@ CATCHRET
CATCHRET - Represents a return from a catch block funclet.
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:645
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:775
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
@ LOOP_DEPENDENCE_WAR_MASK
The llvm.loop.dependence.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_VScale()
Matches a call to llvm.vscale().
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
Offsets
Offsets in bytes from the start of the input buffer.
std::pair< JumpTableHeader, JumpTable > JumpTableBlock
LLVM_ABI void sortAndRangeify(CaseClusterVector &Clusters)
Sort Clusters and merge adjacent cases.
std::vector< CaseCluster > CaseClusterVector
@ CC_Range
A cluster of adjacent case labels with the same destination, or just one case.
@ CC_JumpTable
A cluster of cases suitable for jump table lowering.
@ CC_BitTests
A cluster of cases suitable for bit test lowering.
SmallVector< SwitchWorkListItem, 4 > SwitchWorkList
CaseClusterVector::iterator CaseClusterIt
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
ExceptionBehavior
Exception behavior used for floating point operations.
Definition FPEnv.h:39
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
@ ebMayTrap
This corresponds to "fpexcept.maytrap".
Definition FPEnv.h:41
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:695
constexpr float log2ef
Definition MathExtras.h:52
constexpr double e
constexpr float ln2f
Definition MathExtras.h:50
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
Type * getValueType(Value *V, bool ReVec, bool LookThroughCmp)
Returns the "element type" of the given value/instruction V.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
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
LLVM_ABI ISD::NodeType getAtomicRMWOpcode(AtomicRMWInst::BinOp Op)
Return the atomic node opcode for an atomicrmw operation.
Definition Analysis.cpp:292
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
LLVM_ABI bool canDescribeGlobalAddressInLocationList(const MachineFunction &MF)
Test if the debug info for MF can name a describable global address in a location list too,...
Definition Analysis.cpp:695
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:248
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
SDValue peekThroughFreeze(SDValue V)
Return the non-frozen source operand of V if it exists.
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Unknown
Not known to have no common set bits.
LLVM_ABI void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs=nullptr, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition Analysis.cpp:121
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void diagnoseDontCall(const CallInst &CI)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isExceptionPointerAndSelectorType(Type *Ty)
Return true if landingpad result type Ty is a struct of an exception pointer (pointer or integer) and...
Definition Analysis.cpp:201
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
auto cast_or_null(const Y &Val)
Definition Casting.h:714
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
LLVM_ABI void reportFatalInternalError(Error Err)
Report a fatal error that indicates a bug in LLVM.
Definition Error.cpp:173
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void ComputeValueTypes(const DataLayout &DL, Type *Ty, SmallVectorImpl< Type * > &Types, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
Given an LLVM IR type, compute non-aggregate subtypes.
Definition Analysis.cpp:74
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
FPOp
The floating-point operations supported by the folding helpers.
Definition FPFold.h:25
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_FMINNUM
Unsigned maximum.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&...args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest.
Definition STLExtras.h:869
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
generic_gep_type_iterator<> gep_type_iterator
auto succ_size(const MachineBasicBlock *BB)
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:214
LLVM_ABI MDNode * getMemCacheHint(const Instruction &I, unsigned OperandNo=0)
Return the hint payload for operand OperandNo of I, or nullptr if absent.
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
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
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2354
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:709
DWARFExpression::Operation Op
@ Dynamic
Denotes mode unknown at compile time.
LLVM_ABI ISD::CondCode getFCmpCodeWithoutNaN(ISD::CondCode CC)
getFCmpCodeWithoutNaN - Given an ISD condition code comparing floats, return the equivalent code if w...
Definition Analysis.cpp:236
LLVM_ABI const GlobalValue * getDescribableGlobalAddress(const Constant *C, int64_t &Offset, const MachineFunction &MF)
If C is the address of a global, possibly displaced by a constant, return that global and set Offset ...
Definition Analysis.cpp:676
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
LLVM_ABI GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:183
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI unsigned ComputeLinearIndex(Type *Ty, const unsigned *Indices, const unsigned *IndicesEnd, unsigned CurIndex=0)
Compute the linearized index of a member in a nested aggregate/struct/array.
Definition Analysis.cpp:35
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:144
uint64_t getScalarStoreSize() const
Definition ValueTypes.h:440
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
EVT changeVectorElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a vector type whose attributes match ourselves with the exception of the element type...
Definition ValueTypes.h:98
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isRISCVVectorTuple() const
Return true if this is a vector value type.
Definition ValueTypes.h:212
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isFixedLengthVector() const
Definition ValueTypes.h:214
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:330
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
EVT changeElementType(LLVMContext &Context, EVT EltVT) const
Return a VT for a type whose attributes match ourselves with the exception of the element type that i...
Definition ValueTypes.h:136
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
void setPointerAddrSpace(unsigned AS)
InputArg - This struct carries flags and type information about a single incoming (formal) argument o...
static const unsigned NoArgIndex
Sentinel value for implicit machine-level input arguments.
OutputArg - This struct carries flags and a value for a single outgoing (actual) argument or outgoing...
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber/label.
Definition InlineAsm.h:129
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
This class contains a discriminated union of information about pointers in memory operands,...
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.
A lightweight accessor for an operand bundle meant to be passed around by value.
This struct represents the registers (physical or virtual) that a particular set of values is assigne...
SmallVector< std::pair< Register, TypeSize >, 4 > getRegsAndSizes() const
Return a list of registers and their sizes.
RegsForValue()=default
SmallVector< unsigned, 4 > RegCount
This list holds the number of registers for each value.
SmallVector< EVT, 4 > ValueVTs
The value types of the values, which may not be legal, and may need be promoted or synthesized from o...
SmallVector< Register, 4 > Regs
This list holds the registers assigned to the values.
void AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching, unsigned MatchingIdx, const SDLoc &dl, SelectionDAG &DAG, std::vector< SDValue > &Ops) const
Add this value to the specified inlineasm node operand list.
SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr) const
Emit a series of CopyFromReg nodes that copies from this value and returns the result as a ValueVTs v...
SmallVector< MVT, 4 > RegVTs
The value types of the registers.
void getCopyToRegs(SDValue Val, SelectionDAG &DAG, const SDLoc &dl, SDValue &Chain, SDValue *Glue, const Value *V=nullptr, ISD::NodeType PreferredExtendType=ISD::ANY_EXTEND) const
Emit a series of CopyToReg nodes that copies the specified value into the registers specified by this...
std::optional< CallingConv::ID > CallConv
Records if this value needs to be treated in an ABI dependant manner, different to normal type legali...
bool occupiesMultipleRegs() const
Check if the total RegCount is greater than one.
These are IR-level optimization flags that may be propagated to SDNodes.
void copyFMF(const FPMathOperator &FPMO)
Propagate the fast-math-flags from an IR FPMathOperator.
void setUnpredictable(bool b)
bool hasAllowReassociation() const
void setNoUnsignedWrap(bool b)
void setNoSignedWrap(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
A direct output of a callbr's asm, and the registers that its INLINEASM_BR defines it in (see RegsFor...
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
SDLoc DL
The debug location of the instruction this CaseBlock was produced from.
static CaseCluster range(const ConstantInt *Low, const ConstantInt *High, MachineBasicBlock *MBB, BranchProbability Prob)
Register Reg
The virtual register containing the index of the jump table entry to jump to.
MachineBasicBlock * Default
The MBB of the default bb, which is a successor of the range check MBB.
unsigned JTI
The JumpTableIndex for this jump table in the function.
MachineBasicBlock * MBB
The MBB into which to emit the code for the indirect jump.
std::optional< SDLoc > SL
The debug location of the instruction this JumpTable was produced from.
This contains information for each constraint that we are lowering.
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setConvergent(bool Value=true)
CallLoweringInfo & setDeactivationSymbol(GlobalValue *Sym)
CallLoweringInfo & setCFIType(const ConstantInt *Type)
SmallVector< ISD::InputArg, 32 > Ins
Type * OrigRetTy
Original unlegalized return type.
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setIsPatchPoint(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setIsPreallocated(bool Value=true)
CallLoweringInfo & setConvergenceControlToken(SDValue Token)
SmallVector< ISD::OutputArg, 32 > Outs
Type * RetTy
Same as OrigRetTy, or partially legalized for soft float libcalls.
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setPtrAuth(PtrAuthInfo Value)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.
MakeLibCallOptions & setDiscardResult(bool Value=true)
This structure contains the information necessary for lowering pointer-authenticating indirect calls.
LLVM_ABI void addIPToStateRange(const InvokeInst *II, MCSymbol *InvokeBegin, MCSymbol *InvokeEnd)