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"
85#include "llvm/IR/Metadata.h"
86#include "llvm/IR/Module.h"
87#include "llvm/IR/Operator.h"
90#include "llvm/IR/Statepoint.h"
91#include "llvm/IR/Type.h"
92#include "llvm/IR/User.h"
93#include "llvm/IR/Value.h"
94#include "llvm/MC/MCAsmInfo.h"
95#include "llvm/MC/MCContext.h"
100#include "llvm/Support/Debug.h"
108#include <cstddef>
109#include <limits>
110#include <optional>
111#include <tuple>
112
113using namespace llvm;
114using namespace PatternMatch;
115using namespace SwitchCG;
116
117#define DEBUG_TYPE "isel"
118
119/// LimitFloatPrecision - Generate low-precision inline sequences for
120/// some float libcalls (6, 8 or 12 bits).
121static unsigned LimitFloatPrecision;
122
123static cl::opt<bool>
124 InsertAssertAlign("insert-assert-align", cl::init(true),
125 cl::desc("Insert the experimental `assertalign` node."),
127
129 LimitFPPrecision("limit-float-precision",
130 cl::desc("Generate low-precision inline sequences "
131 "for some float libcalls"),
133 cl::init(0));
134
136 "switch-peel-threshold", cl::Hidden, cl::init(66),
137 cl::desc("Set the case probability threshold for peeling the case from a "
138 "switch statement. A value greater than 100 will void this "
139 "optimization"));
140
141// Limit the width of DAG chains. This is important in general to prevent
142// DAG-based analysis from blowing up. For example, alias analysis and
143// load clustering may not complete in reasonable time. It is difficult to
144// recognize and avoid this situation within each individual analysis, and
145// future analyses are likely to have the same behavior. Limiting DAG width is
146// the safe approach and will be especially important with global DAGs.
147//
148// MaxParallelChains default is arbitrarily high to avoid affecting
149// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150// sequence over this should have been converted to llvm.memcpy by the
151// frontend. It is easy to induce this behavior with .ll code such as:
152// %buffer = alloca [4096 x i8]
153// %data = load [4096 x i8]* %argPtr
154// store [4096 x i8] %data, [4096 x i8]* %buffer
155static const unsigned MaxParallelChains = 64;
156
158 const SDValue *Parts, unsigned NumParts,
159 MVT PartVT, EVT ValueVT, const Value *V,
160 SDValue InChain,
161 std::optional<CallingConv::ID> CC);
162
163/// getCopyFromParts - Create a value that contains the specified legal parts
164/// combined into the value they represent. If the parts combine to a type
165/// larger than ValueVT then AssertOp can be used to specify whether the extra
166/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167/// (ISD::AssertSext).
168static SDValue
169getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171 SDValue InChain,
172 std::optional<CallingConv::ID> CC = std::nullopt,
173 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174 // Let the target assemble the parts if it wants to
176 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177 PartVT, ValueVT, CC))
178 return Val;
179
180 if (ValueVT.isVector())
181 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182 InChain, CC);
183
184 assert(NumParts > 0 && "No parts to assemble!");
185 SDValue Val = Parts[0];
186
187 if (NumParts > 1) {
188 // Assemble the value from multiple parts.
189 if (ValueVT.isInteger()) {
190 unsigned PartBits = PartVT.getSizeInBits();
191 unsigned ValueBits = ValueVT.getSizeInBits();
192
193 // Assemble the power of 2 part.
194 unsigned RoundParts = llvm::bit_floor(NumParts);
195 unsigned RoundBits = PartBits * RoundParts;
196 EVT RoundVT = RoundBits == ValueBits ?
197 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198 SDValue Lo, Hi;
199
200 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201
202 if (RoundParts > 2) {
203 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204 InChain);
205 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206 PartVT, HalfVT, V, InChain);
207 } else {
208 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210 }
211
212 if (DAG.getDataLayout().isBigEndian())
213 std::swap(Lo, Hi);
214
215 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216
217 if (RoundParts < NumParts) {
218 // Assemble the trailing non-power-of-2 part.
219 unsigned OddParts = NumParts - RoundParts;
220 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222 OddVT, V, InChain, CC);
223
224 // Combine the round and odd parts.
225 Lo = Val;
226 if (DAG.getDataLayout().isBigEndian())
227 std::swap(Lo, Hi);
228 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230 Hi = DAG.getNode(
231 ISD::SHL, DL, TotalVT, Hi,
232 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
233 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
234 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
235 }
236 } else if (PartVT.isFloatingPoint()) {
237 // FP split into multiple FP parts (for ppcf128)
238 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
239 "Unexpected split");
240 SDValue Lo, Hi;
241 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
242 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
243 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
244 std::swap(Lo, Hi);
245 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
246 } else {
247 // FP split into integer parts (soft fp)
248 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
249 !PartVT.isVector() && "Unexpected split");
250 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
251 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
252 InChain, CC);
253 }
254 }
255
256 // There is now one part, held in Val. Correct it to match ValueVT.
257 // PartEVT is the type of the register class that holds the value.
258 // ValueVT is the type of the inline asm operation.
259 EVT PartEVT = Val.getValueType();
260
261 if (PartEVT == ValueVT)
262 return Val;
263
264 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
265 ValueVT.bitsLT(PartEVT)) {
266 // For an FP value in an integer part, we need to truncate to the right
267 // width first.
268 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
269 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
270 }
271
272 // Handle types that have the same size.
273 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
274 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
275
276 // Handle types with different sizes.
277 if (PartEVT.isInteger() && ValueVT.isInteger()) {
278 if (ValueVT.bitsLT(PartEVT)) {
279 // For a truncate, see if we have any information to
280 // indicate whether the truncated bits will always be
281 // zero or sign-extension.
282 if (AssertOp)
283 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
284 DAG.getValueType(ValueVT));
285 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
286 }
287 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
288 }
289
290 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
291 // FP_ROUND's are always exact here.
292 if (ValueVT.bitsLT(Val.getValueType())) {
293
294 SDValue NoChange =
295 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
296
297 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
298 llvm::Attribute::StrictFP)) {
299 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
300 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
301 NoChange);
302 }
303
304 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
305 }
306
307 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
308 }
309
310 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
311 // then truncating.
312 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
313 ValueVT.bitsLT(PartEVT)) {
314 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
315 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
316 }
317
318 report_fatal_error("Unknown mismatch in getCopyFromParts!");
319}
320
322 const Twine &ErrMsg) {
324 if (!I)
325 return Ctx.emitError(ErrMsg);
326
327 if (const CallInst *CI = dyn_cast<CallInst>(I))
328 if (CI->isInlineAsm()) {
329 return Ctx.diagnose(DiagnosticInfoInlineAsm(
330 *CI, ErrMsg + ", possible invalid constraint for vector type"));
331 }
332
333 return Ctx.emitError(I, ErrMsg);
334}
335
336/// Emit a fatal error if the broken down registers don't match part type
337/// or count.
338static void ensureMatchedVecRegParts(unsigned NumRegs, unsigned NumParts,
339 MVT RegisterVT, MVT PartVT) {
340 if (NumRegs == NumParts && RegisterVT == PartVT)
341 return;
342
344 Twine("Part count doesn't match vector breakdown! ") + Twine(NumRegs) +
345 " registers, " + Twine(NumParts) + " parts, " + RegisterVT.getString() +
346 " RegisterVT, " + PartVT.getString() + " PartVT");
347}
348
349/// getCopyFromPartsVector - Create a value that contains the specified legal
350/// parts combined into the value they represent. If the parts combine to a
351/// type larger than ValueVT then AssertOp can be used to specify whether the
352/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
353/// ValueVT (ISD::AssertSext).
355 const SDValue *Parts, unsigned NumParts,
356 MVT PartVT, EVT ValueVT, const Value *V,
357 SDValue InChain,
358 std::optional<CallingConv::ID> CallConv) {
359 assert(ValueVT.isVector() && "Not a vector value");
360 assert(NumParts > 0 && "No parts to assemble!");
361 const bool IsABIRegCopy = CallConv.has_value();
362
364 SDValue Val = Parts[0];
365
366 // Handle a multi-element vector.
367 if (NumParts > 1) {
368 EVT IntermediateVT;
369 MVT RegisterVT;
370 unsigned NumIntermediates;
371 unsigned NumRegs;
372
373 if (IsABIRegCopy) {
374 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
375 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
376 NumIntermediates, RegisterVT);
377 } else {
378 NumRegs =
379 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
380 NumIntermediates, RegisterVT);
381 }
382
383 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
384 assert(RegisterVT.getSizeInBits() ==
385 Parts[0].getSimpleValueType().getSizeInBits() &&
386 "Part type sizes don't match!");
387
388 // Assemble the parts into intermediate operands.
389 SmallVector<SDValue, 8> Ops(NumIntermediates);
390 if (NumIntermediates == NumParts) {
391 // If the register was not expanded, truncate or copy the value,
392 // as appropriate.
393 for (unsigned i = 0; i != NumParts; ++i)
394 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
395 V, InChain, CallConv);
396 } else if (NumParts > 0) {
397 // If the intermediate type was expanded, build the intermediate
398 // operands from the parts.
399 assert(NumParts % NumIntermediates == 0 &&
400 "Must expand into a divisible number of parts!");
401 unsigned Factor = NumParts / NumIntermediates;
402 for (unsigned i = 0; i != NumIntermediates; ++i)
403 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
404 IntermediateVT, V, InChain, CallConv);
405 }
406
407 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
408 // intermediate operands.
409 EVT BuiltVectorTy =
410 IntermediateVT.isVector()
412 *DAG.getContext(), IntermediateVT.getScalarType(),
413 IntermediateVT.getVectorElementCount() * NumParts)
415 IntermediateVT.getScalarType(),
416 NumIntermediates);
417 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
419 DL, BuiltVectorTy, Ops);
420 }
421
422 // There is now one part, held in Val. Correct it to match ValueVT.
423 EVT PartEVT = Val.getValueType();
424
425 if (PartEVT == ValueVT)
426 return Val;
427
428 if (PartEVT.isVector()) {
429 // Vector/Vector bitcast.
430 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432
433 // If the parts vector has more elements than the value vector, then we
434 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
435 // Extract the elements we want.
436 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
439 (PartEVT.getVectorElementCount().isScalable() ==
440 ValueVT.getVectorElementCount().isScalable()) &&
441 "Cannot narrow, it would be a lossy transformation");
442 PartEVT =
444 ValueVT.getVectorElementCount());
445 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
446 DAG.getVectorIdxConstant(0, DL));
447 if (PartEVT == ValueVT)
448 return Val;
449 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
450 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
451
452 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
453 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
454 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 }
456
457 // Promoted vector extract
458 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
459 }
460
461 // Trivial bitcast if the types are the same size and the destination
462 // vector type is legal.
463 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
464 TLI.isTypeLegal(ValueVT))
465 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
466
467 if (ValueVT.getVectorNumElements() != 1) {
468 // Certain ABIs require that vectors are passed as integers. For vectors
469 // are the same size, this is an obvious bitcast.
470 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
471 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
472 } else if (ValueVT.bitsLT(PartEVT)) {
473 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
474 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
475 // Drop the extra bits.
476 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
477 return DAG.getBitcast(ValueVT, Val);
478 }
479
481 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482 return DAG.getUNDEF(ValueVT);
483 }
484
485 // Handle cases such as i8 -> <1 x i1>
486 EVT ValueSVT = ValueVT.getVectorElementType();
487 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
488 unsigned ValueSize = ValueSVT.getSizeInBits();
489 if (ValueSize == PartEVT.getSizeInBits()) {
490 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
491 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
492 // It's possible a scalar floating point type gets softened to integer and
493 // then promoted to a larger integer. If PartEVT is the larger integer
494 // we need to truncate it and then bitcast to the FP type.
495 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
496 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
497 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
498 Val = DAG.getBitcast(ValueSVT, Val);
499 } else {
500 Val = ValueVT.isFloatingPoint()
501 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
502 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
503 }
504 }
505
506 return DAG.getBuildVector(ValueVT, DL, Val);
507}
508
509static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
510 SDValue Val, SDValue *Parts, unsigned NumParts,
511 MVT PartVT, const Value *V,
512 std::optional<CallingConv::ID> CallConv);
513
514/// getCopyToParts - Create a series of nodes that contain the specified value
515/// split into legal parts. If the parts contain more bits than Val, then, for
516/// integers, ExtendKind can be used to specify how to generate the extra bits.
517static void
519 unsigned NumParts, MVT PartVT, const Value *V,
520 std::optional<CallingConv::ID> CallConv = std::nullopt,
522 // Let the target split the parts if it wants to
524 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
525 CallConv))
526 return;
527 EVT ValueVT = Val.getValueType();
528
529 // Handle the vector case separately.
530 if (ValueVT.isVector())
531 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
532 CallConv);
533
534 unsigned OrigNumParts = NumParts;
536 "Copying to an illegal type!");
537
538 if (NumParts == 0)
539 return;
540
541 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
542 EVT PartEVT = PartVT;
543 if (PartEVT == ValueVT) {
544 assert(NumParts == 1 && "No-op copy with multiple parts!");
545 Parts[0] = Val;
546 return;
547 }
548
549 unsigned PartBits = PartVT.getSizeInBits();
550 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
551 // If the parts cover more bits than the value has, promote the value.
552 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
553 assert(NumParts == 1 && "Do not know what to promote to!");
554 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
555 } else {
556 if (ValueVT.isFloatingPoint()) {
557 // FP values need to be bitcast, then extended if they are being put
558 // into a larger container.
559 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
560 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
561 }
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569 }
570 } else if (PartBits == ValueVT.getSizeInBits()) {
571 // Different types of the same size.
572 assert(NumParts == 1 && PartEVT != ValueVT);
573 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
574 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
575 // If the parts cover less bits than value has, truncate the value.
576 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
577 ValueVT.isInteger() &&
578 "Unknown mismatch!");
579 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581 if (PartVT == MVT::x86mmx)
582 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
583 }
584
585 // The value may have changed - recompute ValueVT.
586 ValueVT = Val.getValueType();
587 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
588 "Failed to tile the value with PartVT!");
589
590 if (NumParts == 1) {
591 if (PartEVT != ValueVT) {
593 "scalar-to-vector conversion failed");
594 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
595 }
596
597 Parts[0] = Val;
598 return;
599 }
600
601 // Expand the value into multiple parts.
602 if (NumParts & (NumParts - 1)) {
603 // The number of parts is not a power of 2. Split off and copy the tail.
604 assert(PartVT.isInteger() && ValueVT.isInteger() &&
605 "Do not know what to expand to!");
606 unsigned RoundParts = llvm::bit_floor(NumParts);
607 unsigned RoundBits = RoundParts * PartBits;
608 unsigned OddParts = NumParts - RoundParts;
609 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
610 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
611
612 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
613 CallConv);
614
615 if (DAG.getDataLayout().isBigEndian())
616 // The odd parts were reversed by getCopyToParts - unreverse them.
617 std::reverse(Parts + RoundParts, Parts + NumParts);
618
619 NumParts = RoundParts;
620 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
621 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
622 }
623
624 // The number of parts is a power of 2. Repeatedly bisect the value using
625 // EXTRACT_ELEMENT.
626 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
628 ValueVT.getSizeInBits()),
629 Val);
630
631 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
632 for (unsigned i = 0; i < NumParts; i += StepSize) {
633 unsigned ThisBits = StepSize * PartBits / 2;
634 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
635 SDValue &Part0 = Parts[i];
636 SDValue &Part1 = Parts[i+StepSize/2];
637
638 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
639 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
640 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
641 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
642
643 if (ThisBits == PartBits && ThisVT != PartVT) {
644 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
645 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
646 }
647 }
648 }
649
650 if (DAG.getDataLayout().isBigEndian())
651 std::reverse(Parts, Parts + OrigNumParts);
652}
653
655 const SDLoc &DL, EVT PartVT) {
656 if (!PartVT.isVector())
657 return SDValue();
658
659 EVT ValueVT = Val.getValueType();
660 EVT PartEVT = PartVT.getVectorElementType();
661 EVT ValueEVT = ValueVT.getVectorElementType();
662 ElementCount PartNumElts = PartVT.getVectorElementCount();
663 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
664
665 // We only support widening vectors with equivalent element types and
666 // fixed/scalable properties. If a target needs to widen a fixed-length type
667 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
668 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
669 PartNumElts.isScalable() != ValueNumElts.isScalable())
670 return SDValue();
671
672 // Have a try for bf16 because some targets share its ABI with fp16.
673 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
675 "Cannot widen to illegal type");
676 Val = DAG.getNode(
678 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
679 } else if (PartEVT != ValueEVT) {
680 return SDValue();
681 }
682
683 // Widening a scalable vector to another scalable vector is done by inserting
684 // the vector into a larger undef one.
685 if (PartNumElts.isScalable())
686 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
687 Val, DAG.getVectorIdxConstant(0, DL));
688
689 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
690 // undef elements.
692 DAG.ExtractVectorElements(Val, Ops);
693 SDValue EltUndef = DAG.getUNDEF(PartEVT);
694 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
695
696 // FIXME: Use CONCAT for 2x -> 4x.
697 return DAG.getBuildVector(PartVT, DL, Ops);
698}
699
700/// getCopyToPartsVector - Create a series of nodes that contain the specified
701/// value split into legal parts.
702static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
703 SDValue Val, SDValue *Parts, unsigned NumParts,
704 MVT PartVT, const Value *V,
705 std::optional<CallingConv::ID> CallConv) {
706 EVT ValueVT = Val.getValueType();
707 assert(ValueVT.isVector() && "Not a vector");
709 const bool IsABIRegCopy = CallConv.has_value();
710
711 if (NumParts == 1) {
712 EVT PartEVT = PartVT;
713 if (PartEVT == ValueVT) {
714 // Nothing to do.
715 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
716 // Bitconvert vector->vector case.
717 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
718 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
719 Val = Widened;
720 } else if (PartVT.isVector() &&
722 ValueVT.getVectorElementType()) &&
723 PartEVT.getVectorElementCount() ==
724 ValueVT.getVectorElementCount()) {
725
726 // Promoted vector extract
727 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
728 } else if (PartEVT.isVector() &&
729 PartEVT.getVectorElementType() !=
730 ValueVT.getVectorElementType() &&
731 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
733 // Combination of widening and promotion.
734 EVT WidenVT =
736 PartVT.getVectorElementCount());
737 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
738 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
739 } else {
740 // Don't extract an integer from a float vector. This can happen if the
741 // FP type gets softened to integer and then promoted. The promotion
742 // prevents it from being picked up by the earlier bitcast case.
743 if (ValueVT.getVectorElementCount().isScalar() &&
744 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
745 // If we reach this condition and PartVT is FP, this means that
746 // ValueVT is also FP and both have a different size, otherwise we
747 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
748 // would be invalid since that would mean the smaller FP type has to
749 // be extended to the larger one.
750 if (PartVT.isFloatingPoint()) {
751 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
752 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
753 } else
754 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
755 DAG.getVectorIdxConstant(0, DL));
756 } else {
757 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
758 assert(PartVT.getFixedSizeInBits() > ValueSize &&
759 "lossy conversion of vector to scalar type");
760 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
761 Val = DAG.getBitcast(IntermediateType, Val);
762 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
763 }
764 }
765
766 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
767 Parts[0] = Val;
768 return;
769 }
770
771 // Handle a multi-element vector.
772 EVT IntermediateVT;
773 MVT RegisterVT;
774 unsigned NumIntermediates;
775 unsigned NumRegs;
776 if (IsABIRegCopy) {
777 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
778 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
779 RegisterVT);
780 } else {
781 NumRegs =
782 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
783 NumIntermediates, RegisterVT);
784 }
785
786 ensureMatchedVecRegParts(NumRegs, NumParts, RegisterVT, PartVT);
787 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
788 "Mixing scalable and fixed vectors when copying in parts");
789
790 std::optional<ElementCount> DestEltCnt;
791
792 if (IntermediateVT.isVector())
793 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
794 else
795 DestEltCnt = ElementCount::getFixed(NumIntermediates);
796
797 EVT BuiltVectorTy = EVT::getVectorVT(
798 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
799
800 if (ValueVT == BuiltVectorTy) {
801 // Nothing to do.
802 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
803 // Bitconvert vector->vector case.
804 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
805 } else {
806 if (BuiltVectorTy.getVectorElementType().bitsGT(
807 ValueVT.getVectorElementType())) {
808 // Integer promotion.
809 ValueVT = EVT::getVectorVT(*DAG.getContext(),
810 BuiltVectorTy.getVectorElementType(),
811 ValueVT.getVectorElementCount());
812 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
813 }
814
815 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
816 Val = Widened;
817 }
818 }
819
820 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
821
822 // Split the vector into intermediate operands.
823 SmallVector<SDValue, 8> Ops(NumIntermediates);
824 for (unsigned i = 0; i != NumIntermediates; ++i) {
825 if (IntermediateVT.isVector()) {
826 // This does something sensible for scalable vectors - see the
827 // definition of EXTRACT_SUBVECTOR for further details.
828 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
829 Ops[i] =
830 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
831 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
832 } else {
833 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
834 DAG.getVectorIdxConstant(i, DL));
835 }
836 }
837
838 // Split the intermediate operands into legal parts.
839 if (NumParts == NumIntermediates) {
840 // If the register was not expanded, promote or copy the value,
841 // as appropriate.
842 for (unsigned i = 0; i != NumParts; ++i)
843 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
844 } else if (NumParts > 0) {
845 // If the intermediate type was expanded, split each the value into
846 // legal parts.
847 assert(NumIntermediates != 0 && "division by zero");
848 assert(NumParts % NumIntermediates == 0 &&
849 "Must expand into a divisible number of parts!");
850 unsigned Factor = NumParts / NumIntermediates;
851 for (unsigned i = 0; i != NumIntermediates; ++i)
852 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
853 CallConv);
854 }
855}
856
857static void failForInvalidBundles(const CallBase &I, StringRef Name,
858 ArrayRef<uint32_t> AllowedBundles) {
859 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
860 ListSeparator LS;
861 std::string Error;
863 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
864 OperandBundleUse U = I.getOperandBundleAt(i);
865 if (!is_contained(AllowedBundles, U.getTagID()))
866 OS << LS << U.getTagName();
867 }
869 Twine("cannot lower ", Name)
870 .concat(Twine(" with arbitrary operand bundles: ", Error)));
871 }
872}
873
875 EVT valuevt, std::optional<CallingConv::ID> CC)
876 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
877 RegCount(1, regs.size()), CallConv(CC) {}
878
880 const DataLayout &DL, Register Reg, Type *Ty,
881 std::optional<CallingConv::ID> CC) {
883
884 CallConv = CC;
885
886 for (EVT ValueVT : ValueVTs) {
887 unsigned NumRegs =
889 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
890 : TLI.getNumRegisters(Context, ValueVT);
891 MVT RegisterVT =
893 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
894 : TLI.getRegisterType(Context, ValueVT);
895 for (unsigned i = 0; i != NumRegs; ++i)
896 Regs.push_back(Reg + i);
897 RegVTs.push_back(RegisterVT);
898 RegCount.push_back(NumRegs);
899 Reg = Reg.id() + NumRegs;
900 }
901}
902
904 FunctionLoweringInfo &FuncInfo,
905 const SDLoc &dl, SDValue &Chain,
906 SDValue *Glue, const Value *V) const {
907 // A Value with type {} or [0 x %t] needs no registers.
908 if (ValueVTs.empty())
909 return SDValue();
910
912
913 // Assemble the legal parts into the final values.
916 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
917 // Copy the legal parts from the registers.
918 EVT ValueVT = ValueVTs[Value];
919 unsigned NumRegs = RegCount[Value];
920 MVT RegisterVT = isABIMangled()
921 ? TLI.getRegisterTypeForCallingConv(
922 *DAG.getContext(), *CallConv, RegVTs[Value])
923 : RegVTs[Value];
924
925 Parts.resize(NumRegs);
926 for (unsigned i = 0; i != NumRegs; ++i) {
927 SDValue P;
928 if (!Glue) {
929 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
930 } else {
931 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
932 *Glue = P.getValue(2);
933 }
934
935 Chain = P.getValue(1);
936 Parts[i] = P;
937
938 // If the source register was virtual and if we know something about it,
939 // add an assert node.
940 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
941 continue;
942
944 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
945 if (!LOI)
946 continue;
947
948 unsigned RegSize = RegisterVT.getScalarSizeInBits();
949 unsigned NumSignBits = LOI->NumSignBits;
950 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
951
952 if (NumZeroBits == RegSize) {
953 // The current value is a zero.
954 // Explicitly express that as it would be easier for
955 // optimizations to kick in.
956 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
957 continue;
958 }
959
960 // FIXME: We capture more information than the dag can represent. For
961 // now, just use the tightest assertzext/assertsext possible.
962 bool isSExt;
963 EVT FromVT(MVT::Other);
964 if (NumZeroBits) {
965 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
966 isSExt = false;
967 } else if (NumSignBits > 1) {
968 FromVT =
969 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
970 isSExt = true;
971 } else {
972 continue;
973 }
974 // Add an assertion node.
975 assert(FromVT != MVT::Other);
976 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
977 RegisterVT, P, DAG.getValueType(FromVT));
978 }
979
980 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
981 RegisterVT, ValueVT, V, Chain, CallConv);
982 Part += NumRegs;
983 Parts.clear();
984 }
985
986 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
987}
988
990 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
991 const Value *V,
992 ISD::NodeType PreferredExtendType) const {
994 ISD::NodeType ExtendKind = PreferredExtendType;
995
996 // Get the list of the values's legal parts.
997 unsigned NumRegs = Regs.size();
998 SmallVector<SDValue, 8> Parts(NumRegs);
999 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
1000 unsigned NumParts = RegCount[Value];
1001
1002 MVT RegisterVT = isABIMangled()
1003 ? TLI.getRegisterTypeForCallingConv(
1004 *DAG.getContext(), *CallConv, RegVTs[Value])
1005 : RegVTs[Value];
1006
1008 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
1010
1011 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1012 NumParts, RegisterVT, V, CallConv, ExtendKind);
1013 Part += NumParts;
1014 }
1015
1016 // Copy the parts into the registers.
1017 SmallVector<SDValue, 8> Chains(NumRegs);
1018 for (unsigned i = 0; i != NumRegs; ++i) {
1019 SDValue Part;
1020 if (!Glue) {
1021 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1022 } else {
1023 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1024 *Glue = Part.getValue(1);
1025 }
1026
1027 Chains[i] = Part.getValue(0);
1028 }
1029
1030 if (NumRegs == 1 || Glue)
1031 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1032 // flagged to it. That is the CopyToReg nodes and the user are considered
1033 // a single scheduling unit. If we create a TokenFactor and return it as
1034 // chain, then the TokenFactor is both a predecessor (operand) of the
1035 // user as well as a successor (the TF operands are flagged to the user).
1036 // c1, f1 = CopyToReg
1037 // c2, f2 = CopyToReg
1038 // c3 = TokenFactor c1, c2
1039 // ...
1040 // = op c3, ..., f2
1041 Chain = Chains[NumRegs-1];
1042 else
1043 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1044}
1045
1047 unsigned MatchingIdx, const SDLoc &dl,
1048 SelectionDAG &DAG,
1049 std::vector<SDValue> &Ops) const {
1051
1052 InlineAsm::Flag Flag(Code, Regs.size());
1053 if (HasMatching)
1054 Flag.setMatchingOp(MatchingIdx);
1055 else if (!Regs.empty() && Regs.front().isVirtual()) {
1056 // Put the register class of the virtual registers in the flag word. That
1057 // way, later passes can recompute register class constraints for inline
1058 // assembly as well as normal instructions.
1059 // Don't do this for tied operands that can use the regclass information
1060 // from the def.
1062 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1063 Flag.setRegClass(RC->getID());
1064 }
1065
1066 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1067 Ops.push_back(Res);
1068
1069 if (Code == InlineAsm::Kind::Clobber) {
1070 // Clobbers should always have a 1:1 mapping with registers, and may
1071 // reference registers that have illegal (e.g. vector) types. Hence, we
1072 // shouldn't try to apply any sort of splitting logic to them.
1073 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1074 "No 1:1 mapping from clobbers to regs?");
1075 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1076 (void)SP;
1077 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1078 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1079 assert(
1080 (Regs[I] != SP ||
1082 "If we clobbered the stack pointer, MFI should know about it.");
1083 }
1084 return;
1085 }
1086
1087 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1088 MVT RegisterVT = RegVTs[Value];
1089 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1090 RegisterVT);
1091 for (unsigned i = 0; i != NumRegs; ++i) {
1092 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1093 Register TheReg = Regs[Reg++];
1094 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1095 }
1096 }
1097}
1098
1102 unsigned I = 0;
1103 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1104 unsigned RegCount = std::get<0>(CountAndVT);
1105 MVT RegisterVT = std::get<1>(CountAndVT);
1106 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1107 for (unsigned E = I + RegCount; I != E; ++I)
1108 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1109 }
1110 return OutVec;
1111}
1112
1114 AssumptionCache *ac, const TargetLibraryInfo *li,
1115 const TargetTransformInfo &TTI) {
1116 BatchAA = aa;
1117 AC = ac;
1118 GFI = gfi;
1119 LibInfo = li;
1120 Context = DAG.getContext();
1121 LPadToCallSiteMap.clear();
1122 this->TTI = &TTI;
1123 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1124 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1125 *DAG.getMachineFunction().getFunction().getParent());
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);
1843 SDValue Result;
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);
1854 resolveDanglingDebugInfo(V, Result);
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 auto *U : Ins->users()) {
2686 // If user is independent of RHS calculation we don't need to count it.
2687 if (auto *UIns = dyn_cast<Instruction>(U))
2688 if (UIns != BrCond && !RhsDeps.contains(UIns))
2689 return false;
2690 }
2691 return true;
2692 };
2693
2694 // Prune instructions from RHS Deps that are dependencies of unrelated
2695 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2696 // arbitrary and just meant to cap the how much time we spend in the pruning
2697 // loop. Its highly unlikely to come into affect.
2698 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2699 // Stop after a certain point. No incorrectness from including too many
2700 // instructions.
2701 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2702 const Instruction *ToDrop = nullptr;
2703 for (const auto &InsPair : RhsDeps) {
2704 if (!ShouldCountInsn(InsPair.first)) {
2705 ToDrop = InsPair.first;
2706 break;
2707 }
2708 }
2709 if (ToDrop == nullptr)
2710 break;
2711 RhsDeps.erase(ToDrop);
2712 }
2713
2714 for (const auto &InsPair : RhsDeps) {
2715 // Finally accumulate latency that we can only attribute to computing the
2716 // RHS condition. Use latency because we are essentially trying to calculate
2717 // the cost of the dependency chain.
2718 // Possible TODO: We could try to estimate ILP and make this more precise.
2719 CostOfIncluding += TTI->getInstructionCost(
2720 InsPair.first, TargetTransformInfo::TCK_Latency);
2721
2722 if (CostOfIncluding > CostThresh)
2723 return false;
2724 }
2725 return true;
2726}
2727
2730 MachineBasicBlock *FBB,
2731 MachineBasicBlock *CurBB,
2732 MachineBasicBlock *SwitchBB,
2734 BranchProbability TProb,
2735 BranchProbability FProb,
2736 bool InvertCond) {
2737 // Skip over not part of the tree and remember to invert op and operands at
2738 // next level.
2739 Value *NotCond;
2740 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2741 InBlock(NotCond, CurBB->getBasicBlock())) {
2742 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2743 !InvertCond);
2744 return;
2745 }
2746
2748 const Value *BOpOp0, *BOpOp1;
2749 // Compute the effective opcode for Cond, taking into account whether it needs
2750 // to be inverted, e.g.
2751 // and (not (or A, B)), C
2752 // gets lowered as
2753 // and (and (not A, not B), C)
2755 if (BOp) {
2756 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2757 ? Instruction::And
2758 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2759 ? Instruction::Or
2761 if (InvertCond) {
2762 if (BOpc == Instruction::And)
2763 BOpc = Instruction::Or;
2764 else if (BOpc == Instruction::Or)
2765 BOpc = Instruction::And;
2766 }
2767 }
2768
2769 // If this node is not part of the or/and tree, emit it as a branch.
2770 // Note that all nodes in the tree should have same opcode.
2771 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2772 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2773 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2774 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2775 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2776 TProb, FProb, InvertCond);
2777 return;
2778 }
2779
2780 // Create TmpBB after CurBB.
2781 MachineFunction::iterator BBI(CurBB);
2782 MachineFunction &MF = DAG.getMachineFunction();
2784 CurBB->getParent()->insert(++BBI, TmpBB);
2785
2786 if (Opc == Instruction::Or) {
2787 // Codegen X | Y as:
2788 // BB1:
2789 // jmp_if_X TBB
2790 // jmp TmpBB
2791 // TmpBB:
2792 // jmp_if_Y TBB
2793 // jmp FBB
2794 //
2795
2796 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2797 // The requirement is that
2798 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2799 // = TrueProb for original BB.
2800 // Assuming the original probabilities are A and B, one choice is to set
2801 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2802 // A/(1+B) and 2B/(1+B). This choice assumes that
2803 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2804 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2805 // TmpBB, but the math is more complicated.
2806
2807 auto NewTrueProb = TProb / 2;
2808 auto NewFalseProb = TProb / 2 + FProb;
2809 // Emit the LHS condition.
2810 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2811 NewFalseProb, InvertCond);
2812
2813 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2814 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2816 // Emit the RHS condition into TmpBB.
2817 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2818 Probs[1], InvertCond);
2819 } else {
2820 assert(Opc == Instruction::And && "Unknown merge op!");
2821 // Codegen X & Y as:
2822 // BB1:
2823 // jmp_if_X TmpBB
2824 // jmp FBB
2825 // TmpBB:
2826 // jmp_if_Y TBB
2827 // jmp FBB
2828 //
2829 // This requires creation of TmpBB after CurBB.
2830
2831 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2832 // The requirement is that
2833 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2834 // = FalseProb for original BB.
2835 // Assuming the original probabilities are A and B, one choice is to set
2836 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2837 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2838 // TrueProb for BB1 * FalseProb for TmpBB.
2839
2840 auto NewTrueProb = TProb + FProb / 2;
2841 auto NewFalseProb = FProb / 2;
2842 // Emit the LHS condition.
2843 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2844 NewFalseProb, InvertCond);
2845
2846 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2847 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2849 // Emit the RHS condition into TmpBB.
2850 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2851 Probs[1], InvertCond);
2852 }
2853}
2854
2855/// If the set of cases should be emitted as a series of branches, return true.
2856/// If we should emit this as a bunch of and/or'd together conditions, return
2857/// false.
2858bool
2859SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2860 if (Cases.size() != 2) return true;
2861
2862 // If this is two comparisons of the same values or'd or and'd together, they
2863 // will get folded into a single comparison, so don't emit two blocks.
2864 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2865 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2866 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2867 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2868 return false;
2869 }
2870
2871 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2872 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2873 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2874 Cases[0].CC == Cases[1].CC &&
2875 isa<Constant>(Cases[0].CmpRHS) &&
2876 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2877 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2878 return false;
2879 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2880 return false;
2881 }
2882
2883 return true;
2884}
2885
2886void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2888
2889 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2890
2891 // Update machine-CFG edges.
2892 BrMBB->addSuccessor(Succ0MBB);
2893
2894 // If this is not a fall-through branch or optimizations are switched off,
2895 // emit the branch.
2896 if (Succ0MBB != NextBlock(BrMBB) ||
2898 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2899 DAG.getBasicBlock(Succ0MBB));
2900 setValue(&I, Br);
2901 DAG.setRoot(Br);
2902 }
2903}
2904
2905void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2906 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2907
2908 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2909
2910 // If this condition is one of the special cases we handle, do special stuff
2911 // now.
2912 const Value *CondVal = I.getCondition();
2913 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2914
2915 // If this is a series of conditions that are or'd or and'd together, emit
2916 // this as a sequence of branches instead of setcc's with and/or operations.
2917 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2918 // unpredictable branches, and vector extracts because those jumps are likely
2919 // expensive for any target), this should improve performance.
2920 // For example, instead of something like:
2921 // cmp A, B
2922 // C = seteq
2923 // cmp D, E
2924 // F = setle
2925 // or C, F
2926 // jnz foo
2927 // Emit:
2928 // cmp A, B
2929 // je foo
2930 // cmp D, E
2931 // jle foo
2932 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2933 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2934 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2935 BOp->hasOneUse() && !IsUnpredictable) {
2936 Value *Vec;
2937 const Value *BOp0, *BOp1;
2939 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2940 Opcode = Instruction::And;
2941 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2942 Opcode = Instruction::Or;
2943
2944 if (Opcode &&
2945 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2946 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2948 FuncInfo, I, Opcode, BOp0, BOp1,
2949 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2950 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2951 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2952 getEdgeProbability(BrMBB, Succ0MBB),
2953 getEdgeProbability(BrMBB, Succ1MBB),
2954 /*InvertCond=*/false);
2955 // If the compares in later blocks need to use values not currently
2956 // exported from this block, export them now. This block should always
2957 // be the first entry.
2958 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2959
2960 // Allow some cases to be rejected.
2961 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2962 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2963 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2964 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2965 }
2966
2967 // Emit the branch for this block.
2968 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2969 SL->SwitchCases.erase(SL->SwitchCases.begin());
2970 return;
2971 }
2972
2973 // Okay, we decided not to do this, remove any inserted MBB's and clear
2974 // SwitchCases.
2975 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2976 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2977
2978 SL->SwitchCases.clear();
2979 }
2980 }
2981
2982 // Create a CaseBlock record representing this branch.
2983 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2984 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2986 IsUnpredictable);
2987
2988 // Use visitSwitchCase to actually insert the fast branch sequence for this
2989 // cond branch.
2990 visitSwitchCase(CB, BrMBB);
2991}
2992
2993/// visitSwitchCase - Emits the necessary code to represent a single node in
2994/// the binary search tree resulting from lowering a switch instruction.
2996 MachineBasicBlock *SwitchBB) {
2997 SDValue Cond;
2998 SDValue CondLHS = getValue(CB.CmpLHS);
2999 SDLoc dl = CB.DL;
3000
3001 if (CB.CC == ISD::SETTRUE) {
3002 // Branch or fall through to TrueBB.
3003 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3004 SwitchBB->normalizeSuccProbs();
3005 if (CB.TrueBB != NextBlock(SwitchBB)) {
3006 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
3007 DAG.getBasicBlock(CB.TrueBB)));
3008 }
3009 return;
3010 }
3011
3012 auto &TLI = DAG.getTargetLoweringInfo();
3013 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
3014
3015 // Build the setcc now.
3016 if (!CB.CmpMHS) {
3017 // Fold "(X == true)" to X and "(X == false)" to !X to
3018 // handle common cases produced by branch lowering.
3019 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
3020 CB.CC == ISD::SETEQ)
3021 Cond = CondLHS;
3022 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
3023 CB.CC == ISD::SETEQ) {
3024 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
3025 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
3026 } else {
3027 SDValue CondRHS = getValue(CB.CmpRHS);
3028
3029 // If a pointer's DAG type is larger than its memory type then the DAG
3030 // values are zero-extended. This breaks signed comparisons so truncate
3031 // back to the underlying type before doing the compare.
3032 if (CondLHS.getValueType() != MemVT) {
3033 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
3034 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
3035 }
3036 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
3037 }
3038 } else {
3039 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
3040
3041 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
3042 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
3043
3044 SDValue CmpOp = getValue(CB.CmpMHS);
3045 EVT VT = CmpOp.getValueType();
3046
3047 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
3048 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
3049 ISD::SETLE);
3050 } else {
3051 SDValue SUB = DAG.getNode(ISD::SUB, dl,
3052 VT, CmpOp, DAG.getConstant(Low, dl, VT));
3053 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
3054 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
3055 }
3056 }
3057
3058 // Update successor info
3059 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3060 // TrueBB and FalseBB are always different unless the incoming IR is
3061 // degenerate. This only happens when running llc on weird IR.
3062 if (CB.TrueBB != CB.FalseBB)
3063 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
3064 SwitchBB->normalizeSuccProbs();
3065
3066 // If the lhs block is the next block, invert the condition so that we can
3067 // fall through to the lhs instead of the rhs block.
3068 if (CB.TrueBB == NextBlock(SwitchBB)) {
3069 std::swap(CB.TrueBB, CB.FalseBB);
3070 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3071 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3072 }
3073
3074 SDNodeFlags Flags;
3076 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3077 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3078
3079 setValue(CurInst, BrCond);
3080
3081 // Insert the false branch. Do this even if it's a fall through branch,
3082 // this makes it easier to do DAG optimizations which require inverting
3083 // the branch condition.
3084 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3085 DAG.getBasicBlock(CB.FalseBB));
3086
3087 DAG.setRoot(BrCond);
3088}
3089
3090/// visitJumpTable - Emit JumpTable node in the current MBB
3092 // Emit the code for the jump table
3093 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3094 assert(JT.Reg && "Should lower JT Header first!");
3095 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3096 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3097 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3098 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3099 Index.getValue(1), Table, Index);
3100 DAG.setRoot(BrJumpTable);
3101}
3102
3103/// visitJumpTableHeader - This function emits necessary code to produce index
3104/// in the JumpTable from switch case.
3106 JumpTableHeader &JTH,
3107 MachineBasicBlock *SwitchBB) {
3108 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3109 const SDLoc &dl = *JT.SL;
3110
3111 // Subtract the lowest switch case value from the value being switched on.
3112 SDValue SwitchOp = getValue(JTH.SValue);
3113 EVT VT = SwitchOp.getValueType();
3114 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3115 DAG.getConstant(JTH.First, dl, VT));
3116
3117 // The SDNode we just created, which holds the value being switched on minus
3118 // the smallest case value, needs to be copied to a virtual register so it
3119 // can be used as an index into the jump table in a subsequent basic block.
3120 // This value may be smaller or larger than the target's pointer type, and
3121 // therefore require extension or truncating.
3122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3123 SwitchOp =
3124 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3125
3126 Register JumpTableReg =
3127 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3128 SDValue CopyTo =
3129 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3130 JT.Reg = JumpTableReg;
3131
3132 if (!JTH.FallthroughUnreachable) {
3133 // Emit the range check for the jump table, and branch to the default block
3134 // for the switch statement if the value being switched on exceeds the
3135 // largest case in the switch.
3136 SDValue CMP = DAG.getSetCC(
3137 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3138 Sub.getValueType()),
3139 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3140
3141 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3142 MVT::Other, CopyTo, CMP,
3143 DAG.getBasicBlock(JT.Default));
3144
3145 // Avoid emitting unnecessary branches to the next block.
3146 if (JT.MBB != NextBlock(SwitchBB))
3147 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3148 DAG.getBasicBlock(JT.MBB));
3149
3150 DAG.setRoot(BrCond);
3151 } else {
3152 // Avoid emitting unnecessary branches to the next block.
3153 if (JT.MBB != NextBlock(SwitchBB))
3154 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3155 DAG.getBasicBlock(JT.MBB)));
3156 else
3157 DAG.setRoot(CopyTo);
3158 }
3159}
3160
3161/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3162/// variable if there exists one.
3164 SDValue &Chain) {
3166 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3167 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3169 Value *Global =
3170 TLI.getSDagStackGuard(*MF.getFunction().getParent(), DAG.getLibcalls());
3172 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3173 if (Global) {
3174 MachinePointerInfo MPInfo(Global);
3178 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3179 DAG.setNodeMemRefs(Node, {MemRef});
3180 }
3181 if (PtrTy != PtrMemTy)
3182 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3183 return SDValue(Node, 0);
3184}
3185
3186/// Codegen a new tail for a stack protector check ParentMBB which has had its
3187/// tail spliced into a stack protector check success bb.
3188///
3189/// For a high level explanation of how this fits into the stack protector
3190/// generation see the comment on the declaration of class
3191/// StackProtectorDescriptor.
3193 MachineBasicBlock *ParentBB) {
3194
3195 // First create the loads to the guard/stack slot for the comparison.
3196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3197 auto &DL = DAG.getDataLayout();
3198 EVT PtrTy = TLI.getFrameIndexTy(DL);
3199 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3200
3201 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3202 int FI = MFI.getStackProtectorIndex();
3203
3204 SDValue Guard;
3205 SDLoc dl = getCurSDLoc();
3206 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3207 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3208 Align Align = DL.getPrefTypeAlign(
3209 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3210
3211 // Generate code to load the content of the guard slot.
3212 SDValue GuardVal = DAG.getLoad(
3213 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3214 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3216
3217 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3218 // original cookie for comparison. The prologue stored (FP - Cookie) or
3219 // (FP XOR Cookie), so we apply the same operation again to unmix:
3220 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3221 if (TLI.useStackGuardMixFP())
3222 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3223
3224 // If we're using function-based instrumentation, call the guard check
3225 // function
3227 // Get the guard check function from the target and verify it exists since
3228 // we're using function-based instrumentation
3229 const Function *GuardCheckFn =
3230 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3231 assert(GuardCheckFn && "Guard check function is null");
3232
3233 // The target provides a guard check function to validate the guard value.
3234 // Generate a call to that function with the content of the guard slot as
3235 // argument.
3236 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3237 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3238
3240 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3241 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3242 Entry.IsInReg = true;
3243 Args.push_back(Entry);
3244
3247 .setChain(DAG.getEntryNode())
3248 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3249 getValue(GuardCheckFn), std::move(Args));
3250
3251 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3252 DAG.setRoot(Result.second);
3253 return;
3254 }
3255
3256 // Load the fresh guard value for comparison.
3257 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3258 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3259 SDValue Chain = DAG.getEntryNode();
3260 if (TLI.useStackGuardMixFP()) {
3261 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3262 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3263 SDValue GuardPtr = getValue(IRGuard);
3264 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3265 MachinePointerInfo(IRGuard, 0), Align,
3267 } else {
3268 LLVMContext &Ctx = *DAG.getContext();
3269 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3270 Guard = DAG.getPOISON(PtrMemTy);
3271 }
3272 } else {
3273 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3274 if (TLI.useLoadStackGuardNode(M)) {
3275 Guard = getLoadStackGuard(DAG, dl, Chain);
3276 } else {
3277 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3278 SDValue GuardPtr = getValue(IRGuard);
3279 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3280 MachinePointerInfo(IRGuard, 0), Align,
3282 } else {
3283 LLVMContext &Ctx = *DAG.getContext();
3284 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3285 Guard = DAG.getPOISON(PtrMemTy);
3286 }
3287 }
3288 }
3289
3290 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3291 // contain unmixed cookie values that can be compared directly.
3292
3293 // Perform the comparison via a getsetcc.
3294 SDValue Cmp = DAG.getSetCC(
3295 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3296 Guard, GuardVal, ISD::SETNE);
3297
3298 // If the guard/stackslot do not equal, branch to failure MBB.
3299 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3300 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3301 // Otherwise branch to success MBB.
3302 SDValue Br = DAG.getNode(ISD::BR, dl,
3303 MVT::Other, BrCond,
3304 DAG.getBasicBlock(SPD.getSuccessMBB()));
3305
3306 DAG.setRoot(Br);
3307}
3308
3309/// Codegen the failure basic block for a stack protector check.
3310///
3311/// A failure stack protector machine basic block consists simply of a call to
3312/// __stack_chk_fail().
3313///
3314/// For a high level explanation of how this fits into the stack protector
3315/// generation see the comment on the declaration of class
3316/// StackProtectorDescriptor.
3319
3320 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3321 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3322 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3323 SDValue Chain;
3324
3325 // For -Oz builds with a guard check function, we use function-based
3326 // instrumentation. Otherwise, if we have a guard check function, we call it
3327 // in the failure block.
3328 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3329 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3330 // First create the loads to the guard/stack slot for the comparison.
3331 auto &DL = DAG.getDataLayout();
3332 EVT PtrTy = TLI.getFrameIndexTy(DL);
3333 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3334
3335 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3336 int FI = MFI.getStackProtectorIndex();
3337
3338 SDLoc dl = getCurSDLoc();
3339 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3340 Align Align = DL.getPrefTypeAlign(
3341 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3342
3343 // Generate code to load the content of the guard slot.
3344 SDValue GuardVal = DAG.getLoad(
3345 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3346 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3348
3349 if (TLI.useStackGuardMixFP())
3350 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3351
3352 // The target provides a guard check function to validate the guard value.
3353 // Generate a call to that function with the content of the guard slot as
3354 // argument.
3355 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3356 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3357
3359 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3360 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3361 Entry.IsInReg = true;
3362 Args.push_back(Entry);
3363
3366 .setChain(DAG.getEntryNode())
3367 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3368 getValue(GuardCheckFn), std::move(Args));
3369
3370 Chain = TLI.LowerCallTo(CLI).second;
3371 } else {
3373 CallOptions.setDiscardResult(true);
3374 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3375 {}, CallOptions, getCurSDLoc())
3376 .second;
3377 }
3378
3379 // Emit a trap instruction if we are required to do so.
3380 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3381 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3382 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3383
3384 DAG.setRoot(Chain);
3385}
3386
3387/// visitBitTestHeader - This function emits necessary code to produce value
3388/// suitable for "bit tests"
3390 MachineBasicBlock *SwitchBB) {
3391 SDLoc dl = getCurSDLoc();
3392
3393 // Subtract the minimum value.
3394 SDValue SwitchOp = getValue(B.SValue);
3395 EVT VT = SwitchOp.getValueType();
3396 SDValue RangeSub =
3397 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3398
3399 // Determine the type of the test operands.
3400 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3401 bool UsePtrType = false;
3402 if (!TLI.isTypeLegal(VT)) {
3403 UsePtrType = true;
3404 } else {
3405 for (const BitTestCase &Case : B.Cases)
3406 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3407 // Switch table case range are encoded into series of masks.
3408 // Just use pointer type, it's guaranteed to fit.
3409 UsePtrType = true;
3410 break;
3411 }
3412 }
3413 SDValue Sub = RangeSub;
3414 if (UsePtrType) {
3415 VT = TLI.getPointerTy(DAG.getDataLayout());
3416 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3417 }
3418
3419 B.RegVT = VT.getSimpleVT();
3420 B.Reg = FuncInfo.CreateReg(B.RegVT);
3421 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3422
3423 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3424
3425 if (!B.FallthroughUnreachable)
3426 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3427 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3428 SwitchBB->normalizeSuccProbs();
3429
3430 SDValue Root = CopyTo;
3431 if (!B.FallthroughUnreachable) {
3432 // Conditional branch to the default block.
3433 SDValue RangeCmp = DAG.getSetCC(dl,
3434 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3435 RangeSub.getValueType()),
3436 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3437 ISD::SETUGT);
3438
3439 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3440 DAG.getBasicBlock(B.Default));
3441 }
3442
3443 // Avoid emitting unnecessary branches to the next block.
3444 if (MBB != NextBlock(SwitchBB))
3445 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3446
3447 DAG.setRoot(Root);
3448}
3449
3450/// visitBitTestCase - this function produces one "bit test"
3452 MachineBasicBlock *NextMBB,
3453 BranchProbability BranchProbToNext,
3454 Register Reg, BitTestCase &B,
3455 MachineBasicBlock *SwitchBB) {
3456 SDLoc dl = getCurSDLoc();
3457 MVT VT = BB.RegVT;
3458 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3459 SDValue Cmp;
3460 unsigned PopCount = llvm::popcount(B.Mask);
3461 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3462 if (PopCount == 1) {
3463 // Testing for a single bit; just compare the shift count with what it
3464 // would need to be to shift a 1 bit in that position.
3465 Cmp = DAG.getSetCC(
3466 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3467 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3468 ISD::SETEQ);
3469 } else if (PopCount == BB.Range) {
3470 // There is only one zero bit in the range, test for it directly.
3471 Cmp = DAG.getSetCC(
3472 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3473 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3474 } else {
3475 // Make desired shift
3476 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3477 DAG.getConstant(1, dl, VT), ShiftOp);
3478
3479 // Emit bit tests and jumps
3480 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3481 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3482 Cmp = DAG.getSetCC(
3483 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3484 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3485 }
3486
3487 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3488 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3489 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3490 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3491 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3492 // one as they are relative probabilities (and thus work more like weights),
3493 // and hence we need to normalize them to let the sum of them become one.
3494 SwitchBB->normalizeSuccProbs();
3495
3496 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3497 MVT::Other, getControlRoot(),
3498 Cmp, DAG.getBasicBlock(B.TargetBB));
3499
3500 // Avoid emitting unnecessary branches to the next block.
3501 if (NextMBB != NextBlock(SwitchBB))
3502 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3503 DAG.getBasicBlock(NextMBB));
3504
3505 DAG.setRoot(BrAnd);
3506}
3507
3508void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3509 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3510
3511 // Retrieve successors. Look through artificial IR level blocks like
3512 // catchswitch for successors.
3513 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3514 const BasicBlock *EHPadBB = I.getSuccessor(1);
3515 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3516
3517 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3518 // have to do anything here to lower funclet bundles.
3519 failForInvalidBundles(I, "invokes",
3525
3526 const Value *Callee(I.getCalledOperand());
3527 const Function *Fn = dyn_cast<Function>(Callee);
3528 if (isa<InlineAsm>(Callee))
3529 visitInlineAsm(I, EHPadBB);
3530 else if (Fn && Fn->isIntrinsic()) {
3531 switch (Fn->getIntrinsicID()) {
3532 default:
3533 llvm_unreachable("Cannot invoke this intrinsic");
3534 case Intrinsic::donothing:
3535 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3536 case Intrinsic::seh_try_begin:
3537 case Intrinsic::seh_scope_begin:
3538 case Intrinsic::seh_try_end:
3539 case Intrinsic::seh_scope_end:
3540 if (EHPadMBB)
3541 // a block referenced by EH table
3542 // so dtor-funclet not removed by opts
3543 EHPadMBB->setMachineBlockAddressTaken();
3544 break;
3545 case Intrinsic::experimental_patchpoint_void:
3546 case Intrinsic::experimental_patchpoint:
3547 visitPatchpoint(I, EHPadBB);
3548 break;
3549 case Intrinsic::experimental_gc_statepoint:
3551 break;
3552 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3553 // but these intrinsics are special because they can be invoked, so we
3554 // manually lower it to a DAG node here.
3555 case Intrinsic::wasm_throw: {
3557 std::array<SDValue, 4> Ops = {
3558 getControlRoot(), // inchain for the terminator node
3559 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3560 TLI.getPointerTy(DAG.getDataLayout())),
3561 getValue(I.getArgOperand(0)), // tag
3562 getValue(I.getArgOperand(1)) // thrown value
3563 };
3564 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3565 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3566 break;
3567 }
3568 case Intrinsic::wasm_rethrow: {
3569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3570 std::array<SDValue, 2> Ops = {
3571 getControlRoot(), // inchain for the terminator node
3572 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3573 TLI.getPointerTy(DAG.getDataLayout()))};
3574 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3575 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3576 break;
3577 }
3578 // EH labels mark it as an invoke site, like a call.
3579 case Intrinsic::bpf_unwind_exit: {
3580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3581 MCSymbol *BeginLabel;
3582 std::array<SDValue, 2> Ops = {
3583 lowerStartEH(getControlRoot(), EHPadBB, BeginLabel),
3584 DAG.getTargetConstant(Intrinsic::bpf_unwind_exit, getCurSDLoc(),
3585 TLI.getPointerTy(DAG.getDataLayout()))};
3586 SDValue Chain =
3587 DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), MVT::Other, Ops);
3588 DAG.setRoot(lowerEndEH(Chain, &I, EHPadBB, BeginLabel));
3589 break;
3590 }
3591 }
3592 } else if (I.hasDeoptState()) {
3593 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3594 // Eventually we will support lowering the @llvm.experimental.deoptimize
3595 // intrinsic, and right now there are no plans to support other intrinsics
3596 // with deopt state.
3597 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3598 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3600 } else {
3601 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3602 }
3603
3604 // If the value of the invoke is used outside of its defining block, make it
3605 // available as a virtual register.
3606 // We already took care of the exported value for the statepoint instruction
3607 // during call to the LowerStatepoint.
3608 if (!isa<GCStatepointInst>(I)) {
3610 }
3611
3613 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3614 BranchProbability EHPadBBProb =
3615 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3617 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3618
3619 // Update successor info.
3620 addSuccessorWithProb(InvokeMBB, Return);
3621 for (auto &UnwindDest : UnwindDests) {
3622 UnwindDest.first->setIsEHPad();
3623 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3624 }
3625 InvokeMBB->normalizeSuccProbs();
3626
3627 // Drop into normal successor.
3628 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3629 DAG.getBasicBlock(Return)));
3630}
3631
3632/// The intrinsics currently supported by callbr are implicit control flow
3633/// intrinsics such as amdgcn.kill.
3634/// - they should be called (no "dontcall-" attributes)
3635/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3636/// - they do not need custom argument handling (no
3637/// TLI.CollectTargetIntrinsicOperands())
3638void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3639#ifndef NDEBUG
3641 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3642 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3643 assert(Infos.empty() && "Intrinsic touches memory");
3644#endif
3645
3646 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3647
3649 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3650 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3651
3652 // Create the node.
3653 SDValue Result =
3654 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3655 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3656
3657 setValue(&I, Result);
3658}
3659
3660void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3661 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3662
3663 if (I.isInlineAsm()) {
3664 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3665 // have to do anything here to lower funclet bundles.
3666 failForInvalidBundles(I, "callbrs",
3668 visitInlineAsm(I);
3669 } else {
3670 assert(!I.hasOperandBundles() &&
3671 "Can't have operand bundles for intrinsics");
3672 visitCallBrIntrinsic(I);
3673 }
3675
3676 // Retrieve successors.
3677 SmallPtrSet<BasicBlock *, 8> Dests;
3678 Dests.insert(I.getDefaultDest());
3679 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3680
3681 // Update successor info.
3682 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3683 // TODO: For most of the cases where there is an intrinsic callbr, we're
3684 // having exactly one indirect target, which will be unreachable. As soon as
3685 // this changes, we might need to enhance
3686 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3687 // intrinsic indirect branches.
3688 if (I.isInlineAsm()) {
3689 for (BasicBlock *Dest : I.getIndirectDests()) {
3690 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3691 Target->setIsInlineAsmBrIndirectTarget();
3692 // If we introduce a type of asm goto statement that is permitted to use
3693 // an indirect call instruction to jump to its labels, then we should add
3694 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3695 // target block as requiring a BTI.
3696
3697 Target->setLabelMustBeEmitted();
3698 // Don't add duplicate machine successors.
3699 if (Dests.insert(Dest).second)
3700 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3701 }
3702 }
3703 CallBrMBB->normalizeSuccProbs();
3704
3705 // Drop into default successor.
3706 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3707 MVT::Other, getControlRoot(),
3708 DAG.getBasicBlock(Return)));
3709}
3710
3711void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3712 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3713}
3714
3715void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3716 assert(FuncInfo.MBB->isEHPad() &&
3717 "Call to landingpad not in landing pad!");
3718
3719 // If there aren't registers to copy the values into (e.g., during SjLj
3720 // exceptions), then don't bother to create these DAG nodes.
3721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3722 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3723 if (TLI.getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn) ==
3724 0 &&
3726 PersonalityFn) == 0)
3727 return;
3728
3729 // If landingpad's return type is token type, we don't create DAG nodes
3730 // for its exception pointer and selector value. The extraction of exception
3731 // pointer or selector value from token type landingpads is not currently
3732 // supported.
3733 if (LP.getType()->isTokenTy())
3734 return;
3735
3736 // LangRef leaves the result type target-specific, so diagnose types this
3737 // lowering cannot represent instead of asserting.
3738 SDLoc dl = getCurSDLoc();
3740 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3741 *LP.getFunction(),
3742 "landingpad result type must be a struct of an exception pointer and "
3743 "an integer selector",
3744 dl.getDebugLoc()));
3745 setValueToPoison(&LP, dl);
3746 return;
3747 }
3748
3749 SmallVector<EVT, 2> ValueVTs;
3750 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3751 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3752
3753 // Get the two live-in registers as SDValues. The physregs have already been
3754 // copied into virtual registers.
3755 SDValue Ops[2];
3756 if (FuncInfo.ExceptionPointerVirtReg) {
3757 Ops[0] = DAG.getZExtOrTrunc(
3758 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3759 FuncInfo.ExceptionPointerVirtReg,
3760 TLI.getPointerTy(DAG.getDataLayout())),
3761 dl, ValueVTs[0]);
3762 } else {
3763 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3764 }
3765 Ops[1] = DAG.getZExtOrTrunc(
3766 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3767 FuncInfo.ExceptionSelectorVirtReg,
3768 TLI.getPointerTy(DAG.getDataLayout())),
3769 dl, ValueVTs[1]);
3770
3771 // Merge into one.
3772 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3773 DAG.getVTList(ValueVTs), Ops);
3774 setValue(&LP, Res);
3775}
3776
3779 // Update JTCases.
3780 for (JumpTableBlock &JTB : SL->JTCases)
3781 if (JTB.first.HeaderBB == First)
3782 JTB.first.HeaderBB = Last;
3783
3784 // Update BitTestCases.
3785 for (BitTestBlock &BTB : SL->BitTestCases)
3786 if (BTB.Parent == First)
3787 BTB.Parent = Last;
3788}
3789
3790void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3791 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3792
3793 // Update machine-CFG edges with unique successors.
3795 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3796 BasicBlock *BB = I.getSuccessor(i);
3797 bool Inserted = Done.insert(BB).second;
3798 if (!Inserted)
3799 continue;
3800
3801 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3802 addSuccessorWithProb(IndirectBrMBB, Succ);
3803 }
3804 IndirectBrMBB->normalizeSuccProbs();
3805
3807 MVT::Other, getControlRoot(),
3808 getValue(I.getAddress())));
3809}
3810
3811void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3812 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3813 DAG.getTarget().Options.NoTrapAfterNoreturn))
3814 return;
3815
3816 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3817}
3818
3819void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3820 SDNodeFlags Flags;
3821 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3822 Flags.copyFMF(*FPOp);
3823
3824 SDValue Op = getValue(I.getOperand(0));
3825 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3826 Op, Flags);
3827 setValue(&I, UnNodeValue);
3828}
3829
3830void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3831 SDNodeFlags Flags;
3832 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3833 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3834 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3835 }
3836 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3837 Flags.setExact(ExactOp->isExact());
3838 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3839 Flags.setDisjoint(DisjointOp->isDisjoint());
3840 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3841 Flags.copyFMF(*FPOp);
3842
3843 SDValue Op1 = getValue(I.getOperand(0));
3844 SDValue Op2 = getValue(I.getOperand(1));
3845 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3846 Op1, Op2, Flags);
3847 setValue(&I, BinNodeValue);
3848}
3849
3850void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3851 SDValue Op1 = getValue(I.getOperand(0));
3852 SDValue Op2 = getValue(I.getOperand(1));
3853
3854 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3855 Op1.getValueType(), DAG.getDataLayout());
3856
3857 // Coerce the shift amount to the right type if we can. This exposes the
3858 // truncate or zext to optimization early.
3859 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3861 "Unexpected shift type");
3862 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3863 }
3864
3865 bool nuw = false;
3866 bool nsw = false;
3867 bool exact = false;
3868
3869 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3870
3871 if (const OverflowingBinaryOperator *OFBinOp =
3873 nuw = OFBinOp->hasNoUnsignedWrap();
3874 nsw = OFBinOp->hasNoSignedWrap();
3875 }
3876 if (const PossiblyExactOperator *ExactOp =
3878 exact = ExactOp->isExact();
3879 }
3880 SDNodeFlags Flags;
3881 Flags.setExact(exact);
3882 Flags.setNoSignedWrap(nsw);
3883 Flags.setNoUnsignedWrap(nuw);
3884 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3885 Flags);
3886 setValue(&I, Res);
3887}
3888
3889void SelectionDAGBuilder::visitSDiv(const User &I) {
3890 SDValue Op1 = getValue(I.getOperand(0));
3891 SDValue Op2 = getValue(I.getOperand(1));
3892
3893 SDNodeFlags Flags;
3894 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3895 cast<PossiblyExactOperator>(&I)->isExact());
3896 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3897 Op2, Flags));
3898}
3899
3900void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3901 ICmpInst::Predicate predicate = I.getPredicate();
3902 SDValue Op1 = getValue(I.getOperand(0));
3903 SDValue Op2 = getValue(I.getOperand(1));
3904 ISD::CondCode Opcode = getICmpCondCode(predicate);
3905
3906 auto &TLI = DAG.getTargetLoweringInfo();
3907 EVT MemVT =
3908 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3909
3910 // If a pointer's DAG type is larger than its memory type then the DAG values
3911 // are zero-extended. This breaks signed comparisons so truncate back to the
3912 // underlying type before doing the compare.
3913 if (Op1.getValueType() != MemVT) {
3914 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3915 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3916 }
3917
3918 SDNodeFlags Flags;
3919 Flags.setSameSign(I.hasSameSign());
3920
3921 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3922 I.getType());
3923 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3924 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3925}
3926
3927void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3928 FCmpInst::Predicate predicate = I.getPredicate();
3929 SDValue Op1 = getValue(I.getOperand(0));
3930 SDValue Op2 = getValue(I.getOperand(1));
3931
3932 ISD::CondCode Condition = getFCmpCondCode(predicate);
3933 auto *FPMO = cast<FPMathOperator>(&I);
3934 if (FPMO->hasNoNaNs() ||
3935 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3936 Condition = getFCmpCodeWithoutNaN(Condition);
3937
3938 SDNodeFlags Flags;
3939 Flags.copyFMF(*FPMO);
3940
3941 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3942 I.getType());
3943 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3944 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3945}
3946
3947// Check if the condition of the select has one use or two users that are both
3948// selects with the same condition.
3949static bool hasOnlySelectUsers(const Value *Cond) {
3950 return llvm::all_of(Cond->users(), [](const Value *V) {
3951 return isa<SelectInst>(V);
3952 });
3953}
3954
3955void SelectionDAGBuilder::visitSelect(const User &I) {
3956 SmallVector<EVT, 4> ValueVTs;
3957 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3958 ValueVTs);
3959 unsigned NumValues = ValueVTs.size();
3960 if (NumValues == 0) return;
3961
3963 SDValue Cond = getValue(I.getOperand(0));
3964 SDValue LHSVal = getValue(I.getOperand(1));
3965 SDValue RHSVal = getValue(I.getOperand(2));
3966 SmallVector<SDValue, 1> BaseOps(1, Cond);
3968 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3969
3970 bool IsUnaryAbs = false;
3971 bool Negate = false;
3972
3973 SDNodeFlags Flags;
3974 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3975 Flags.copyFMF(*FPOp);
3976
3977 Flags.setUnpredictable(
3978 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3979
3980 // Min/max matching is only viable if all output VTs are the same.
3981 if (all_equal(ValueVTs)) {
3982 EVT VT = ValueVTs[0];
3983 LLVMContext &Ctx = *DAG.getContext();
3984 auto &TLI = DAG.getTargetLoweringInfo();
3985
3986 // We care about the legality of the operation after it has been type
3987 // legalized.
3989 VT = TLI.getTypeToTransformTo(Ctx, VT);
3990
3991 // If the vselect is legal, assume we want to leave this as a vector setcc +
3992 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3993 // min/max is legal on the scalar type.
3994 bool UseScalarMinMax = VT.isVector() &&
3996
3997 // ValueTracking's select pattern matching does not account for -0.0,
3998 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3999 // -0.0 is less than +0.0.
4000 const Value *LHS, *RHS;
4001 auto SPR = matchSelectPattern(&I, LHS, RHS);
4003 switch (SPR.Flavor) {
4004 case SPF_UMAX: Opc = ISD::UMAX; break;
4005 case SPF_UMIN: Opc = ISD::UMIN; break;
4006 case SPF_SMAX: Opc = ISD::SMAX; break;
4007 case SPF_SMIN: Opc = ISD::SMIN; break;
4008 case SPF_FMINNUM:
4010 break;
4011
4012 switch (SPR.NaNBehavior) {
4013 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4014 case SPNB_RETURNS_ANY:
4015 case SPNB_RETURNS_NAN:
4016 break;
4017 case SPNB_RETURNS_OTHER:
4019 Flags.setNoSignedZeros(true);
4020 break;
4021 }
4022 break;
4023 case SPF_FMAXNUM:
4025 break;
4026
4027 switch (SPR.NaNBehavior) {
4028 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4029 case SPNB_RETURNS_NAN:
4030 case SPNB_RETURNS_ANY:
4031 break;
4032 case SPNB_RETURNS_OTHER:
4034 Flags.setNoSignedZeros(true);
4035 break;
4036 }
4037 break;
4038 case SPF_NABS:
4039 Negate = true;
4040 [[fallthrough]];
4041 case SPF_ABS:
4042 IsUnaryAbs = true;
4043 Opc = ISD::ABS;
4044 break;
4045 default: break;
4046 }
4047
4048 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
4050 (UseScalarMinMax &&
4052 // If the underlying comparison instruction is used by any other
4053 // instruction, the consumed instructions won't be destroyed, so it is
4054 // not profitable to convert to a min/max.
4056 OpCode = Opc;
4057 LHSVal = getValue(LHS);
4058 RHSVal = getValue(RHS);
4059 BaseOps.clear();
4060 }
4061
4062 if (IsUnaryAbs) {
4063 OpCode = Opc;
4064 LHSVal = getValue(LHS);
4065 BaseOps.clear();
4066 }
4067 }
4068
4069 if (IsUnaryAbs) {
4070 for (unsigned i = 0; i != NumValues; ++i) {
4071 SDLoc dl = getCurSDLoc();
4072 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
4073 Values[i] =
4074 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
4075 if (Negate)
4076 Values[i] = DAG.getNegative(Values[i], dl, VT);
4077 }
4078 } else {
4079 for (unsigned i = 0; i != NumValues; ++i) {
4080 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
4081 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
4082 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
4083 Values[i] = DAG.getNode(
4084 OpCode, getCurSDLoc(),
4085 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
4086 }
4087 }
4088
4090 DAG.getVTList(ValueVTs), Values));
4091}
4092
4093void SelectionDAGBuilder::visitTrunc(const User &I) {
4094 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4095 SDValue N = getValue(I.getOperand(0));
4096 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4097 I.getType());
4098 SDNodeFlags Flags;
4099 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4100 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4101 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4102 }
4103
4104 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4105}
4106
4107void SelectionDAGBuilder::visitZExt(const User &I) {
4108 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4109 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4110 SDValue N = getValue(I.getOperand(0));
4111 auto &TLI = DAG.getTargetLoweringInfo();
4112 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4113
4114 SDNodeFlags Flags;
4115 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4116 Flags.setNonNeg(PNI->hasNonNeg());
4117
4118 // Eagerly use nonneg information to canonicalize towards sign_extend if
4119 // that is the target's preference.
4120 // TODO: Let the target do this later.
4121 if (Flags.hasNonNeg() &&
4122 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4123 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4124 return;
4125 }
4126
4127 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4128}
4129
4130void SelectionDAGBuilder::visitSExt(const User &I) {
4131 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4132 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4133 SDValue N = getValue(I.getOperand(0));
4134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4135 I.getType());
4136 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4137}
4138
4139void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4140 // FPTrunc is never a no-op cast, no need to check
4141 SDValue N = getValue(I.getOperand(0));
4142 SDLoc dl = getCurSDLoc();
4143 SDNodeFlags Flags;
4144 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4145 Flags.copyFMF(*FPOp);
4146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4147 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4148 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4149 DAG.getTargetConstant(
4150 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4151 Flags));
4152}
4153
4154void SelectionDAGBuilder::visitFPExt(const User &I) {
4155 // FPExt is never a no-op cast, no need to check
4156 SDValue N = getValue(I.getOperand(0));
4157 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4158 I.getType());
4159 SDNodeFlags Flags;
4160 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4161 Flags.copyFMF(*FPOp);
4162 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4163}
4164
4165void SelectionDAGBuilder::visitFPToUI(const User &I) {
4166 // FPToUI is never a no-op cast, no need to check
4167 SDValue N = getValue(I.getOperand(0));
4168 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4169 I.getType());
4170 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4171}
4172
4173void SelectionDAGBuilder::visitFPToSI(const User &I) {
4174 // FPToSI is never a no-op cast, no need to check
4175 SDValue N = getValue(I.getOperand(0));
4176 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4177 I.getType());
4178 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4179}
4180
4181void SelectionDAGBuilder::visitUIToFP(const User &I) {
4182 // UIToFP is never a no-op cast, no need to check
4183 SDValue N = getValue(I.getOperand(0));
4184 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4185 I.getType());
4186 SDNodeFlags Flags;
4187 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4188 Flags.copyFMF(*cast<FPMathOperator>(&I));
4189
4190 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4191}
4192
4193void SelectionDAGBuilder::visitSIToFP(const User &I) {
4194 // SIToFP is never a no-op cast, no need to check
4195 SDValue N = getValue(I.getOperand(0));
4196 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4197 I.getType());
4198 SDNodeFlags Flags;
4199 Flags.copyFMF(*cast<FPMathOperator>(&I));
4200
4201 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4202}
4203
4204void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4205 SDValue N = getValue(I.getOperand(0));
4206 // By definition the type of the ptrtoaddr must be equal to the address type.
4207 const auto &TLI = DAG.getTargetLoweringInfo();
4208 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4209 // The address width must be smaller or equal to the pointer representation
4210 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4211 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4212 setValue(&I, N);
4213}
4214
4215void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4216 // What to do depends on the size of the integer and the size of the pointer.
4217 // We can either truncate, zero extend, or no-op, accordingly.
4218 SDValue N = getValue(I.getOperand(0));
4219 auto &TLI = DAG.getTargetLoweringInfo();
4220 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4221 I.getType());
4222 EVT PtrMemVT =
4223 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4224 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4225 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4226 setValue(&I, N);
4227}
4228
4229void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4230 // What to do depends on the size of the integer and the size of the pointer.
4231 // We can either truncate, zero extend, or no-op, accordingly.
4232 SDValue N = getValue(I.getOperand(0));
4233 auto &TLI = DAG.getTargetLoweringInfo();
4234 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4235 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4236 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4237 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4238 setValue(&I, N);
4239}
4240
4241void SelectionDAGBuilder::visitBitCast(const User &I) {
4242 SDValue N = getValue(I.getOperand(0));
4243 SDLoc dl = getCurSDLoc();
4244 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4245 I.getType());
4246
4247 // BitCast assures us that source and destination are the same size so this is
4248 // either a BITCAST or a no-op.
4249 if (DestVT != N.getValueType())
4250 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4251 DestVT, N)); // convert types.
4252 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4253 // might fold any kind of constant expression to an integer constant and that
4254 // is not what we are looking for. Only recognize a bitcast of a genuine
4255 // constant integer as an opaque constant.
4256 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4257 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4258 /*isOpaque*/true));
4259 else
4260 setValue(&I, N); // noop cast.
4261}
4262
4263void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4265 const Value *SV = I.getOperand(0);
4266 SDValue N = getValue(SV);
4267 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4268
4269 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4270 unsigned DestAS = I.getType()->getPointerAddressSpace();
4271
4272 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(), SrcAS, DestAS)) {
4273 SDNodeFlags Flags;
4274 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4275 Flags.setNonNull(ASC->hasNonNull());
4276 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4277 }
4278
4279 setValue(&I, N);
4280}
4281
4282void SelectionDAGBuilder::visitInsertElement(const User &I) {
4283 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4284 SDValue InVec = getValue(I.getOperand(0));
4285 SDValue InVal = getValue(I.getOperand(1));
4286 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4287 TLI.getVectorIdxTy(DAG.getDataLayout()));
4289 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4290 InVec, InVal, InIdx));
4291}
4292
4293void SelectionDAGBuilder::visitBitInsert(const User &I) {
4294 SDValue Base = getValue(I.getOperand(0));
4295 SDValue Val = getValue(I.getOperand(1));
4296 SDValue Offset = getValue(I.getOperand(2));
4297 EVT BaseVT = Base.getValueType();
4298 EVT ValVT = Val.getValueType();
4299 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4300 SDLoc dl = getCurSDLoc();
4301
4302 assert(BaseVT.getSizeInBits() >= ValVT.getSizeInBits() &&
4303 "bitinsert val wider than base should be rejected by verifier");
4304
4305 // If Val is a float, cast it to an integer of the same bitwidth
4306 // so DAG.getZExtOrTrunc can process it safely.
4307 if (!ValVT.isInteger()) {
4308 ValVT = ValVT.changeTypeToInteger();
4309 Val = DAG.getBitcast(ValVT, Val);
4310 }
4311
4312 // Legalize shift amount to the target's shift amount type.
4313 EVT ShiftAmtTy = TLI.getShiftAmountTy(BaseVT, DAG.getDataLayout());
4314 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4315
4316 unsigned BaseBitWidth = BaseVT.getScalarSizeInBits();
4317 unsigned ValBitWidth = ValVT.getScalarSizeInBits();
4318 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4319 SDValue ShiftedMask =
4320 DAG.getNode(ISD::SHL, dl, BaseVT, DAG.getConstant(InsertMask, dl, BaseVT),
4321 LegalShiftAmount);
4322 SDValue ClearMask = DAG.getNOT(dl, ShiftedMask, BaseVT);
4323 SDValue ClearedBase = DAG.getNode(ISD::AND, dl, BaseVT, Base, ClearMask);
4324
4325 SDValue ExtVal = DAG.getZExtOrTrunc(Val, dl, BaseVT);
4326 SDValue ShiftedVal =
4327 DAG.getNode(ISD::SHL, dl, BaseVT, ExtVal, LegalShiftAmount);
4328 SDValue Result = DAG.getNode(ISD::OR, dl, BaseVT, ClearedBase, ShiftedVal);
4329 setValue(&I, Result);
4330}
4331
4332void SelectionDAGBuilder::visitBitExtract(const User &I) {
4333 SDValue Src = getValue(I.getOperand(0));
4334 SDValue Offset = getValue(I.getOperand(1));
4335 EVT SrcVT = Src.getValueType();
4336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4337 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4338 SDLoc dl = getCurSDLoc();
4339
4340 assert(ResultVT.getSizeInBits() <= SrcVT.getSizeInBits() &&
4341 "bitextract result wider than source should be rejected by verifier");
4342
4343 // Legalize shift amount to the target's shift amount type.
4344 EVT ShiftAmtTy = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
4345 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4346
4347 // Shift right by Offset - brings target field to bit 0
4348 SDValue Shifted = DAG.getNode(ISD::SRL, dl, SrcVT, Src, LegalShiftAmount);
4349
4351 if (!ResultVT.isInteger()) {
4352 // Drop into the integer domain to safely truncate the shifted bits
4353 EVT IntResultVT = ResultVT.changeTypeToInteger();
4354 Result = DAG.getNode(ISD::TRUNCATE, dl, IntResultVT, Shifted);
4355 Result = DAG.getBitcast(ResultVT, Result);
4356 } else {
4357 // Normal integer path
4358 Result = DAG.getNode(ISD::TRUNCATE, dl, ResultVT, Shifted);
4359 }
4360
4361 setValue(&I, Result);
4362}
4363
4364void SelectionDAGBuilder::visitExtractElement(const User &I) {
4365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4366 SDValue InVec = getValue(I.getOperand(0));
4367 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4368 TLI.getVectorIdxTy(DAG.getDataLayout()));
4370 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4371 InVec, InIdx));
4372}
4373
4374void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4375 SDValue Src1 = getValue(I.getOperand(0));
4376 SDValue Src2 = getValue(I.getOperand(1));
4377 ArrayRef<int> Mask;
4378 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4379 Mask = SVI->getShuffleMask();
4380 else
4381 Mask = cast<ConstantExpr>(I).getShuffleMask();
4382 SDLoc DL = getCurSDLoc();
4383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4384 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4385 EVT SrcVT = Src1.getValueType();
4386
4387 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4388 // Canonical splat form of first element of first input vector.
4389 SDValue FirstElt =
4390 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4391 DAG.getVectorIdxConstant(0, DL));
4392 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4393 return;
4394 }
4395
4396 // For now, we only handle splats for scalable vectors.
4397 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4398 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4399 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4400
4401 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4402 unsigned MaskNumElts = Mask.size();
4403
4404 if (SrcNumElts == MaskNumElts) {
4405 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4406 return;
4407 }
4408
4409 // Normalize the shuffle vector since mask and vector length don't match.
4410 if (SrcNumElts < MaskNumElts) {
4411 // Mask is longer than the source vectors. We can use concatenate vector to
4412 // make the mask and vectors lengths match.
4413
4414 if (MaskNumElts % SrcNumElts == 0) {
4415 // Mask length is a multiple of the source vector length.
4416 // Check if the shuffle is some kind of concatenation of the input
4417 // vectors.
4418 unsigned NumConcat = MaskNumElts / SrcNumElts;
4419 bool IsConcat = true;
4420 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4421 for (unsigned i = 0; i != MaskNumElts; ++i) {
4422 int Idx = Mask[i];
4423 if (Idx < 0)
4424 continue;
4425 // Ensure the indices in each SrcVT sized piece are sequential and that
4426 // the same source is used for the whole piece.
4427 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4428 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4429 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4430 IsConcat = false;
4431 break;
4432 }
4433 // Remember which source this index came from.
4434 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4435 }
4436
4437 // The shuffle is concatenating multiple vectors together. Just emit
4438 // a CONCAT_VECTORS operation.
4439 if (IsConcat) {
4440 SmallVector<SDValue, 8> ConcatOps;
4441 for (auto Src : ConcatSrcs) {
4442 if (Src < 0)
4443 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4444 else if (Src == 0)
4445 ConcatOps.push_back(Src1);
4446 else
4447 ConcatOps.push_back(Src2);
4448 }
4449 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4450 return;
4451 }
4452 }
4453
4454 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4455 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4456 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4457 PaddedMaskNumElts);
4458
4459 // Pad both vectors with undefs to make them the same length as the mask.
4460 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4461
4462 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4463 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4464 MOps1[0] = Src1;
4465 MOps2[0] = Src2;
4466
4467 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4468 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4469
4470 // Readjust mask for new input vector length.
4471 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4472 for (unsigned i = 0; i != MaskNumElts; ++i) {
4473 int Idx = Mask[i];
4474 if (Idx >= (int)SrcNumElts)
4475 Idx -= SrcNumElts - PaddedMaskNumElts;
4476 MappedOps[i] = Idx;
4477 }
4478
4479 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4480
4481 // If the concatenated vector was padded, extract a subvector with the
4482 // correct number of elements.
4483 if (MaskNumElts != PaddedMaskNumElts)
4484 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4485 DAG.getVectorIdxConstant(0, DL));
4486
4487 setValue(&I, Result);
4488 return;
4489 }
4490
4491 assert(SrcNumElts > MaskNumElts);
4492
4493 // Analyze the access pattern of the vector to see if we can extract
4494 // two subvectors and do the shuffle.
4495 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4496 bool CanExtract = true;
4497 for (int Idx : Mask) {
4498 unsigned Input = 0;
4499 if (Idx < 0)
4500 continue;
4501
4502 if (Idx >= (int)SrcNumElts) {
4503 Input = 1;
4504 Idx -= SrcNumElts;
4505 }
4506
4507 // If all the indices come from the same MaskNumElts sized portion of
4508 // the sources we can use extract. Also make sure the extract wouldn't
4509 // extract past the end of the source.
4510 int NewStartIdx = alignDown(Idx, MaskNumElts);
4511 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4512 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4513 CanExtract = false;
4514 // Make sure we always update StartIdx as we use it to track if all
4515 // elements are undef.
4516 StartIdx[Input] = NewStartIdx;
4517 }
4518
4519 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4520 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4521 return;
4522 }
4523 if (CanExtract) {
4524 // Extract appropriate subvector and generate a vector shuffle
4525 for (unsigned Input = 0; Input < 2; ++Input) {
4526 SDValue &Src = Input == 0 ? Src1 : Src2;
4527 if (StartIdx[Input] < 0)
4528 Src = DAG.getUNDEF(VT);
4529 else {
4530 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4531 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4532 }
4533 }
4534
4535 // Calculate new mask.
4536 SmallVector<int, 8> MappedOps(Mask);
4537 for (int &Idx : MappedOps) {
4538 if (Idx >= (int)SrcNumElts)
4539 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4540 else if (Idx >= 0)
4541 Idx -= StartIdx[0];
4542 }
4543
4544 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4545 return;
4546 }
4547
4548 // We can't use either concat vectors or extract subvectors so fall back to
4549 // replacing the shuffle with extract and build vector.
4550 // to insert and build vector.
4551 EVT EltVT = VT.getVectorElementType();
4553 for (int Idx : Mask) {
4554 SDValue Res;
4555
4556 if (Idx < 0) {
4557 Res = DAG.getUNDEF(EltVT);
4558 } else {
4559 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4560 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4561
4562 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4563 DAG.getVectorIdxConstant(Idx, DL));
4564 }
4565
4566 Ops.push_back(Res);
4567 }
4568
4569 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4570}
4571
4572void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4573 ArrayRef<unsigned> Indices = I.getIndices();
4574 const Value *Op0 = I.getOperand(0);
4575 const Value *Op1 = I.getOperand(1);
4576 Type *AggTy = I.getType();
4577 Type *ValTy = Op1->getType();
4578 bool IntoUndef = isa<UndefValue>(Op0);
4579 bool FromUndef = isa<UndefValue>(Op1);
4580
4581 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4582
4583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4584 SmallVector<EVT, 4> AggValueVTs;
4585 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4586 SmallVector<EVT, 4> ValValueVTs;
4587 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4588
4589 unsigned NumAggValues = AggValueVTs.size();
4590 unsigned NumValValues = ValValueVTs.size();
4591 SmallVector<SDValue, 4> Values(NumAggValues);
4592
4593 // Ignore an insertvalue that produces an empty object
4594 if (!NumAggValues) {
4595 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4596 return;
4597 }
4598
4599 SDValue Agg = getValue(Op0);
4600 unsigned i = 0;
4601 // Copy the beginning value(s) from the original aggregate.
4602 for (; i != LinearIndex; ++i)
4603 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4604 SDValue(Agg.getNode(), Agg.getResNo() + i);
4605 // Copy values from the inserted value(s).
4606 if (NumValValues) {
4607 SDValue Val = getValue(Op1);
4608 for (; i != LinearIndex + NumValValues; ++i)
4609 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4610 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4611 }
4612 // Copy remaining value(s) from the original aggregate.
4613 for (; i != NumAggValues; ++i)
4614 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4615 SDValue(Agg.getNode(), Agg.getResNo() + i);
4616
4618 DAG.getVTList(AggValueVTs), Values));
4619}
4620
4621void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4622 ArrayRef<unsigned> Indices = I.getIndices();
4623 const Value *Op0 = I.getOperand(0);
4624 Type *AggTy = Op0->getType();
4625 Type *ValTy = I.getType();
4626 bool OutOfUndef = isa<UndefValue>(Op0);
4627
4628 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4629
4630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4631 SmallVector<EVT, 4> ValValueVTs;
4632 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4633
4634 unsigned NumValValues = ValValueVTs.size();
4635
4636 // Ignore a extractvalue that produces an empty object
4637 if (!NumValValues) {
4638 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4639 return;
4640 }
4641
4642 SmallVector<SDValue, 4> Values(NumValValues);
4643
4644 SDValue Agg = getValue(Op0);
4645 // Copy out the selected value(s).
4646 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4647 Values[i - LinearIndex] =
4648 OutOfUndef ?
4649 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4650 SDValue(Agg.getNode(), Agg.getResNo() + i);
4651
4653 DAG.getVTList(ValValueVTs), Values));
4654}
4655
4656void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4657 Value *Op0 = I.getOperand(0);
4658 // Note that the pointer operand may be a vector of pointers. Take the scalar
4659 // element which holds a pointer.
4660 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4661 SDValue N = getValue(Op0);
4662 SDLoc dl = getCurSDLoc();
4663 auto &TLI = DAG.getTargetLoweringInfo();
4664 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4665
4666 // For a vector GEP, keep the prefix scalar as long as possible, then
4667 // convert any scalars encountered after the first vector operand to vectors.
4668 bool IsVectorGEP = I.getType()->isVectorTy();
4669 ElementCount VectorElementCount =
4670 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4672
4674 GTI != E; ++GTI) {
4675 const Value *Idx = GTI.getOperand();
4676 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4677 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4678 if (Field) {
4679 // N = N + Offset
4681 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4682
4683 // In an inbounds GEP with an offset that is nonnegative even when
4684 // interpreted as signed, assume there is no unsigned overflow.
4685 SDNodeFlags Flags;
4686 if (NW.hasNoUnsignedWrap() ||
4687 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4689 Flags.setInBounds(NW.isInBounds());
4690
4691 N = DAG.getMemBasePlusOffset(
4692 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4693 }
4694 } else {
4695 // IdxSize is the width of the arithmetic according to IR semantics.
4696 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4697 // (and fix up the result later).
4698 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4699 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4700 TypeSize ElementSize =
4701 GTI.getSequentialElementStride(DAG.getDataLayout());
4702 // We intentionally mask away the high bits here; ElementSize may not
4703 // fit in IdxTy.
4704 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4705 /*isSigned=*/false, /*implicitTrunc=*/true);
4706 bool ElementScalable = ElementSize.isScalable();
4707
4708 // If this is a scalar constant or a splat vector of constants,
4709 // handle it quickly.
4710 const auto *C = dyn_cast<Constant>(Idx);
4711 if (C && isa<VectorType>(C->getType()))
4712 C = C->getSplatValue();
4713
4714 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4715 if (CI && CI->isZero())
4716 continue;
4717 if (CI && !ElementScalable) {
4718 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4719 LLVMContext &Context = *DAG.getContext();
4720 SDValue OffsVal;
4721 if (N.getValueType().isVector())
4722 OffsVal = DAG.getConstant(
4723 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4724 else
4725 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4726
4727 // In an inbounds GEP with an offset that is nonnegative even when
4728 // interpreted as signed, assume there is no unsigned overflow.
4729 SDNodeFlags Flags;
4730 if (NW.hasNoUnsignedWrap() ||
4731 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4732 Flags.setNoUnsignedWrap(true);
4733 Flags.setInBounds(NW.isInBounds());
4734
4735 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4736
4737 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4738 continue;
4739 }
4740
4741 // N = N + Idx * ElementMul;
4742 SDValue IdxN = getValue(Idx);
4743
4744 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4745 if (N.getValueType().isVector()) {
4746 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4747 VectorElementCount);
4748 IdxN = DAG.getSplat(VT, dl, IdxN);
4749 } else {
4750 EVT VT =
4751 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4752 N = DAG.getSplat(VT, dl, N);
4753 }
4754 }
4755
4756 // If the index is smaller or larger than intptr_t, truncate or extend
4757 // it.
4758 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4759
4760 SDNodeFlags ScaleFlags;
4761 // The multiplication of an index by the type size does not wrap the
4762 // pointer index type in a signed sense (mul nsw).
4764
4765 // The multiplication of an index by the type size does not wrap the
4766 // pointer index type in an unsigned sense (mul nuw).
4767 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4768
4769 if (ElementScalable) {
4770 EVT VScaleTy = N.getValueType().getScalarType();
4771 SDValue VScale = DAG.getNode(
4772 ISD::VSCALE, dl, VScaleTy,
4773 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4774 if (N.getValueType().isVector())
4775 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4776 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4777 ScaleFlags);
4778 } else {
4779 // If this is a multiply by a power of two, turn it into a shl
4780 // immediately. This is a very common case.
4781 if (ElementMul != 1) {
4782 if (ElementMul.isPowerOf2()) {
4783 unsigned Amt = ElementMul.logBase2();
4784 IdxN = DAG.getNode(
4785 ISD::SHL, dl, N.getValueType(), IdxN,
4786 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4787 ScaleFlags);
4788 } else {
4789 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4790 IdxN.getValueType());
4791 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4792 ScaleFlags);
4793 }
4794 }
4795 }
4796
4797 // The successive addition of the current address, truncated to the
4798 // pointer index type and interpreted as an unsigned number, and each
4799 // offset, also interpreted as an unsigned number, does not wrap the
4800 // pointer index type (add nuw).
4801 SDNodeFlags AddFlags;
4802 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4803 AddFlags.setInBounds(NW.isInBounds());
4804
4805 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4806 }
4807 }
4808
4809 if (IsVectorGEP && !N.getValueType().isVector()) {
4810 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4811 N = DAG.getSplat(VT, dl, N);
4812 }
4813
4814 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4815 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4816 if (IsVectorGEP) {
4817 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4818 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4819 }
4820
4821 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4822 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4823
4824 setValue(&I, N);
4825}
4826
4827void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4828 // If this is a fixed sized alloca in the entry block of the function,
4829 // allocate it statically on the stack.
4830 if (FuncInfo.StaticAllocaMap.count(&I))
4831 return; // getValue will auto-populate this.
4832
4833 SDLoc dl = getCurSDLoc();
4834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4835 auto &DL = DAG.getDataLayout();
4836 TypeSize TySize = I.getAllocationBaseSize(DL);
4837 MaybeAlign Alignment = I.getAlign();
4838
4839 SDValue AllocSize = getValue(I.getArraySize());
4840
4841 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4842 if (AllocSize.getValueType() != IntPtr)
4843 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4844
4845 AllocSize = DAG.getNode(
4846 ISD::MUL, dl, IntPtr, AllocSize,
4847 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4848
4849 // Handle alignment. If the requested alignment is less than or equal to
4850 // the stack alignment, ignore it. If the size is greater than or equal to
4851 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4852 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4853 if (*Alignment <= StackAlign)
4854 Alignment = std::nullopt;
4855
4856 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4857 // Round the size of the allocation up to the stack alignment size
4858 // by add SA-1 to the size. This doesn't overflow because we're computing
4859 // an address inside an alloca.
4860 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4861 DAG.getConstant(StackAlignMask, dl, IntPtr),
4863
4864 // Mask out the low bits for alignment purposes.
4865 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4866 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4867
4868 SDValue Ops[] = {
4869 getRoot(), AllocSize,
4870 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4871 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4872 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4873 setValue(&I, DSA);
4874 DAG.setRoot(DSA.getValue(1));
4875
4876 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4877}
4878
4879static const MDNode *getRangeMetadata(const Instruction &I) {
4880 return I.getMetadata(LLVMContext::MD_range);
4881}
4882
4883static std::optional<ConstantRange> getRange(const Instruction &I) {
4884 if (const auto *CB = dyn_cast<CallBase>(&I))
4885 if (std::optional<ConstantRange> CR = CB->getRange())
4886 return CR;
4887 if (const MDNode *Range = getRangeMetadata(I))
4889 return std::nullopt;
4890}
4891
4893 if (const auto *CB = dyn_cast<CallBase>(&I))
4894 return CB->getRetNoFPClass();
4895 return fcNone;
4896}
4897
4898void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4899 if (I.isAtomic())
4900 return visitAtomicLoad(I);
4901
4902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4903 const Value *SV = I.getOperand(0);
4904 if (TLI.supportSwiftError()) {
4905 // Swifterror values can come from either a function parameter with
4906 // swifterror attribute or an alloca with swifterror attribute.
4907 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4908 if (Arg->hasSwiftErrorAttr())
4909 return visitLoadFromSwiftError(I);
4910 }
4911
4912 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4913 if (Alloca->isSwiftError())
4914 return visitLoadFromSwiftError(I);
4915 }
4916 }
4917
4918 SDValue Ptr = getValue(SV);
4919
4920 Type *Ty = I.getType();
4921 SmallVector<EVT, 4> ValueVTs, MemVTs;
4923 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4924 unsigned NumValues = ValueVTs.size();
4925 if (NumValues == 0)
4926 return;
4927
4928 Align Alignment = I.getAlign();
4929 AAMDNodes AAInfo = I.getAAMetadata();
4930 const MDNode *Ranges = getRangeMetadata(I);
4931 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4932 bool isVolatile = I.isVolatile();
4933 MachineMemOperand::Flags MMOFlags =
4934 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4935
4936 SDValue Root;
4937 bool ConstantMemory = false;
4938 if (isVolatile)
4939 // Serialize volatile loads with other side effects.
4940 Root = getRoot();
4941 else if (NumValues > MaxParallelChains)
4942 Root = getMemoryRoot();
4943 else if (BatchAA &&
4944 BatchAA->pointsToConstantMemory(MemoryLocation(
4945 SV,
4946 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4947 AAInfo))) {
4948 // Do not serialize (non-volatile) loads of constant memory with anything.
4949 Root = DAG.getEntryNode();
4950 ConstantMemory = true;
4952 } else {
4953 // Do not serialize non-volatile loads against each other.
4954 Root = DAG.getRoot();
4955 }
4956
4957 SDLoc dl = getCurSDLoc();
4958
4959 if (isVolatile)
4960 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4961
4963 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4964
4965 unsigned ChainI = 0;
4966 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4967 // Serializing loads here may result in excessive register pressure, and
4968 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4969 // could recover a bit by hoisting nodes upward in the chain by recognizing
4970 // they are side-effect free or do not alias. The optimizer should really
4971 // avoid this case by converting large object/array copies to llvm.memcpy
4972 // (MaxParallelChains should always remain as failsafe).
4973 if (ChainI == MaxParallelChains) {
4974 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4975 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4976 ArrayRef(Chains.data(), ChainI));
4977 Root = Chain;
4978 ChainI = 0;
4979 }
4980
4981 // TODO: MachinePointerInfo only supports a fixed length offset.
4982 MachinePointerInfo PtrInfo =
4983 !Offsets[i].isScalable() || Offsets[i].isZero()
4984 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4985 : MachinePointerInfo();
4986
4987 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4988 SDValue L =
4989 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4990 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4991 Chains[ChainI] = L.getValue(1);
4992
4993 if (MemVTs[i] != ValueVTs[i])
4994 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4995
4996 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4997 uint64_t FPTestInt =
4998 cast<ConstantInt>(
4999 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
5000 ->getZExtValue();
5001 if (FPTestInt != fcNone) {
5002 SDValue FPTestConst =
5003 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
5004 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
5005 FPTestConst);
5006 }
5007 }
5008 Values[i] = L;
5009 }
5010
5011 if (!ConstantMemory) {
5012 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5013 ArrayRef(Chains.data(), ChainI));
5014 if (isVolatile)
5015 DAG.setRoot(Chain);
5016 else
5017 PendingLoads.push_back(Chain);
5018 }
5019
5020 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
5021 DAG.getVTList(ValueVTs), Values));
5022}
5023
5024void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
5025 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5026 "call visitStoreToSwiftError when backend supports swifterror");
5027
5028 SmallVector<EVT, 4> ValueVTs;
5029 SmallVector<uint64_t, 4> Offsets;
5030 const Value *SrcV = I.getOperand(0);
5031 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5032 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5033 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5034 "expect a single EVT for swifterror");
5035
5036 SDValue Src = getValue(SrcV);
5037 // Create a virtual register, then update the virtual register.
5038 Register VReg =
5039 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
5040 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
5041 // Chain can be getRoot or getControlRoot.
5042 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
5043 SDValue(Src.getNode(), Src.getResNo()));
5044 DAG.setRoot(CopyNode);
5045}
5046
5047void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
5048 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5049 "call visitLoadFromSwiftError when backend supports swifterror");
5050
5051 assert(!I.isVolatile() &&
5052 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
5053 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
5054 "Support volatile, non temporal, invariant for load_from_swift_error");
5055
5056 const Value *SV = I.getOperand(0);
5057 Type *Ty = I.getType();
5058 assert(
5059 (!BatchAA ||
5060 !BatchAA->pointsToConstantMemory(MemoryLocation(
5061 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
5062 I.getAAMetadata()))) &&
5063 "load_from_swift_error should not be constant memory");
5064
5065 SmallVector<EVT, 4> ValueVTs;
5066 SmallVector<uint64_t, 4> Offsets;
5067 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
5068 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5069 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5070 "expect a single EVT for swifterror");
5071
5072 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
5073 SDValue L = DAG.getCopyFromReg(
5074 getRoot(), getCurSDLoc(),
5075 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
5076
5077 setValue(&I, L);
5078}
5079
5080void SelectionDAGBuilder::visitStore(const StoreInst &I) {
5081 if (I.isAtomic())
5082 return visitAtomicStore(I);
5083
5084 const Value *SrcV = I.getOperand(0);
5085 const Value *PtrV = I.getOperand(1);
5086
5087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5088 if (TLI.supportSwiftError()) {
5089 // Swifterror values can come from either a function parameter with
5090 // swifterror attribute or an alloca with swifterror attribute.
5091 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
5092 if (Arg->hasSwiftErrorAttr())
5093 return visitStoreToSwiftError(I);
5094 }
5095
5096 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
5097 if (Alloca->isSwiftError())
5098 return visitStoreToSwiftError(I);
5099 }
5100 }
5101
5102 SmallVector<EVT, 4> ValueVTs, MemVTs;
5104 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5105 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
5106 unsigned NumValues = ValueVTs.size();
5107 if (NumValues == 0)
5108 return;
5109
5110 // Get the lowered operands. Note that we do this after
5111 // checking if NumResults is zero, because with zero results
5112 // the operands won't have values in the map.
5113 SDValue Src = getValue(SrcV);
5114 SDValue Ptr = getValue(PtrV);
5115
5116 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
5117 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5118 SDLoc dl = getCurSDLoc();
5119 Align Alignment = I.getAlign();
5120 AAMDNodes AAInfo = I.getAAMetadata();
5121 const MDNode *MemCacheHint =
5122 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5123
5124 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5125
5126 unsigned ChainI = 0;
5127 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5128 // See visitLoad comments.
5129 if (ChainI == MaxParallelChains) {
5130 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5131 ArrayRef(Chains.data(), ChainI));
5132 Root = Chain;
5133 ChainI = 0;
5134 }
5135
5136 // TODO: MachinePointerInfo only supports a fixed length offset.
5137 MachinePointerInfo PtrInfo =
5138 !Offsets[i].isScalable() || Offsets[i].isZero()
5139 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
5140 : MachinePointerInfo();
5141
5142 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5143 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
5144 if (MemVTs[i] != ValueVTs[i])
5145 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
5146 SDValue St =
5147 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
5148 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
5149 Chains[ChainI] = St;
5150 }
5151
5152 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5153 ArrayRef(Chains.data(), ChainI));
5154 setValue(&I, StoreNode);
5155 DAG.setRoot(StoreNode);
5156}
5157
5158void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
5159 bool IsCompressing) {
5160 SDLoc sdl = getCurSDLoc();
5161
5162 Value *Src0Operand = I.getArgOperand(0);
5163 Value *PtrOperand = I.getArgOperand(1);
5164 Value *MaskOperand = I.getArgOperand(2);
5165 Align Alignment = I.getParamAlign(1).valueOrOne();
5166
5167 SDValue Ptr = getValue(PtrOperand);
5168 SDValue Src0 = getValue(Src0Operand);
5169 SDValue Mask = getValue(MaskOperand);
5170 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5171
5172 EVT VT = Src0.getValueType();
5173
5174 const auto &TLI = DAG.getTargetLoweringInfo();
5175
5176 auto MMOFlags = MachineMemOperand::MOStore;
5177 MMOFlags |= TLI.getTargetMMOFlags(I);
5178 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5180
5181 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5182
5183 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5184 MachinePointerInfo(PtrOperand), MMOFlags,
5185 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5186 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5187
5188 SDValue StoreNode =
5189 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5190 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5191 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5192 Mask)
5193 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5194 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5195 IsCompressing);
5196 DAG.setRoot(StoreNode);
5197 setValue(&I, StoreNode);
5198}
5199
5200// Get a uniform base for the Gather/Scatter intrinsic.
5201// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5202// We try to represent it as a base pointer + vector of indices.
5203// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5204// The first operand of the GEP may be a single pointer or a vector of pointers
5205// Example:
5206// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5207// or
5208// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5209// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5210//
5211// When the first GEP operand is a single pointer - it is the uniform base we
5212// are looking for. If first operand of the GEP is a splat vector - we
5213// extract the splat value and use it as a uniform base.
5214// In all other cases the function returns 'false'.
5215static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5216 SDValue &Scale, SelectionDAGBuilder *SDB,
5217 const BasicBlock *CurBB, uint64_t ElemSize) {
5218 SelectionDAG& DAG = SDB->DAG;
5220 const DataLayout &DL = DAG.getDataLayout();
5221
5222 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5223
5224 // Handle splat constant pointer.
5225 if (auto *C = dyn_cast<Constant>(Ptr)) {
5226 C = C->getSplatValue();
5227 if (!C)
5228 return false;
5229
5230 Base = SDB->getValue(C);
5231
5232 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5233 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5234 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5235 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5236 return true;
5237 }
5238
5240 if (!GEP || GEP->getParent() != CurBB)
5241 return false;
5242
5243 if (GEP->getNumOperands() != 2)
5244 return false;
5245
5246 const Value *BasePtr = GEP->getPointerOperand();
5247 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5248
5249 // Make sure the base is scalar and the index is a vector.
5250 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5251 return false;
5252
5253 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5254 if (ScaleVal.isScalable())
5255 return false;
5256
5257 // Target may not support the required addressing mode.
5258 if (ScaleVal != 1 &&
5259 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5260 return false;
5261
5262 Base = SDB->getValue(BasePtr);
5263 Index = SDB->getValue(IndexVal);
5264
5265 Scale =
5266 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5267 return true;
5268}
5269
5270void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5271 SDLoc sdl = getCurSDLoc();
5272
5273 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5274 const Value *Ptr = I.getArgOperand(1);
5275 SDValue Src0 = getValue(I.getArgOperand(0));
5276 SDValue Mask = getValue(I.getArgOperand(2));
5277 EVT VT = Src0.getValueType();
5278 Align Alignment = I.getParamAlign(1).valueOrOne();
5279 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5280
5281 SDValue Base;
5282 SDValue Index;
5283 SDValue Scale;
5284 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5285 I.getParent(), VT.getScalarStoreSize());
5286
5287 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5288 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5289 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5290 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5291 if (!UniformBase) {
5292 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5293 Index = getValue(Ptr);
5294 Scale =
5295 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5296 }
5297
5298 EVT IdxVT = Index.getValueType();
5299 EVT EltTy = IdxVT.getVectorElementType();
5300 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5301 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5302 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5303 }
5304
5305 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5306 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5307 Ops, MMO, ISD::SIGNED_SCALED, false);
5308 DAG.setRoot(Scatter);
5309 setValue(&I, Scatter);
5310}
5311
5312void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5313 SDLoc sdl = getCurSDLoc();
5314
5315 Value *PtrOperand = I.getArgOperand(0);
5316 Value *MaskOperand = I.getArgOperand(1);
5317 Value *Src0Operand = I.getArgOperand(2);
5318 Align Alignment = I.getParamAlign(0).valueOrOne();
5319
5320 SDValue Ptr = getValue(PtrOperand);
5321 SDValue Src0 = getValue(Src0Operand);
5322 SDValue Mask = getValue(MaskOperand);
5323 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5324
5325 EVT VT = Src0.getValueType();
5326 AAMDNodes AAInfo = I.getAAMetadata();
5327 const MDNode *Ranges = getRangeMetadata(I);
5328 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5329
5330 // Do not serialize masked loads of constant memory with anything.
5331 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5332 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5333
5334 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5335
5336 const auto &TLI = DAG.getTargetLoweringInfo();
5337
5338 auto MMOFlags = MachineMemOperand::MOLoad;
5339 MMOFlags |= TLI.getTargetMMOFlags(I);
5340 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5342 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5344
5345 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5346 MachinePointerInfo(PtrOperand), MMOFlags,
5347 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5348 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5349
5350 // The Load/Res may point to different values and both of them are output
5351 // variables.
5352 SDValue Load;
5353 SDValue Res;
5354 if (!IsExpanding &&
5355 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5356 /*IsStore=*/false))
5357 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5358 else
5359 Res = Load =
5360 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5361 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5362 if (AddToChain)
5363 PendingLoads.push_back(Load.getValue(1));
5364 setValue(&I, Res);
5365}
5366
5367void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5368 SDLoc sdl = getCurSDLoc();
5369 Value *PtrOperand = I.getArgOperand(0);
5370 // The remaining arguments (num_accessible_bytes or oracle function + args)
5371 // are IR-level semantics only; they are not needed at codegen.
5372 SDValue Ptr = getValue(PtrOperand);
5373
5374 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5375 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5376 Align Alignment = I.getParamAlign(0).valueOrOne();
5377 AAMDNodes AAInfo = I.getAAMetadata();
5378
5379 SDValue InChain = DAG.getRoot();
5380
5381 // Use MOLoad but NOT MODereferenceable - the memory may not be
5382 // fully dereferenceable.
5383 auto MMOFlags = MachineMemOperand::MOLoad;
5384 MMOFlags |= TLI.getTargetMMOFlags(I);
5385 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5387 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5389
5390 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5391 MachinePointerInfo(PtrOperand), MMOFlags,
5392 LocationSize::precise(VT.getStoreSize()), Alignment, AAInfo);
5393
5394 SDValue Load = DAG.getLoad(VT, sdl, InChain, Ptr, MMO);
5395 PendingLoads.push_back(Load.getValue(1));
5396 setValue(&I, Load);
5397}
5398
5399void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5400 SDLoc sdl = getCurSDLoc();
5401
5402 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5403 const Value *Ptr = I.getArgOperand(0);
5404 SDValue Src0 = getValue(I.getArgOperand(2));
5405 SDValue Mask = getValue(I.getArgOperand(1));
5406
5407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5408 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5409 Align Alignment = I.getParamAlign(0).valueOrOne();
5410
5411 const MDNode *Ranges = getRangeMetadata(I);
5412
5413 SDValue Root = DAG.getRoot();
5414 SDValue Base;
5415 SDValue Index;
5416 SDValue Scale;
5417 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5418 I.getParent(), VT.getScalarStoreSize());
5419 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5420 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5421 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5423 MMOMetadata(I.getAAMetadata(), Ranges));
5424
5425 if (!UniformBase) {
5426 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5427 Index = getValue(Ptr);
5428 Scale =
5429 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5430 }
5431
5432 EVT IdxVT = Index.getValueType();
5433 EVT EltTy = IdxVT.getVectorElementType();
5434 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5435 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5436 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5437 }
5438
5439 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5440 SDValue Gather =
5441 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5443
5444 PendingLoads.push_back(Gather.getValue(1));
5445 setValue(&I, Gather);
5446}
5447
5448void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5449 SDLoc dl = getCurSDLoc();
5450 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5451 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5452 SyncScope::ID SSID = I.getSyncScopeID();
5453
5454 SDValue InChain = getRoot();
5455
5456 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5457 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5458
5459 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5460 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5461
5462 MachineFunction &MF = DAG.getMachineFunction();
5463 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5464 MachineMemOperand *MMO = MF.getMachineMemOperand(
5465 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5466 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5467 SSID, SuccessOrdering, FailureOrdering);
5468
5470 dl, MemVT, VTs, InChain,
5471 getValue(I.getPointerOperand()),
5472 getValue(I.getCompareOperand()),
5473 getValue(I.getNewValOperand()), MMO);
5474
5475 SDValue OutChain = L.getValue(2);
5476
5477 setValue(&I, L);
5478 DAG.setRoot(OutChain);
5479}
5480
5481void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5482 SDLoc dl = getCurSDLoc();
5484 switch (I.getOperation()) {
5485 default: llvm_unreachable("Unknown atomicrmw operation");
5503 break;
5506 break;
5509 break;
5512 break;
5515 break;
5518 break;
5521 break;
5524 break;
5525 }
5526 AtomicOrdering Ordering = I.getOrdering();
5527 SyncScope::ID SSID = I.getSyncScopeID();
5528
5529 SDValue InChain = getRoot();
5530
5531 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5532 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5533 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5534
5535 MachineFunction &MF = DAG.getMachineFunction();
5536 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5537 MachineMemOperand *MMO = MF.getMachineMemOperand(
5538 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5539 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5540 SSID, Ordering);
5541
5542 SDValue L =
5543 DAG.getAtomic(NT, dl, MemVT, InChain,
5544 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5545 MMO);
5546
5547 SDValue OutChain = L.getValue(1);
5548
5549 setValue(&I, L);
5550 DAG.setRoot(OutChain);
5551}
5552
5553void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5554 SDLoc dl = getCurSDLoc();
5555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5556 SDValue Ops[3];
5557 Ops[0] = getRoot();
5558 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5559 TLI.getFenceOperandTy(DAG.getDataLayout()));
5560 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5561 TLI.getFenceOperandTy(DAG.getDataLayout()));
5562 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5563 setValue(&I, N);
5564 DAG.setRoot(N);
5565}
5566
5567void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5568 SDLoc dl = getCurSDLoc();
5569 AtomicOrdering Order = I.getOrdering();
5570 SyncScope::ID SSID = I.getSyncScopeID();
5571
5572 SDValue InChain = getRoot();
5573
5574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5575 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5576 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5577
5578 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5579 report_fatal_error("Cannot generate unaligned atomic load");
5580
5581 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5582
5583 const MDNode *Ranges = getRangeMetadata(I);
5584 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5585 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5586 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5587 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5588 Order);
5589
5590 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5591
5592 SDValue Ptr = getValue(I.getPointerOperand());
5593 SDValue L =
5594 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5595
5596 SDValue OutChain = L.getValue(1);
5597 if (MemVT != VT)
5598 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5599
5600 setValue(&I, L);
5601 DAG.setRoot(OutChain);
5602}
5603
5604void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5605 SDLoc dl = getCurSDLoc();
5606
5607 AtomicOrdering Ordering = I.getOrdering();
5608 SyncScope::ID SSID = I.getSyncScopeID();
5609
5610 SDValue InChain = getRoot();
5611
5612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5613 EVT MemVT =
5614 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5615
5616 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5617 report_fatal_error("Cannot generate unaligned atomic store");
5618
5619 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5620
5621 MachineFunction &MF = DAG.getMachineFunction();
5622 const MDNode *MemCacheHint =
5623 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5624 MachineMemOperand *MMO = MF.getMachineMemOperand(
5625 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5626 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5627 SSID, Ordering);
5628
5629 SDValue Val = getValue(I.getValueOperand());
5630 if (Val.getValueType() != MemVT)
5631 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5632 SDValue Ptr = getValue(I.getPointerOperand());
5633
5634 SDValue OutChain =
5635 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5636
5637 setValue(&I, OutChain);
5638 DAG.setRoot(OutChain);
5639}
5640
5641/// Check if this intrinsic call depends on the chain (1st return value)
5642/// and if it only *loads* memory.
5643/// Ignore the callsite's attributes. A specific call site may be marked with
5644/// readnone, but the lowering code will expect the chain based on the
5645/// definition.
5646std::pair<bool, bool>
5647SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5648 const Function *F = I.getCalledFunction();
5649 bool HasChain = !F->doesNotAccessMemory();
5650 bool OnlyLoad =
5651 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5652
5653 return {HasChain, OnlyLoad};
5654}
5655
5656SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5657 const CallBase &I, bool HasChain, bool OnlyLoad,
5658 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5660
5661 // Build the operand list.
5663 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5664 if (OnlyLoad) {
5665 // We don't need to serialize loads against other loads.
5666 Ops.push_back(DAG.getRoot());
5667 } else {
5668 Ops.push_back(getRoot());
5669 }
5670 }
5671
5672 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5673 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5674 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5675 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5676 TLI.getPointerTy(DAG.getDataLayout())));
5677
5678 // Add all operands of the call to the operand list.
5679 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5680 const Value *Arg = I.getArgOperand(i);
5681 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5682 Ops.push_back(getValue(Arg));
5683 continue;
5684 }
5685
5686 // Use TargetConstant instead of a regular constant for immarg.
5687 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5688 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5689 assert(CI->getBitWidth() <= 64 &&
5690 "large intrinsic immediates not handled");
5691 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5692 } else {
5693 Ops.push_back(
5694 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5695 }
5696 }
5697
5698 if (std::optional<OperandBundleUse> Bundle =
5699 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5700 auto *Sym = Bundle->Inputs[0].get();
5701 SDValue SDSym = getValue(Sym);
5702 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5703 Ops.push_back(SDSym);
5704 }
5705
5706 if (std::optional<OperandBundleUse> Bundle =
5707 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5708 Value *Token = Bundle->Inputs[0].get();
5709 SDValue ConvControlToken = getValue(Token);
5710 assert(Ops.back().getValueType() != MVT::Glue &&
5711 "Did not expect another glue node here.");
5712 ConvControlToken =
5713 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5714 Ops.push_back(ConvControlToken);
5715 }
5716
5717 return Ops;
5718}
5719
5720SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5721 bool HasChain) {
5722 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5723
5724 SmallVector<EVT, 4> ValueVTs;
5725 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5726
5727 if (HasChain)
5728 ValueVTs.push_back(MVT::Other);
5729
5730 return DAG.getVTList(ValueVTs);
5731}
5732
5733/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5734SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5735 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5736 const SDVTList &VTs) {
5737 if (!HasChain)
5738 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5739 if (!IntrinsicVT.isVoidTy())
5740 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5741 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5742}
5743
5744/// Set root, convert return type if necessary and check alignment.
5745SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5746 bool HasChain,
5747 bool OnlyLoad,
5748 SDValue Result) {
5749 if (HasChain) {
5750 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5751 if (OnlyLoad)
5752 PendingLoads.push_back(Chain);
5753 else
5754 DAG.setRoot(Chain);
5755 }
5756
5757 if (I.getType()->isVoidTy())
5758 return Result;
5759
5760 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5761 // Insert `assertalign` node if there's an alignment.
5762 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5763 } else if (!isa<VectorType>(I.getType())) {
5764 Result = lowerRangeToAssertZExt(DAG, I, Result);
5765 }
5766
5767 return Result;
5768}
5769
5770/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5771/// node.
5772void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5773 unsigned Intrinsic) {
5774 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5775 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5776
5777 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5778 Intrinsic)) {
5779 SDLoc DL = getCurSDLoc();
5780 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5781 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5782
5783 // The intrinsic is not available on this subtarget. Preserve the chain for
5784 // side-effecting intrinsics and lower any result to poison so that
5785 // compilation can continue and collect further diagnostics.
5786 if (HasChain && !OnlyLoad)
5787 DAG.setRoot(getRoot());
5788
5790 return;
5791 }
5792
5793 // Infos is set by getTgtMemIntrinsic.
5795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5796 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5797 // Use the first (primary) info determines the node opcode.
5798 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5799
5801 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5802 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5803
5804 // Propagate fast-math-flags from IR to node(s).
5805 SDNodeFlags Flags;
5806 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5807 Flags.copyFMF(*FPMO);
5808 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5809
5810 // Create the node.
5812
5813 // In some cases, custom collection of operands from CallInst I may be needed.
5815 if (!Infos.empty()) {
5816 // This is target intrinsic that touches memory
5817 // Create MachineMemOperands for each memory access described by the target.
5818 MachineFunction &MF = DAG.getMachineFunction();
5820 for (const auto &Info : Infos) {
5821 // TODO: We currently just fallback to address space 0 if
5822 // getTgtMemIntrinsic didn't yield anything useful.
5823 MachinePointerInfo MPI;
5824 if (Info.ptrVal)
5825 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5826 else if (Info.fallbackAddressSpace)
5827 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5828 EVT MemVT = Info.memVT;
5829 LocationSize Size = LocationSize::precise(Info.size);
5830 if (Size.hasValue() && !Size.getValue())
5832 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5833 MachineMemOperand *MMO = MF.getMachineMemOperand(
5834 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5835 Info.order, Info.failureOrder);
5836 MMOs.push_back(MMO);
5837 }
5838
5839 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5840 Info->memVT, MMOs);
5841 } else {
5842 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5843 }
5844
5845 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5846
5847 setValue(&I, Result);
5848}
5849
5850/// GetSignificand - Get the significand and build it into a floating-point
5851/// number with exponent of 1:
5852///
5853/// Op = (Op & 0x007fffff) | 0x3f800000;
5854///
5855/// where Op is the hexadecimal representation of floating point value.
5857 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5858 DAG.getConstant(0x007fffff, dl, MVT::i32));
5859 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5860 DAG.getConstant(0x3f800000, dl, MVT::i32));
5861 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5862}
5863
5864/// GetExponent - Get the exponent:
5865///
5866/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5867///
5868/// where Op is the hexadecimal representation of floating point value.
5870 const TargetLowering &TLI, const SDLoc &dl) {
5871 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5872 DAG.getConstant(0x7f800000, dl, MVT::i32));
5873 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5874 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5875 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5876 DAG.getConstant(127, dl, MVT::i32));
5877 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5878}
5879
5880/// getF32Constant - Get 32-bit floating point constant.
5881static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5882 const SDLoc &dl) {
5883 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5884 MVT::f32);
5885}
5886
5888 SelectionDAG &DAG) {
5889 // TODO: What fast-math-flags should be set on the floating-point nodes?
5890
5891 // IntegerPartOfX = ((int32_t)(t0);
5892 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5893
5894 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5895 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5896 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5897
5898 // IntegerPartOfX <<= 23;
5899 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5900 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5901
5902 SDValue TwoToFractionalPartOfX;
5903 if (LimitFloatPrecision <= 6) {
5904 // For floating-point precision of 6:
5905 //
5906 // TwoToFractionalPartOfX =
5907 // 0.997535578f +
5908 // (0.735607626f + 0.252464424f * x) * x;
5909 //
5910 // error 0.0144103317, which is 6 bits
5911 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5912 getF32Constant(DAG, 0x3e814304, dl));
5913 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5914 getF32Constant(DAG, 0x3f3c50c8, dl));
5915 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5916 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5917 getF32Constant(DAG, 0x3f7f5e7e, dl));
5918 } else if (LimitFloatPrecision <= 12) {
5919 // For floating-point precision of 12:
5920 //
5921 // TwoToFractionalPartOfX =
5922 // 0.999892986f +
5923 // (0.696457318f +
5924 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5925 //
5926 // error 0.000107046256, which is 13 to 14 bits
5927 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5928 getF32Constant(DAG, 0x3da235e3, dl));
5929 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5930 getF32Constant(DAG, 0x3e65b8f3, dl));
5931 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5932 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5933 getF32Constant(DAG, 0x3f324b07, dl));
5934 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5935 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5936 getF32Constant(DAG, 0x3f7ff8fd, dl));
5937 } else { // LimitFloatPrecision <= 18
5938 // For floating-point precision of 18:
5939 //
5940 // TwoToFractionalPartOfX =
5941 // 0.999999982f +
5942 // (0.693148872f +
5943 // (0.240227044f +
5944 // (0.554906021e-1f +
5945 // (0.961591928e-2f +
5946 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5947 // error 2.47208000*10^(-7), which is better than 18 bits
5948 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5949 getF32Constant(DAG, 0x3924b03e, dl));
5950 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5951 getF32Constant(DAG, 0x3ab24b87, dl));
5952 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5953 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5954 getF32Constant(DAG, 0x3c1d8c17, dl));
5955 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5956 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5957 getF32Constant(DAG, 0x3d634a1d, dl));
5958 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5959 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5960 getF32Constant(DAG, 0x3e75fe14, dl));
5961 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5962 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5963 getF32Constant(DAG, 0x3f317234, dl));
5964 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5965 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5966 getF32Constant(DAG, 0x3f800000, dl));
5967 }
5968
5969 // Add the exponent into the result in integer domain.
5970 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5971 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5972 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5973}
5974
5975/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5976/// limited-precision mode.
5978 const TargetLowering &TLI, SDNodeFlags Flags) {
5979 if (Op.getValueType() == MVT::f32 &&
5981
5982 // Put the exponent in the right bit position for later addition to the
5983 // final result:
5984 //
5985 // t0 = Op * log2(e)
5986
5987 // TODO: What fast-math-flags should be set here?
5988 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5989 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5990 return getLimitedPrecisionExp2(t0, dl, DAG);
5991 }
5992
5993 // No special expansion.
5994 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5995}
5996
5997/// expandLog - Lower a log intrinsic. Handles the special sequences for
5998/// limited-precision mode.
6000 const TargetLowering &TLI, SDNodeFlags Flags) {
6001 // TODO: What fast-math-flags should be set on the floating-point nodes?
6002
6003 if (Op.getValueType() == MVT::f32 &&
6005 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6006
6007 // Scale the exponent by log(2).
6008 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6009 SDValue LogOfExponent =
6010 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6011 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
6012
6013 // Get the significand and build it into a floating-point number with
6014 // exponent of 1.
6015 SDValue X = GetSignificand(DAG, Op1, dl);
6016
6017 SDValue LogOfMantissa;
6018 if (LimitFloatPrecision <= 6) {
6019 // For floating-point precision of 6:
6020 //
6021 // LogofMantissa =
6022 // -1.1609546f +
6023 // (1.4034025f - 0.23903021f * x) * x;
6024 //
6025 // error 0.0034276066, which is better than 8 bits
6026 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6027 getF32Constant(DAG, 0xbe74c456, dl));
6028 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6029 getF32Constant(DAG, 0x3fb3a2b1, dl));
6030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6031 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6032 getF32Constant(DAG, 0x3f949a29, dl));
6033 } else if (LimitFloatPrecision <= 12) {
6034 // For floating-point precision of 12:
6035 //
6036 // LogOfMantissa =
6037 // -1.7417939f +
6038 // (2.8212026f +
6039 // (-1.4699568f +
6040 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
6041 //
6042 // error 0.000061011436, which is 14 bits
6043 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6044 getF32Constant(DAG, 0xbd67b6d6, dl));
6045 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6046 getF32Constant(DAG, 0x3ee4f4b8, dl));
6047 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6048 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6049 getF32Constant(DAG, 0x3fbc278b, dl));
6050 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6051 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6052 getF32Constant(DAG, 0x40348e95, dl));
6053 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6054 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6055 getF32Constant(DAG, 0x3fdef31a, dl));
6056 } else { // LimitFloatPrecision <= 18
6057 // For floating-point precision of 18:
6058 //
6059 // LogOfMantissa =
6060 // -2.1072184f +
6061 // (4.2372794f +
6062 // (-3.7029485f +
6063 // (2.2781945f +
6064 // (-0.87823314f +
6065 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
6066 //
6067 // error 0.0000023660568, which is better than 18 bits
6068 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6069 getF32Constant(DAG, 0xbc91e5ac, dl));
6070 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6071 getF32Constant(DAG, 0x3e4350aa, dl));
6072 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6073 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6074 getF32Constant(DAG, 0x3f60d3e3, dl));
6075 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6076 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6077 getF32Constant(DAG, 0x4011cdf0, dl));
6078 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6079 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6080 getF32Constant(DAG, 0x406cfd1c, dl));
6081 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6082 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6083 getF32Constant(DAG, 0x408797cb, dl));
6084 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6085 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6086 getF32Constant(DAG, 0x4006dcab, dl));
6087 }
6088
6089 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
6090 }
6091
6092 // No special expansion.
6093 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
6094}
6095
6096/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
6097/// limited-precision mode.
6099 const TargetLowering &TLI, SDNodeFlags Flags) {
6100 // TODO: What fast-math-flags should be set on the floating-point nodes?
6101
6102 if (Op.getValueType() == MVT::f32 &&
6104 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6105
6106 // Get the exponent.
6107 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
6108
6109 // Get the significand and build it into a floating-point number with
6110 // exponent of 1.
6111 SDValue X = GetSignificand(DAG, Op1, dl);
6112
6113 // Different possible minimax approximations of significand in
6114 // floating-point for various degrees of accuracy over [1,2].
6115 SDValue Log2ofMantissa;
6116 if (LimitFloatPrecision <= 6) {
6117 // For floating-point precision of 6:
6118 //
6119 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
6120 //
6121 // error 0.0049451742, which is more than 7 bits
6122 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6123 getF32Constant(DAG, 0xbeb08fe0, dl));
6124 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6125 getF32Constant(DAG, 0x40019463, dl));
6126 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6127 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6128 getF32Constant(DAG, 0x3fd6633d, dl));
6129 } else if (LimitFloatPrecision <= 12) {
6130 // For floating-point precision of 12:
6131 //
6132 // Log2ofMantissa =
6133 // -2.51285454f +
6134 // (4.07009056f +
6135 // (-2.12067489f +
6136 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
6137 //
6138 // error 0.0000876136000, which is better than 13 bits
6139 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6140 getF32Constant(DAG, 0xbda7262e, dl));
6141 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6142 getF32Constant(DAG, 0x3f25280b, dl));
6143 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6144 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6145 getF32Constant(DAG, 0x4007b923, dl));
6146 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6147 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6148 getF32Constant(DAG, 0x40823e2f, dl));
6149 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6150 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6151 getF32Constant(DAG, 0x4020d29c, dl));
6152 } else { // LimitFloatPrecision <= 18
6153 // For floating-point precision of 18:
6154 //
6155 // Log2ofMantissa =
6156 // -3.0400495f +
6157 // (6.1129976f +
6158 // (-5.3420409f +
6159 // (3.2865683f +
6160 // (-1.2669343f +
6161 // (0.27515199f -
6162 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
6163 //
6164 // error 0.0000018516, which is better than 18 bits
6165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6166 getF32Constant(DAG, 0xbcd2769e, dl));
6167 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6168 getF32Constant(DAG, 0x3e8ce0b9, dl));
6169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6170 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6171 getF32Constant(DAG, 0x3fa22ae7, dl));
6172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6174 getF32Constant(DAG, 0x40525723, dl));
6175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6176 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6177 getF32Constant(DAG, 0x40aaf200, dl));
6178 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6179 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6180 getF32Constant(DAG, 0x40c39dad, dl));
6181 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6182 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6183 getF32Constant(DAG, 0x4042902c, dl));
6184 }
6185
6186 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
6187 }
6188
6189 // No special expansion.
6190 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
6191}
6192
6193/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6194/// limited-precision mode.
6196 const TargetLowering &TLI, SDNodeFlags Flags) {
6197 // TODO: What fast-math-flags should be set on the floating-point nodes?
6198
6199 if (Op.getValueType() == MVT::f32 &&
6201 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6202
6203 // Scale the exponent by log10(2) [0.30102999f].
6204 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6205 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6206 getF32Constant(DAG, 0x3e9a209a, dl));
6207
6208 // Get the significand and build it into a floating-point number with
6209 // exponent of 1.
6210 SDValue X = GetSignificand(DAG, Op1, dl);
6211
6212 SDValue Log10ofMantissa;
6213 if (LimitFloatPrecision <= 6) {
6214 // For floating-point precision of 6:
6215 //
6216 // Log10ofMantissa =
6217 // -0.50419619f +
6218 // (0.60948995f - 0.10380950f * x) * x;
6219 //
6220 // error 0.0014886165, which is 6 bits
6221 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6222 getF32Constant(DAG, 0xbdd49a13, dl));
6223 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6224 getF32Constant(DAG, 0x3f1c0789, dl));
6225 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6226 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6227 getF32Constant(DAG, 0x3f011300, dl));
6228 } else if (LimitFloatPrecision <= 12) {
6229 // For floating-point precision of 12:
6230 //
6231 // Log10ofMantissa =
6232 // -0.64831180f +
6233 // (0.91751397f +
6234 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6235 //
6236 // error 0.00019228036, which is better than 12 bits
6237 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6238 getF32Constant(DAG, 0x3d431f31, dl));
6239 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6240 getF32Constant(DAG, 0x3ea21fb2, dl));
6241 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6242 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6243 getF32Constant(DAG, 0x3f6ae232, dl));
6244 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6245 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6246 getF32Constant(DAG, 0x3f25f7c3, dl));
6247 } else { // LimitFloatPrecision <= 18
6248 // For floating-point precision of 18:
6249 //
6250 // Log10ofMantissa =
6251 // -0.84299375f +
6252 // (1.5327582f +
6253 // (-1.0688956f +
6254 // (0.49102474f +
6255 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6256 //
6257 // error 0.0000037995730, which is better than 18 bits
6258 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6259 getF32Constant(DAG, 0x3c5d51ce, dl));
6260 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6261 getF32Constant(DAG, 0x3e00685a, dl));
6262 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6263 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6264 getF32Constant(DAG, 0x3efb6798, dl));
6265 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6266 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6267 getF32Constant(DAG, 0x3f88d192, dl));
6268 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6269 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6270 getF32Constant(DAG, 0x3fc4316c, dl));
6271 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6272 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6273 getF32Constant(DAG, 0x3f57ce70, dl));
6274 }
6275
6276 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6277 }
6278
6279 // No special expansion.
6280 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6281}
6282
6283/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6284/// limited-precision mode.
6286 const TargetLowering &TLI, SDNodeFlags Flags) {
6287 if (Op.getValueType() == MVT::f32 &&
6289 return getLimitedPrecisionExp2(Op, dl, DAG);
6290
6291 // No special expansion.
6292 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6293}
6294
6295/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6296/// limited-precision mode with x == 10.0f.
6298 SelectionDAG &DAG, const TargetLowering &TLI,
6299 SDNodeFlags Flags) {
6300 bool IsExp10 = false;
6301 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6304 APFloat Ten(10.0f);
6305 IsExp10 = LHSC->isExactlyValue(Ten);
6306 }
6307 }
6308
6309 // TODO: What fast-math-flags should be set on the FMUL node?
6310 if (IsExp10) {
6311 // Put the exponent in the right bit position for later addition to the
6312 // final result:
6313 //
6314 // #define LOG2OF10 3.3219281f
6315 // t0 = Op * LOG2OF10;
6316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6317 getF32Constant(DAG, 0x40549a78, dl));
6318 return getLimitedPrecisionExp2(t0, dl, DAG);
6319 }
6320
6321 // No special expansion.
6322 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6323}
6324
6325/// ExpandPowI - Expand a llvm.powi intrinsic.
6327 SelectionDAG &DAG) {
6328 // If RHS is a constant, we can expand this out to a multiplication tree if
6329 // it's beneficial on the target, otherwise we end up lowering to a call to
6330 // __powidf2 (for example).
6332 unsigned Val = RHSC->getSExtValue();
6333
6334 // powi(x, 0) -> 1.0
6335 if (Val == 0)
6336 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6337
6339 Val, DAG.shouldOptForSize())) {
6340 // Get the exponent as a positive value.
6341 if ((int)Val < 0)
6342 Val = -Val;
6343 // We use the simple binary decomposition method to generate the multiply
6344 // sequence. There are more optimal ways to do this (for example,
6345 // powi(x,15) generates one more multiply than it should), but this has
6346 // the benefit of being both really simple and much better than a libcall.
6347 SDValue Res; // Logically starts equal to 1.0
6348 SDValue CurSquare = LHS;
6349 // TODO: Intrinsics should have fast-math-flags that propagate to these
6350 // nodes.
6351 while (Val) {
6352 if (Val & 1) {
6353 if (Res.getNode())
6354 Res =
6355 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6356 else
6357 Res = CurSquare; // 1.0*CurSquare.
6358 }
6359
6360 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6361 CurSquare, CurSquare);
6362 Val >>= 1;
6363 }
6364
6365 // If the original was negative, invert the result, producing 1/(x*x*x).
6366 if (RHSC->getSExtValue() < 0)
6367 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6368 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6369 return Res;
6370 }
6371 }
6372
6373 // Otherwise, expand to a libcall.
6374 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6375}
6376
6377static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6378 SDValue LHS, SDValue RHS, SDValue Scale,
6379 SelectionDAG &DAG, const TargetLowering &TLI) {
6380 EVT VT = LHS.getValueType();
6381 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6382 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6383 LLVMContext &Ctx = *DAG.getContext();
6384
6385 // If the type is legal but the operation isn't, this node might survive all
6386 // the way to operation legalization. If we end up there and we do not have
6387 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6388 // node.
6389
6390 // Coax the legalizer into expanding the node during type legalization instead
6391 // by bumping the size by one bit. This will force it to Promote, enabling the
6392 // early expansion and avoiding the need to expand later.
6393
6394 // We don't have to do this if Scale is 0; that can always be expanded, unless
6395 // it's a saturating signed operation. Those can experience true integer
6396 // division overflow, a case which we must avoid.
6397
6398 // FIXME: We wouldn't have to do this (or any of the early
6399 // expansion/promotion) if it was possible to expand a libcall of an
6400 // illegal type during operation legalization. But it's not, so things
6401 // get a bit hacky.
6402 unsigned ScaleInt = Scale->getAsZExtVal();
6403 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6404 (TLI.isTypeLegal(VT) ||
6405 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6406 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
6407 Opcode, VT, ScaleInt);
6408 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6409 EVT PromVT;
6410 if (VT.isScalarInteger())
6411 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6412 else if (VT.isVector()) {
6413 PromVT = VT.getVectorElementType();
6414 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6415 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6416 } else
6417 llvm_unreachable("Wrong VT for DIVFIX?");
6418 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6419 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6420 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6421 // For saturating operations, we need to shift up the LHS to get the
6422 // proper saturation width, and then shift down again afterwards.
6423 if (Saturating)
6424 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6425 DAG.getConstant(1, DL, ShiftTy));
6426 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6427 if (Saturating)
6428 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6429 DAG.getConstant(1, DL, ShiftTy));
6430 return DAG.getZExtOrTrunc(Res, DL, VT);
6431 }
6432 }
6433
6434 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6435}
6436
6437// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6438// bitcasted, or split argument. Returns a list of <Register, size in bits>
6439static void
6440getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6441 const SDValue &N) {
6442 switch (N.getOpcode()) {
6443 case ISD::CopyFromReg: {
6444 SDValue Op = N.getOperand(1);
6445 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6446 Op.getValueType().getSizeInBits());
6447 return;
6448 }
6449 case ISD::BITCAST:
6450 case ISD::AssertZext:
6451 case ISD::AssertSext:
6452 case ISD::TRUNCATE:
6453 getUnderlyingArgRegs(Regs, N.getOperand(0));
6454 return;
6455 case ISD::BUILD_PAIR:
6456 case ISD::BUILD_VECTOR:
6458 for (SDValue Op : N->op_values())
6459 getUnderlyingArgRegs(Regs, Op);
6460 return;
6461 default:
6462 return;
6463 }
6464}
6465
6466/// If the DbgValueInst is a dbg_value of a function argument, create the
6467/// corresponding DBG_VALUE machine instruction for it now. At the end of
6468/// instruction selection, they will be inserted to the entry BB.
6469/// We don't currently support this for variadic dbg_values, as they shouldn't
6470/// appear for function arguments or in the prologue.
6471bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6472 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6473 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6474 const Argument *Arg = dyn_cast<Argument>(V);
6475 if (!Arg)
6476 return false;
6477
6478 MachineFunction &MF = DAG.getMachineFunction();
6479 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6480
6481 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6482 // we've been asked to pursue.
6483 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6484 bool Indirect) {
6485 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6486 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6487 // pointing at the VReg, which will be patched up later.
6488 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6490 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6491 /* isKill */ false, /* isDead */ false,
6492 /* isUndef */ false, /* isEarlyClobber */ false,
6493 /* SubReg */ 0, /* isDebug */ true)});
6494
6495 auto *NewDIExpr = FragExpr;
6496 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6497 // the DIExpression.
6498 if (Indirect)
6499 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6501 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6502 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6503 } else {
6504 // Create a completely standard DBG_VALUE.
6505 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6506 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6507 }
6508 };
6509
6510 if (Kind == FuncArgumentDbgValueKind::Value) {
6511 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6512 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6513 // the entry block.
6514 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6515 if (!IsInEntryBlock)
6516 return false;
6517
6518 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6519 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6520 // variable that also is a param.
6521 //
6522 // Although, if we are at the top of the entry block already, we can still
6523 // emit using ArgDbgValue. This might catch some situations when the
6524 // dbg.value refers to an argument that isn't used in the entry block, so
6525 // any CopyToReg node would be optimized out and the only way to express
6526 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6527 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6528 // we should only emit as ArgDbgValue if the Variable is an argument to the
6529 // current function, and the dbg.value intrinsic is found in the entry
6530 // block.
6531 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6532 !DL->getInlinedAt();
6533 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6534 if (!IsInPrologue && !VariableIsFunctionInputArg)
6535 return false;
6536
6537 // Here we assume that a function argument on IR level only can be used to
6538 // describe one input parameter on source level. If we for example have
6539 // source code like this
6540 //
6541 // struct A { long x, y; };
6542 // void foo(struct A a, long b) {
6543 // ...
6544 // b = a.x;
6545 // ...
6546 // }
6547 //
6548 // and IR like this
6549 //
6550 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6551 // entry:
6552 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6553 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6554 // call void @llvm.dbg.value(metadata i32 %b, "b",
6555 // ...
6556 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6557 // ...
6558 //
6559 // then the last dbg.value is describing a parameter "b" using a value that
6560 // is an argument. But since we already has used %a1 to describe a parameter
6561 // we should not handle that last dbg.value here (that would result in an
6562 // incorrect hoisting of the DBG_VALUE to the function entry).
6563 // Notice that we allow one dbg.value per IR level argument, to accommodate
6564 // for the situation with fragments above.
6565 // If there is no node for the value being handled, we return true to skip
6566 // the normal generation of debug info, as it would kill existing debug
6567 // info for the parameter in case of duplicates.
6568 if (VariableIsFunctionInputArg) {
6569 unsigned ArgNo = Arg->getArgNo();
6570 if (ArgNo >= FuncInfo.DescribedArgs.size())
6571 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6572 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6573 return !NodeMap[V].getNode();
6574 FuncInfo.DescribedArgs.set(ArgNo);
6575 }
6576 }
6577
6578 bool IsIndirect = false;
6579 std::optional<MachineOperand> Op;
6580 // Some arguments' frame index is recorded during argument lowering.
6581 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6582 if (FI != std::numeric_limits<int>::max())
6584
6586 if (!Op && N.getNode()) {
6587 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6588 Register Reg;
6589 if (ArgRegsAndSizes.size() == 1)
6590 Reg = ArgRegsAndSizes.front().first;
6591
6592 if (Reg && Reg.isVirtual()) {
6593 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6594 Register PR = RegInfo.getLiveInPhysReg(Reg);
6595 if (PR)
6596 Reg = PR;
6597 }
6598 if (Reg) {
6600 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6601 }
6602 }
6603
6604 if (!Op && N.getNode()) {
6605 // Check if frame index is available.
6606 SDValue LCandidate = peekThroughBitcasts(N);
6607 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6608 if (FrameIndexSDNode *FINode =
6609 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6610 Op = MachineOperand::CreateFI(FINode->getIndex());
6611 }
6612
6613 if (!Op) {
6614 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6615 auto splitMultiRegDbgValue =
6616 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6617 unsigned Offset = 0;
6618 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6619 // FIXME: Scalable sizes are not supported in fragment expressions.
6620 if (RegSizeInBits.isScalable())
6621 return false;
6622
6623 // If the expression is already a fragment, the current register
6624 // offset+size might extend beyond the fragment. In this case, only
6625 // the register bits that are inside the fragment are relevant.
6626 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6627 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6628 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6629 // The register is entirely outside the expression fragment,
6630 // so is irrelevant for debug info.
6631 if (Offset >= ExprFragmentSizeInBits)
6632 break;
6633 // The register is partially outside the expression fragment, only
6634 // the low bits within the fragment are relevant for debug info.
6635 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6636 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6637 }
6638 }
6639
6640 auto FragmentExpr = DIExpression::createFragmentExpression(
6641 Expr, Offset, RegFragmentSizeInBits);
6642 Offset += RegSizeInBits.getFixedValue();
6643 // If a valid fragment expression cannot be created, the variable's
6644 // correct value cannot be determined and so it is set as poison.
6645 if (!FragmentExpr) {
6646 SDDbgValue *SDV = DAG.getConstantDbgValue(
6647 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6648 DAG.AddDbgValue(SDV, false);
6649 continue;
6650 }
6651 MachineInstr *NewMI = MakeVRegDbgValue(
6652 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6653 FuncInfo.ArgDbgValues.push_back(NewMI);
6654 }
6655
6656 return true;
6657 };
6658
6659 // Check if ValueMap has reg number.
6661 VMI = FuncInfo.ValueMap.find(V);
6662 if (VMI != FuncInfo.ValueMap.end()) {
6663 const auto &TLI = DAG.getTargetLoweringInfo();
6664 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6665 V->getType(), std::nullopt);
6666 if (RFV.occupiesMultipleRegs())
6667 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6668
6669 Op = MachineOperand::CreateReg(VMI->second, false);
6670 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6671 } else if (ArgRegsAndSizes.size() > 1) {
6672 // This was split due to the calling convention, and no virtual register
6673 // mapping exists for the value.
6674 return splitMultiRegDbgValue(ArgRegsAndSizes);
6675 }
6676 }
6677
6678 if (!Op)
6679 return false;
6680
6681 assert(Variable->isValidLocationForIntrinsic(DL) &&
6682 "Expected inlined-at fields to agree");
6683 MachineInstr *NewMI = nullptr;
6684
6685 if (Op->isReg())
6686 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6687 else
6688 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6689 Variable, Expr);
6690
6691 // Otherwise, use ArgDbgValues.
6692 FuncInfo.ArgDbgValues.push_back(NewMI);
6693 return true;
6694}
6695
6696/// Return the appropriate SDDbgValue based on N.
6697SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6698 DILocalVariable *Variable,
6699 DIExpression *Expr,
6700 const DebugLoc &dl,
6701 unsigned DbgSDNodeOrder) {
6702 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6703 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6704 // stack slot locations.
6705 //
6706 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6707 // debug values here after optimization:
6708 //
6709 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6710 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6711 //
6712 // Both describe the direct values of their associated variables.
6713 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6714 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6715 }
6716 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6717 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6718}
6719
6720static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6721 switch (Intrinsic) {
6722 case Intrinsic::smul_fix:
6723 return ISD::SMULFIX;
6724 case Intrinsic::umul_fix:
6725 return ISD::UMULFIX;
6726 case Intrinsic::smul_fix_sat:
6727 return ISD::SMULFIXSAT;
6728 case Intrinsic::umul_fix_sat:
6729 return ISD::UMULFIXSAT;
6730 case Intrinsic::sdiv_fix:
6731 return ISD::SDIVFIX;
6732 case Intrinsic::udiv_fix:
6733 return ISD::UDIVFIX;
6734 case Intrinsic::sdiv_fix_sat:
6735 return ISD::SDIVFIXSAT;
6736 case Intrinsic::udiv_fix_sat:
6737 return ISD::UDIVFIXSAT;
6738 default:
6739 llvm_unreachable("Unhandled fixed point intrinsic");
6740 }
6741}
6742
6743/// Given a @llvm.call.preallocated.setup, return the corresponding
6744/// preallocated call.
6745static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6746 assert(cast<CallBase>(PreallocatedSetup)
6748 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6749 "expected call_preallocated_setup Value");
6750 for (const auto *U : PreallocatedSetup->users()) {
6751 auto *UseCall = cast<CallBase>(U);
6752 const Function *Fn = UseCall->getCalledFunction();
6753 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6754 return UseCall;
6755 }
6756 }
6757 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6758}
6759
6760/// If DI is a debug value with an EntryValue expression, lower it using the
6761/// corresponding physical register of the associated Argument value
6762/// (guaranteed to exist by the verifier).
6763bool SelectionDAGBuilder::visitEntryValueDbgValue(
6765 DIExpression *Expr, DebugLoc DbgLoc) {
6766 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6767 return false;
6768
6769 // These properties are guaranteed by the verifier.
6770 const Argument *Arg = cast<Argument>(Values[0]);
6771 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6772
6773 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6774 if (ArgIt == FuncInfo.ValueMap.end()) {
6775 LLVM_DEBUG(
6776 dbgs() << "Dropping dbg.value: expression is entry_value but "
6777 "couldn't find an associated register for the Argument\n");
6778 return true;
6779 }
6780 Register ArgVReg = ArgIt->getSecond();
6781
6782 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6783 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6784 SDDbgValue *SDV = DAG.getVRegDbgValue(
6785 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6786 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6787 return true;
6788 }
6789 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6790 "couldn't find a physical register\n");
6791 return true;
6792}
6793
6794/// Lower the call to the specified intrinsic function.
6795void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6796 unsigned Intrinsic) {
6797 SDLoc sdl = getCurSDLoc();
6798 switch (Intrinsic) {
6799 case Intrinsic::experimental_convergence_anchor:
6800 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6801 break;
6802 case Intrinsic::experimental_convergence_entry:
6803 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6804 break;
6805 case Intrinsic::experimental_convergence_loop: {
6806 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6807 auto *Token = Bundle->Inputs[0].get();
6808 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6809 getValue(Token)));
6810 break;
6811 }
6812 }
6813}
6814
6815void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6816 unsigned IntrinsicID) {
6817 // For now, we're only lowering an 'add' histogram.
6818 // We can add others later, e.g. saturating adds, min/max.
6819 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6820 "Tried to lower unsupported histogram type");
6821 SDLoc sdl = getCurSDLoc();
6822 Value *Ptr = I.getOperand(0);
6823 SDValue Inc = getValue(I.getOperand(1));
6824 SDValue Mask = getValue(I.getOperand(2));
6825
6826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6827 EVT VT = Inc.getValueType();
6828 Align Alignment = DAG.getEVTAlign(VT);
6829
6830 const MDNode *Ranges = getRangeMetadata(I);
6831
6832 SDValue Root = DAG.getRoot();
6833 SDValue Base;
6834 SDValue Index;
6835 SDValue Scale;
6836 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6837 I.getParent(), VT.getScalarStoreSize());
6838
6839 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6840
6841 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6842 MachinePointerInfo(AS),
6844 MemoryLocation::UnknownSize, Alignment,
6845 MMOMetadata(I.getAAMetadata(), Ranges));
6846
6847 if (!UniformBase) {
6848 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6849 Index = getValue(Ptr);
6850 Scale =
6851 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6852 }
6853
6854 EVT IdxVT = Index.getValueType();
6855
6856 // Avoid using e.g. i32 as index type when the increment must be performed
6857 // on i64's.
6858 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6859 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6860 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6861 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6862 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6863 }
6864
6865 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6866
6867 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6868 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6869 Ops, MMO, ISD::SIGNED_SCALED);
6870
6871 setValue(&I, Histogram);
6872 DAG.setRoot(Histogram);
6873}
6874
6875void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6876 unsigned Intrinsic) {
6877 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6878 "Tried lowering invalid vector extract last");
6879 SDLoc sdl = getCurSDLoc();
6880 const DataLayout &Layout = DAG.getDataLayout();
6881 SDValue Data = getValue(I.getOperand(0));
6882 SDValue Mask = getValue(I.getOperand(1));
6883
6884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6885 EVT ResVT = TLI.getValueType(Layout, I.getType());
6886
6887 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6888 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6889 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6890
6891 Value *Default = I.getOperand(2);
6893 SDValue PassThru = getValue(Default);
6894 EVT BoolVT = Mask.getValueType().getScalarType();
6895 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6896 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6897 }
6898
6899 setValue(&I, Result);
6900}
6901
6902/// Lower the call to the specified intrinsic function.
6903void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6904 unsigned Intrinsic) {
6905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6906 SDLoc sdl = getCurSDLoc();
6907 DebugLoc dl = getCurDebugLoc();
6908 SDValue Res;
6909
6910 SDNodeFlags Flags;
6911 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6912 Flags.copyFMF(*FPOp);
6913
6914 switch (Intrinsic) {
6915 default:
6916 // By default, turn this into a target intrinsic node.
6917 visitTargetIntrinsic(I, Intrinsic);
6918 return;
6919 case Intrinsic::vscale: {
6920 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6921 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6922 return;
6923 }
6924 case Intrinsic::vastart: visitVAStart(I); return;
6925 case Intrinsic::vaend: visitVAEnd(I); return;
6926 case Intrinsic::vacopy: visitVACopy(I); return;
6927 case Intrinsic::returnaddress:
6928 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6929 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6930 getValue(I.getArgOperand(0))));
6931 return;
6932 case Intrinsic::addressofreturnaddress:
6933 setValue(&I,
6934 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6935 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6936 return;
6937 case Intrinsic::sponentry:
6938 setValue(&I,
6939 DAG.getNode(ISD::SPONENTRY, sdl,
6940 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6941 return;
6942 case Intrinsic::frameaddress:
6943 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6944 TLI.getFrameIndexTy(DAG.getDataLayout()),
6945 getValue(I.getArgOperand(0))));
6946 return;
6947 case Intrinsic::read_volatile_register:
6948 case Intrinsic::read_register: {
6949 Value *Reg = I.getArgOperand(0);
6950 SDValue Chain = getRoot();
6952 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6953 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6954 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6955 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6956 setValue(&I, Res);
6957 DAG.setRoot(Res.getValue(1));
6958 return;
6959 }
6960 case Intrinsic::write_register: {
6961 Value *Reg = I.getArgOperand(0);
6962 Value *RegValue = I.getArgOperand(1);
6963 SDValue Chain = getRoot();
6965 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6966 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6967 RegName, getValue(RegValue)));
6968 return;
6969 }
6970 case Intrinsic::write_volatile_register: {
6971 Value *Reg = I.getArgOperand(0);
6972 Value *RegValue = I.getArgOperand(1);
6973 SDValue Chain = getRoot();
6974 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6975 SDValue RegName = DAG.getMDNode(MD);
6976 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6977 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6978 Chain, RegName, getValue(RegValue));
6979 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6980 // preventing the backend from dead-eliminating the write. This is
6981 // preferred over READ_REGISTER, which would emit extra register copies
6982 // (e.g. fmov xN, dN for FP/SIMD registers).
6983 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6984 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6985 const MachineFunction &MF = DAG.getMachineFunction();
6986 Register PhysReg =
6987 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6988 if (PhysReg.isValid()) {
6989 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6990 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6991 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6992 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6993 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6994 } else {
6995 DAG.setRoot(WriteChain);
6996 }
6997 return;
6998 }
6999 case Intrinsic::memcpy:
7000 case Intrinsic::memcpy_inline: {
7001 const auto &MCI = cast<MemCpyInst>(I);
7002 SDValue Dst = getValue(I.getArgOperand(0));
7003 SDValue Src = getValue(I.getArgOperand(1));
7004 SDValue Size = getValue(I.getArgOperand(2));
7005 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7006 "memcpy_inline needs constant size");
7007 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
7008 Align DstAlign = MCI.getDestAlign().valueOrOne();
7009 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
7010 bool isVol = MCI.isVolatile();
7011 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7012 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
7013 isVol, MCI.isForceInlined(), &I, std::nullopt,
7014 MachinePointerInfo(I.getArgOperand(0)),
7015 MachinePointerInfo(I.getArgOperand(1)),
7016 I.getAAMetadata(), BatchAA);
7017 updateDAGForMaybeTailCall(MC);
7018 return;
7019 }
7020 case Intrinsic::memset:
7021 case Intrinsic::memset_inline: {
7022 const auto &MSII = cast<MemSetInst>(I);
7023 SDValue Dst = getValue(I.getArgOperand(0));
7024 SDValue Value = getValue(I.getArgOperand(1));
7025 SDValue Size = getValue(I.getArgOperand(2));
7026 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7027 "memset_inline needs constant size");
7028 // @llvm.memset defines 0 and 1 to both mean no alignment.
7029 Align DstAlign = MSII.getDestAlign().valueOrOne();
7030 bool isVol = MSII.isVolatile();
7031 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7032 SDValue MC = DAG.getMemset(
7033 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
7034 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
7035 updateDAGForMaybeTailCall(MC);
7036 return;
7037 }
7038 case Intrinsic::memmove: {
7039 const auto &MMI = cast<MemMoveInst>(I);
7040 SDValue Op1 = getValue(I.getArgOperand(0));
7041 SDValue Op2 = getValue(I.getArgOperand(1));
7042 SDValue Op3 = getValue(I.getArgOperand(2));
7043 // @llvm.memmove defines 0 and 1 to both mean no alignment.
7044 Align DstAlign = MMI.getDestAlign().valueOrOne();
7045 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
7046 bool isVol = MMI.isVolatile();
7047 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7048 SDValue MM = DAG.getMemmove(
7049 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
7050 /* OverrideTailCall */ std::nullopt,
7051 MachinePointerInfo(I.getArgOperand(0)),
7052 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
7053 updateDAGForMaybeTailCall(MM);
7054 return;
7055 }
7056 case Intrinsic::memcpy_element_unordered_atomic: {
7057 auto &MI = cast<AnyMemCpyInst>(I);
7058 SDValue Dst = getValue(MI.getRawDest());
7059 SDValue Src = getValue(MI.getRawSource());
7060 SDValue Length = getValue(MI.getLength());
7061
7062 Type *LengthTy = MI.getLength()->getType();
7063 unsigned ElemSz = MI.getElementSizeInBytes();
7064 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7065 SDValue MC =
7066 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7067 isTC, MachinePointerInfo(MI.getRawDest()),
7068 MachinePointerInfo(MI.getRawSource()));
7069 updateDAGForMaybeTailCall(MC);
7070 return;
7071 }
7072 case Intrinsic::memmove_element_unordered_atomic: {
7073 auto &MI = cast<AnyMemMoveInst>(I);
7074 SDValue Dst = getValue(MI.getRawDest());
7075 SDValue Src = getValue(MI.getRawSource());
7076 SDValue Length = getValue(MI.getLength());
7077
7078 Type *LengthTy = MI.getLength()->getType();
7079 unsigned ElemSz = MI.getElementSizeInBytes();
7080 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7081 SDValue MC =
7082 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7083 isTC, MachinePointerInfo(MI.getRawDest()),
7084 MachinePointerInfo(MI.getRawSource()));
7085 updateDAGForMaybeTailCall(MC);
7086 return;
7087 }
7088 case Intrinsic::memset_element_unordered_atomic: {
7089 auto &MI = cast<AnyMemSetInst>(I);
7090 SDValue Dst = getValue(MI.getRawDest());
7091 SDValue Val = getValue(MI.getValue());
7092 SDValue Length = getValue(MI.getLength());
7093
7094 Type *LengthTy = MI.getLength()->getType();
7095 unsigned ElemSz = MI.getElementSizeInBytes();
7096 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7097 SDValue MC =
7098 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
7099 isTC, MachinePointerInfo(MI.getRawDest()));
7100 updateDAGForMaybeTailCall(MC);
7101 return;
7102 }
7103 case Intrinsic::call_preallocated_setup: {
7104 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
7105 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7106 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
7107 getRoot(), SrcValue);
7108 setValue(&I, Res);
7109 DAG.setRoot(Res);
7110 return;
7111 }
7112 case Intrinsic::call_preallocated_arg: {
7113 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
7114 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7115 SDValue Ops[3];
7116 Ops[0] = getRoot();
7117 Ops[1] = SrcValue;
7118 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7119 MVT::i32); // arg index
7120 SDValue Res = DAG.getNode(
7122 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
7123 setValue(&I, Res);
7124 DAG.setRoot(Res.getValue(1));
7125 return;
7126 }
7127
7128 case Intrinsic::eh_typeid_for: {
7129 // Find the type id for the given typeinfo.
7130 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
7131 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
7132 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
7133 setValue(&I, Res);
7134 return;
7135 }
7136
7137 case Intrinsic::eh_return_i32:
7138 case Intrinsic::eh_return_i64:
7139 DAG.getMachineFunction().setCallsEHReturn(true);
7140 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
7141 MVT::Other,
7143 getValue(I.getArgOperand(0)),
7144 getValue(I.getArgOperand(1))));
7145 return;
7146 case Intrinsic::eh_unwind_init:
7147 DAG.getMachineFunction().setCallsUnwindInit(true);
7148 return;
7149 case Intrinsic::eh_dwarf_cfa:
7150 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
7151 TLI.getPointerTy(DAG.getDataLayout()),
7152 getValue(I.getArgOperand(0))));
7153 return;
7154 case Intrinsic::eh_sjlj_callsite: {
7155 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
7156 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
7157
7158 FuncInfo.setCurrentCallSite(CI->getZExtValue());
7159 return;
7160 }
7161 case Intrinsic::eh_sjlj_functioncontext: {
7162 // Get and store the index of the function context.
7163 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7164 AllocaInst *FnCtx =
7165 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
7166 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7168 return;
7169 }
7170 case Intrinsic::eh_sjlj_setjmp: {
7171 SDValue Ops[2];
7172 Ops[0] = getRoot();
7173 Ops[1] = getValue(I.getArgOperand(0));
7174 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
7175 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7176 setValue(&I, Op.getValue(0));
7177 DAG.setRoot(Op.getValue(1));
7178 return;
7179 }
7180 case Intrinsic::eh_sjlj_longjmp:
7181 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
7182 getRoot(), getValue(I.getArgOperand(0))));
7183 return;
7184 case Intrinsic::eh_sjlj_setup_dispatch:
7185 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
7186 getRoot()));
7187 return;
7188 case Intrinsic::masked_gather:
7189 visitMaskedGather(I);
7190 return;
7191 case Intrinsic::masked_load:
7192 visitMaskedLoad(I);
7193 return;
7194 case Intrinsic::masked_scatter:
7195 visitMaskedScatter(I);
7196 return;
7197 case Intrinsic::masked_store:
7198 visitMaskedStore(I);
7199 return;
7200 case Intrinsic::masked_expandload:
7201 visitMaskedLoad(I, true /* IsExpanding */);
7202 return;
7203 case Intrinsic::masked_compressstore:
7204 visitMaskedStore(I, true /* IsCompressing */);
7205 return;
7206 case Intrinsic::speculative_load:
7207 visitSpeculativeLoad(I);
7208 return;
7209 case Intrinsic::powi:
7210 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7211 getValue(I.getArgOperand(1)), DAG));
7212 return;
7213 case Intrinsic::log:
7214 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7215 return;
7216 case Intrinsic::log2:
7217 setValue(&I,
7218 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7219 return;
7220 case Intrinsic::log10:
7221 setValue(&I,
7222 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7223 return;
7224 case Intrinsic::exp:
7225 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7226 return;
7227 case Intrinsic::exp2:
7228 setValue(&I,
7229 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7230 return;
7231 case Intrinsic::pow:
7232 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7233 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7234 return;
7235 case Intrinsic::sqrt:
7236 case Intrinsic::fabs:
7237 case Intrinsic::sin:
7238 case Intrinsic::cos:
7239 case Intrinsic::tan:
7240 case Intrinsic::asin:
7241 case Intrinsic::acos:
7242 case Intrinsic::atan:
7243 case Intrinsic::sinh:
7244 case Intrinsic::cosh:
7245 case Intrinsic::tanh:
7246 case Intrinsic::exp10:
7247 case Intrinsic::floor:
7248 case Intrinsic::ceil:
7249 case Intrinsic::trunc:
7250 case Intrinsic::rint:
7251 case Intrinsic::nearbyint:
7252 case Intrinsic::round:
7253 case Intrinsic::roundeven:
7254 case Intrinsic::canonicalize: {
7255 unsigned Opcode;
7256 // clang-format off
7257 switch (Intrinsic) {
7258 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7259 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7260 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7261 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7262 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7263 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7264 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7265 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7266 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7267 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7268 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7269 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7270 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7271 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7272 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7273 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7274 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7275 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7276 case Intrinsic::round: Opcode = ISD::FROUND; break;
7277 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7278 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7279 }
7280 // clang-format on
7281
7282 setValue(&I, DAG.getNode(Opcode, sdl,
7283 getValue(I.getArgOperand(0)).getValueType(),
7284 getValue(I.getArgOperand(0)), Flags));
7285 return;
7286 }
7287 case Intrinsic::atan2:
7288 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7289 getValue(I.getArgOperand(0)).getValueType(),
7290 getValue(I.getArgOperand(0)),
7291 getValue(I.getArgOperand(1)), Flags));
7292 return;
7293 case Intrinsic::lround:
7294 case Intrinsic::llround:
7295 case Intrinsic::lrint:
7296 case Intrinsic::llrint: {
7297 unsigned Opcode;
7298 // clang-format off
7299 switch (Intrinsic) {
7300 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7301 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7302 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7303 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7304 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7305 }
7306 // clang-format on
7307
7308 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7309 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7310 getValue(I.getArgOperand(0))));
7311 return;
7312 }
7313 case Intrinsic::minnum:
7314 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7315 getValue(I.getArgOperand(0)).getValueType(),
7316 getValue(I.getArgOperand(0)),
7317 getValue(I.getArgOperand(1)), Flags));
7318 return;
7319 case Intrinsic::maxnum:
7320 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7321 getValue(I.getArgOperand(0)).getValueType(),
7322 getValue(I.getArgOperand(0)),
7323 getValue(I.getArgOperand(1)), Flags));
7324 return;
7325 case Intrinsic::minimum:
7326 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7327 getValue(I.getArgOperand(0)).getValueType(),
7328 getValue(I.getArgOperand(0)),
7329 getValue(I.getArgOperand(1)), Flags));
7330 return;
7331 case Intrinsic::maximum:
7332 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7333 getValue(I.getArgOperand(0)).getValueType(),
7334 getValue(I.getArgOperand(0)),
7335 getValue(I.getArgOperand(1)), Flags));
7336 return;
7337 case Intrinsic::minimumnum:
7338 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7339 getValue(I.getArgOperand(0)).getValueType(),
7340 getValue(I.getArgOperand(0)),
7341 getValue(I.getArgOperand(1)), Flags));
7342 return;
7343 case Intrinsic::maximumnum:
7344 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7345 getValue(I.getArgOperand(0)).getValueType(),
7346 getValue(I.getArgOperand(0)),
7347 getValue(I.getArgOperand(1)), Flags));
7348 return;
7349 case Intrinsic::copysign:
7350 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7351 getValue(I.getArgOperand(0)).getValueType(),
7352 getValue(I.getArgOperand(0)),
7353 getValue(I.getArgOperand(1)), Flags));
7354 return;
7355 case Intrinsic::ldexp:
7356 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7357 getValue(I.getArgOperand(0)).getValueType(),
7358 getValue(I.getArgOperand(0)),
7359 getValue(I.getArgOperand(1)), Flags));
7360 return;
7361 case Intrinsic::modf:
7362 case Intrinsic::sincos:
7363 case Intrinsic::sincospi:
7364 case Intrinsic::frexp: {
7365 unsigned Opcode;
7366 switch (Intrinsic) {
7367 default:
7368 llvm_unreachable("unexpected intrinsic");
7369 case Intrinsic::sincos:
7370 Opcode = ISD::FSINCOS;
7371 break;
7372 case Intrinsic::sincospi:
7373 Opcode = ISD::FSINCOSPI;
7374 break;
7375 case Intrinsic::modf:
7376 Opcode = ISD::FMODF;
7377 break;
7378 case Intrinsic::frexp:
7379 Opcode = ISD::FFREXP;
7380 break;
7381 }
7382 SmallVector<EVT, 2> ValueVTs;
7383 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7384 SDVTList VTs = DAG.getVTList(ValueVTs);
7385 setValue(
7386 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7387 return;
7388 }
7389 case Intrinsic::arithmetic_fence: {
7390 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7391 getValue(I.getArgOperand(0)).getValueType(),
7392 getValue(I.getArgOperand(0)), Flags));
7393 return;
7394 }
7395 case Intrinsic::fma:
7396 setValue(&I, DAG.getNode(
7397 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7398 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7399 getValue(I.getArgOperand(2)), Flags));
7400 return;
7401#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7402 case Intrinsic::INTRINSIC:
7403#include "llvm/IR/ConstrainedOps.def"
7404 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7405 return;
7406#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7407#include "llvm/IR/VPIntrinsics.def"
7408 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7409 return;
7410 case Intrinsic::fptrunc_round: {
7411 // Get the last argument, the metadata and convert it to an integer in the
7412 // call
7413 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7414 std::optional<RoundingMode> RoundMode =
7415 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7416
7417 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7418
7419 // Propagate fast-math-flags from IR to node(s).
7420 SDNodeFlags Flags;
7421 Flags.copyFMF(*cast<FPMathOperator>(&I));
7422 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7423
7425 Result = DAG.getNode(
7426 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7427 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7428 setValue(&I, Result);
7429
7430 return;
7431 }
7432 case Intrinsic::fmuladd: {
7433 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7434 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7435 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7436 getValue(I.getArgOperand(0)).getValueType(),
7437 getValue(I.getArgOperand(0)),
7438 getValue(I.getArgOperand(1)),
7439 getValue(I.getArgOperand(2)), Flags));
7440 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7441 // TODO: Support splitting the vector.
7442 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7443 getValue(I.getArgOperand(0)).getValueType(),
7444 getValue(I.getArgOperand(0)),
7445 getValue(I.getArgOperand(1)),
7446 getValue(I.getArgOperand(2)), Flags));
7447 } else {
7448 // TODO: Intrinsic calls should have fast-math-flags.
7449 SDValue Mul = DAG.getNode(
7450 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7451 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7452 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7453 getValue(I.getArgOperand(0)).getValueType(),
7454 Mul, getValue(I.getArgOperand(2)), Flags);
7455 setValue(&I, Add);
7456 }
7457 return;
7458 }
7459 case Intrinsic::fptosi_sat: {
7460 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7461 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7462 getValue(I.getArgOperand(0)),
7463 DAG.getValueType(VT.getScalarType())));
7464 return;
7465 }
7466 case Intrinsic::fptoui_sat: {
7467 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7468 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7469 getValue(I.getArgOperand(0)),
7470 DAG.getValueType(VT.getScalarType())));
7471 return;
7472 }
7473 case Intrinsic::convert_from_arbitrary_fp: {
7474 // Extract format metadata and convert to semantics enum.
7475 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7476 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7477 StringRef FormatStr = cast<MDString>(MD)->getString();
7478 const fltSemantics *SrcSem =
7480 if (!SrcSem) {
7481 DAG.getContext()->emitError(
7482 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7483 "'");
7484 setValue(&I, DAG.getPOISON(DstVT));
7485 return;
7486 }
7488
7489 SDValue IntVal = getValue(I.getArgOperand(0));
7490
7491 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7492 SDValue SemConst =
7493 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7494 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7495 SemConst));
7496 return;
7497 }
7498 case Intrinsic::convert_to_arbitrary_fp: {
7499 // Extract format metadata and convert to semantics enum.
7500 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7501 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7502 StringRef FormatStr = cast<MDString>(MD)->getString();
7503 const fltSemantics *DstSem =
7505 if (!DstSem) {
7506 DAG.getContext()->emitError(
7507 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7508 "'");
7509 setValue(&I, DAG.getPOISON(DstVT));
7510 return;
7511 }
7513
7514 Metadata *RoundMD =
7515 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7516 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7517 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7518 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7519 "Dynamic rounding mode should have been rejected by the verifier");
7520
7521 uint64_t Saturate =
7522 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7523
7524 SDValue FloatVal = getValue(I.getArgOperand(0));
7525
7526 SDValue SemConst =
7527 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7528 SDValue RoundConst =
7529 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7530 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7531 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7532 SemConst, RoundConst, SatConst));
7533 return;
7534 }
7535 case Intrinsic::set_rounding:
7536 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7537 {getRoot(), getValue(I.getArgOperand(0))});
7538 setValue(&I, Res);
7539 DAG.setRoot(Res.getValue(0));
7540 return;
7541 case Intrinsic::is_fpclass: {
7542 const DataLayout DLayout = DAG.getDataLayout();
7543 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7544 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7545 FPClassTest Test = static_cast<FPClassTest>(
7546 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7547 MachineFunction &MF = DAG.getMachineFunction();
7548 const Function &F = MF.getFunction();
7549 SDValue Op = getValue(I.getArgOperand(0));
7550 SDNodeFlags Flags;
7551 Flags.setNoFPExcept(
7552 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7553 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7554 // expansion can use illegal types. Making expansion early allows
7555 // legalizing these types prior to selection.
7556 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7558 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7559 setValue(&I, Result);
7560 return;
7561 }
7562
7563 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7564 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7565 setValue(&I, V);
7566 return;
7567 }
7568 case Intrinsic::get_fpenv: {
7569 const DataLayout DLayout = DAG.getDataLayout();
7570 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7571 Align TempAlign = DAG.getEVTAlign(EnvVT);
7572 SDValue Chain = getRoot();
7573 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7574 // and temporary storage in stack.
7576 Res = DAG.getNode(
7577 ISD::GET_FPENV, sdl,
7578 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7579 MVT::Other),
7580 Chain);
7581 } else {
7582 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7583 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7584 auto MPI =
7585 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7586 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7588 TempAlign);
7589 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7590 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7591 }
7592 setValue(&I, Res);
7593 DAG.setRoot(Res.getValue(1));
7594 return;
7595 }
7596 case Intrinsic::set_fpenv: {
7597 SDValue Env = getValue(I.getArgOperand(0));
7598 EVT EnvVT = Env.getValueType();
7599 Align TempAlign = DAG.getEVTAlign(EnvVT);
7600 SDValue Chain = getRoot();
7601 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7602 // environment from memory.
7604 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7605 } else {
7606 // Allocate space in stack, copy environment bits into it and use this
7607 // memory in SET_FPENV_MEM.
7608 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7609 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7610 auto MPI =
7611 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7612 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7614 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7616 TempAlign);
7617 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7618 }
7619 DAG.setRoot(Chain);
7620 return;
7621 }
7622 case Intrinsic::reset_fpenv:
7623 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7624 return;
7625 case Intrinsic::get_fpmode:
7626 Res = DAG.getNode(
7627 ISD::GET_FPMODE, sdl,
7628 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7629 MVT::Other),
7630 DAG.getRoot());
7631 setValue(&I, Res);
7632 DAG.setRoot(Res.getValue(1));
7633 return;
7634 case Intrinsic::set_fpmode:
7635 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7636 getValue(I.getArgOperand(0)));
7637 DAG.setRoot(Res);
7638 return;
7639 case Intrinsic::reset_fpmode: {
7640 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7641 DAG.setRoot(Res);
7642 return;
7643 }
7644 case Intrinsic::pcmarker: {
7645 SDValue Tmp = getValue(I.getArgOperand(0));
7646 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7647 return;
7648 }
7649 case Intrinsic::readcyclecounter: {
7650 SDValue Op = getRoot();
7651 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7652 DAG.getVTList(MVT::i64, MVT::Other), Op);
7653 setValue(&I, Res);
7654 DAG.setRoot(Res.getValue(1));
7655 return;
7656 }
7657 case Intrinsic::readsteadycounter: {
7658 SDValue Op = getRoot();
7659 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7660 DAG.getVTList(MVT::i64, MVT::Other), Op);
7661 setValue(&I, Res);
7662 DAG.setRoot(Res.getValue(1));
7663 return;
7664 }
7665 case Intrinsic::bitreverse:
7666 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7667 getValue(I.getArgOperand(0)).getValueType(),
7668 getValue(I.getArgOperand(0))));
7669 return;
7670 case Intrinsic::bswap:
7671 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7672 getValue(I.getArgOperand(0)).getValueType(),
7673 getValue(I.getArgOperand(0))));
7674 return;
7675 case Intrinsic::cttz: {
7676 SDValue Arg = getValue(I.getArgOperand(0));
7677 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7678 EVT Ty = Arg.getValueType();
7679 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7680 sdl, Ty, Arg));
7681 return;
7682 }
7683 case Intrinsic::ctlz: {
7684 SDValue Arg = getValue(I.getArgOperand(0));
7685 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7686 EVT Ty = Arg.getValueType();
7687 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7688 sdl, Ty, Arg));
7689 return;
7690 }
7691 case Intrinsic::ctpop: {
7692 SDValue Arg = getValue(I.getArgOperand(0));
7693 EVT Ty = Arg.getValueType();
7694 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7695 return;
7696 }
7697 case Intrinsic::fshl:
7698 case Intrinsic::fshr: {
7699 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7700 SDValue X = getValue(I.getArgOperand(0));
7701 SDValue Y = getValue(I.getArgOperand(1));
7702 SDValue Z = getValue(I.getArgOperand(2));
7703 EVT VT = X.getValueType();
7704
7705 if (X == Y) {
7706 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7707 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7708 } else {
7709 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7710 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7711 }
7712 return;
7713 }
7714 case Intrinsic::clmul: {
7715 SDValue X = getValue(I.getArgOperand(0));
7716 SDValue Y = getValue(I.getArgOperand(1));
7717 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7718 return;
7719 }
7720 case Intrinsic::pext: {
7721 SDValue X = getValue(I.getArgOperand(0));
7722 SDValue Y = getValue(I.getArgOperand(1));
7723 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7724 return;
7725 }
7726 case Intrinsic::pdep: {
7727 SDValue X = getValue(I.getArgOperand(0));
7728 SDValue Y = getValue(I.getArgOperand(1));
7729 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7730 return;
7731 }
7732 case Intrinsic::smulh:
7733 case Intrinsic::umulh: {
7734 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7735 SDValue X = getValue(I.getArgOperand(0));
7736 SDValue Y = getValue(I.getArgOperand(1));
7737 setValue(&I, DAG.getNode(Opc, sdl, X.getValueType(), X, Y));
7738 return;
7739 }
7740 case Intrinsic::sadd_sat: {
7741 SDValue Op1 = getValue(I.getArgOperand(0));
7742 SDValue Op2 = getValue(I.getArgOperand(1));
7743 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7744 return;
7745 }
7746 case Intrinsic::uadd_sat: {
7747 SDValue Op1 = getValue(I.getArgOperand(0));
7748 SDValue Op2 = getValue(I.getArgOperand(1));
7749 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7750 return;
7751 }
7752 case Intrinsic::ssub_sat: {
7753 SDValue Op1 = getValue(I.getArgOperand(0));
7754 SDValue Op2 = getValue(I.getArgOperand(1));
7755 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7756 return;
7757 }
7758 case Intrinsic::usub_sat: {
7759 SDValue Op1 = getValue(I.getArgOperand(0));
7760 SDValue Op2 = getValue(I.getArgOperand(1));
7761 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7762 return;
7763 }
7764 case Intrinsic::sshl_sat:
7765 case Intrinsic::ushl_sat: {
7766 SDValue Op1 = getValue(I.getArgOperand(0));
7767 SDValue Op2 = getValue(I.getArgOperand(1));
7768
7769 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7770 Op1.getValueType(), DAG.getDataLayout());
7771
7772 // Coerce the shift amount to the right type if we can. This exposes the
7773 // truncate or zext to optimization early.
7774 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7775 assert(ShiftTy.getSizeInBits() >=
7777 "Unexpected shift type");
7778 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7779 }
7780
7781 unsigned Opc =
7782 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7783 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7784 return;
7785 }
7786 case Intrinsic::smul_fix:
7787 case Intrinsic::umul_fix:
7788 case Intrinsic::smul_fix_sat:
7789 case Intrinsic::umul_fix_sat: {
7790 SDValue Op1 = getValue(I.getArgOperand(0));
7791 SDValue Op2 = getValue(I.getArgOperand(1));
7792 SDValue Op3 = getValue(I.getArgOperand(2));
7793 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7794 Op1.getValueType(), Op1, Op2, Op3));
7795 return;
7796 }
7797 case Intrinsic::sdiv_fix:
7798 case Intrinsic::udiv_fix:
7799 case Intrinsic::sdiv_fix_sat:
7800 case Intrinsic::udiv_fix_sat: {
7801 SDValue Op1 = getValue(I.getArgOperand(0));
7802 SDValue Op2 = getValue(I.getArgOperand(1));
7803 SDValue Op3 = getValue(I.getArgOperand(2));
7805 Op1, Op2, Op3, DAG, TLI));
7806 return;
7807 }
7808 case Intrinsic::smax: {
7809 SDValue Op1 = getValue(I.getArgOperand(0));
7810 SDValue Op2 = getValue(I.getArgOperand(1));
7811 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7812 return;
7813 }
7814 case Intrinsic::smin: {
7815 SDValue Op1 = getValue(I.getArgOperand(0));
7816 SDValue Op2 = getValue(I.getArgOperand(1));
7817 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7818 return;
7819 }
7820 case Intrinsic::umax: {
7821 SDValue Op1 = getValue(I.getArgOperand(0));
7822 SDValue Op2 = getValue(I.getArgOperand(1));
7823 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7824 return;
7825 }
7826 case Intrinsic::umin: {
7827 SDValue Op1 = getValue(I.getArgOperand(0));
7828 SDValue Op2 = getValue(I.getArgOperand(1));
7829 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7830 return;
7831 }
7832 case Intrinsic::abs: {
7833 SDValue Op1 = getValue(I.getArgOperand(0));
7834 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7835 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7836 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7837 return;
7838 }
7839 case Intrinsic::scmp: {
7840 SDValue Op1 = getValue(I.getArgOperand(0));
7841 SDValue Op2 = getValue(I.getArgOperand(1));
7842 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7843 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7844 break;
7845 }
7846 case Intrinsic::ucmp: {
7847 SDValue Op1 = getValue(I.getArgOperand(0));
7848 SDValue Op2 = getValue(I.getArgOperand(1));
7849 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7850 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7851 break;
7852 }
7853 case Intrinsic::stackaddress:
7854 case Intrinsic::stacksave: {
7855 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7857 SDValue Op = getRoot();
7858 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7859 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7860 setValue(&I, Res);
7861 DAG.setRoot(Res.getValue(1));
7862 return;
7863 }
7864 case Intrinsic::stackrestore:
7865 Res = getValue(I.getArgOperand(0));
7866 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7867 return;
7868 case Intrinsic::get_dynamic_area_offset: {
7869 SDValue Op = getRoot();
7870 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7871 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7872 Op);
7873 DAG.setRoot(Op);
7874 setValue(&I, Res);
7875 return;
7876 }
7877 case Intrinsic::stackguard: {
7878 MachineFunction &MF = DAG.getMachineFunction();
7879 const Module &M = *MF.getFunction().getParent();
7880 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7881 SDValue Chain = getRoot();
7882 if (TLI.useLoadStackGuardNode(M)) {
7883 Res = getLoadStackGuard(DAG, sdl, Chain);
7884 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7885 } else {
7886 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7887 if (!Global) {
7888 LLVMContext &Ctx = *DAG.getContext();
7889 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7890 setValue(&I, DAG.getPOISON(PtrTy));
7891 return;
7892 }
7893
7894 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7895 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7896 MachinePointerInfo(Global, 0), Align,
7898 }
7899 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7900 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7901 // post-RA expansion of LOAD_STACK_GUARD.
7903 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7904 DAG.setRoot(Chain);
7905 setValue(&I, Res);
7906 return;
7907 }
7908 case Intrinsic::stackprotector: {
7909 // Emit code into the DAG to store the stack guard onto the stack.
7910 MachineFunction &MF = DAG.getMachineFunction();
7911 MachineFrameInfo &MFI = MF.getFrameInfo();
7912 const Module &M = *MF.getFunction().getParent();
7913 SDValue Src, Chain = getRoot();
7914
7916 Src = getLoadStackGuard(DAG, sdl, Chain);
7917 else
7918 Src = getValue(I.getArgOperand(0)); // The guard's value.
7919
7920 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7921
7922 int FI = FuncInfo.StaticAllocaMap[Slot];
7923 MFI.setStackProtectorIndex(FI);
7924 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7925
7926 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7927
7928 // Store the stack protector onto the stack.
7929 Res = DAG.getStore(
7930 Chain, sdl, Src, FIN,
7931 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7932 MaybeAlign(), MachineMemOperand::MOVolatile);
7933 setValue(&I, Res);
7934 DAG.setRoot(Res);
7935 return;
7936 }
7937 case Intrinsic::objectsize:
7938 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7939
7940 case Intrinsic::is_constant:
7941 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7942
7943 case Intrinsic::annotation:
7944 case Intrinsic::ptr_annotation:
7945 case Intrinsic::launder_invariant_group:
7946 // Drop the intrinsic, but forward the value
7947 setValue(&I, getValue(I.getOperand(0)));
7948 return;
7949
7950 case Intrinsic::type_test:
7951 case Intrinsic::public_type_test:
7952 case Intrinsic::type_checked_load:
7953 case Intrinsic::type_checked_load_relative: {
7954 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7955 // before code generation. Surviving until here usually indicates a
7956 // misconfiguration, for instance when devirtualization is enabled but LTO
7957 // does not actually run.
7958 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7959 *I.getFunction(),
7960 Intrinsic::getBaseName(Intrinsic) +
7961 " intrinsic must be lowered by the LowerTypeTests pass "
7962 "before code generation",
7963 sdl.getDebugLoc()));
7964
7965 // Lower the result to poison so that compilation can continue and collect
7966 // any further diagnostics.
7967 setValueToPoison(&I, sdl);
7968 return;
7969 }
7970
7971 case Intrinsic::assume:
7972 case Intrinsic::experimental_noalias_scope_decl:
7973 case Intrinsic::var_annotation:
7974 case Intrinsic::sideeffect:
7975 // Discard annotate attributes, noalias scope declarations, assumptions, and
7976 // artificial side-effects.
7977 return;
7978
7979 case Intrinsic::codeview_annotation: {
7980 // Emit a label associated with this metadata.
7981 MachineFunction &MF = DAG.getMachineFunction();
7982 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7983 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7984 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7985 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7986 DAG.setRoot(Res);
7987 return;
7988 }
7989
7990 case Intrinsic::init_trampoline: {
7991 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7992
7993 SDValue Ops[6];
7994 Ops[0] = getRoot();
7995 Ops[1] = getValue(I.getArgOperand(0));
7996 Ops[2] = getValue(I.getArgOperand(1));
7997 Ops[3] = getValue(I.getArgOperand(2));
7998 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7999 Ops[5] = DAG.getSrcValue(F);
8000
8001 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
8002
8003 DAG.setRoot(Res);
8004 return;
8005 }
8006 case Intrinsic::adjust_trampoline:
8007 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
8008 TLI.getPointerTy(DAG.getDataLayout()),
8009 getValue(I.getArgOperand(0))));
8010 return;
8011 case Intrinsic::gcroot: {
8012 assert(DAG.getMachineFunction().getFunction().hasGC() &&
8013 "only valid in functions with gc specified, enforced by Verifier");
8014 assert(GFI && "implied by previous");
8015 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
8016 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
8017
8018 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
8019 GFI->addStackRoot(FI->getIndex(), TypeMap);
8020 return;
8021 }
8022 case Intrinsic::gcread:
8023 case Intrinsic::gcwrite:
8024 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
8025 case Intrinsic::get_rounding:
8026 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
8027 setValue(&I, Res);
8028 DAG.setRoot(Res.getValue(1));
8029 return;
8030
8031 case Intrinsic::expect:
8032 case Intrinsic::expect_with_probability:
8033 // Just replace __builtin_expect(exp, c) and
8034 // __builtin_expect_with_probability(exp, c, p) with EXP.
8035 setValue(&I, getValue(I.getArgOperand(0)));
8036 return;
8037
8038 case Intrinsic::ubsantrap:
8039 case Intrinsic::debugtrap:
8040 case Intrinsic::trap: {
8041 StringRef TrapFuncName =
8042 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
8043 if (TrapFuncName.empty()) {
8044 switch (Intrinsic) {
8045 case Intrinsic::trap:
8046 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
8047 break;
8048 case Intrinsic::debugtrap:
8049 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
8050 break;
8051 case Intrinsic::ubsantrap:
8052 DAG.setRoot(DAG.getNode(
8053 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
8054 DAG.getTargetConstant(
8055 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
8056 MVT::i32)));
8057 break;
8058 default: llvm_unreachable("unknown trap intrinsic");
8059 }
8060 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
8061 I.hasFnAttr(Attribute::NoMerge));
8062 return;
8063 }
8065 if (Intrinsic == Intrinsic::ubsantrap) {
8066 Value *Arg = I.getArgOperand(0);
8067 Args.emplace_back(Arg, getValue(Arg),
8068 LibInfo->getExtAttrForI8Param(/*Signed=*/false));
8069 }
8070
8071 TargetLowering::CallLoweringInfo CLI(DAG);
8072 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
8073 CallingConv::C, I.getType(),
8074 DAG.getExternalSymbol(TrapFuncName.data(),
8075 TLI.getPointerTy(DAG.getDataLayout())),
8076 std::move(Args));
8077 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
8078 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8079 DAG.setRoot(Result.second);
8080 return;
8081 }
8082
8083 case Intrinsic::allow_runtime_check:
8084 case Intrinsic::allow_ubsan_check:
8085 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
8086 return;
8087
8088 case Intrinsic::uadd_with_overflow:
8089 case Intrinsic::sadd_with_overflow:
8090 case Intrinsic::usub_with_overflow:
8091 case Intrinsic::ssub_with_overflow:
8092 case Intrinsic::umul_with_overflow:
8093 case Intrinsic::smul_with_overflow: {
8095 switch (Intrinsic) {
8096 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8097 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
8098 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
8099 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
8100 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
8101 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
8102 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
8103 }
8104 SDValue Op1 = getValue(I.getArgOperand(0));
8105 SDValue Op2 = getValue(I.getArgOperand(1));
8106
8107 EVT ResultVT = Op1.getValueType();
8108 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
8109
8110 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
8111 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
8112 return;
8113 }
8114 case Intrinsic::prefetch: {
8115 SDValue Ops[5];
8116 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8118 Ops[0] = DAG.getRoot();
8119 Ops[1] = getValue(I.getArgOperand(0));
8120 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
8121 MVT::i32);
8122 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
8123 MVT::i32);
8124 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
8125 MVT::i32);
8126 SDValue Result = DAG.getMemIntrinsicNode(
8127 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
8128 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
8129 /* align */ std::nullopt, Flags);
8130
8131 // Chain the prefetch in parallel with any pending loads, to stay out of
8132 // the way of later optimizations.
8133 PendingLoads.push_back(Result);
8134 Result = getRoot();
8135 DAG.setRoot(Result);
8136 return;
8137 }
8138 case Intrinsic::lifetime_start:
8139 case Intrinsic::lifetime_end: {
8140 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
8141 // Stack coloring is not enabled in O0, discard region information.
8142 if (TM.getOptLevel() == CodeGenOptLevel::None)
8143 return;
8144
8145 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
8146 if (!LifetimeObject)
8147 return;
8148
8149 // First check that the Alloca is static, otherwise it won't have a
8150 // valid frame index.
8151 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
8152 if (SI == FuncInfo.StaticAllocaMap.end())
8153 return;
8154
8155 const int FrameIndex = SI->second;
8156 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
8157 DAG.setRoot(Res);
8158 return;
8159 }
8160 case Intrinsic::pseudoprobe: {
8161 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
8162 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8163 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
8164 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
8165 DAG.setRoot(Res);
8166 return;
8167 }
8168 case Intrinsic::invariant_start:
8169 // Discard region information.
8170 setValue(&I,
8171 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
8172 return;
8173 case Intrinsic::invariant_end:
8174 // Discard region information.
8175 return;
8176 case Intrinsic::clear_cache: {
8177 SDValue InputChain = DAG.getRoot();
8178 SDValue StartVal = getValue(I.getArgOperand(0));
8179 SDValue EndVal = getValue(I.getArgOperand(1));
8180 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
8181 {InputChain, StartVal, EndVal});
8182 setValue(&I, Res);
8183 DAG.setRoot(Res);
8184 return;
8185 }
8186 case Intrinsic::donothing:
8187 case Intrinsic::seh_try_begin:
8188 case Intrinsic::seh_scope_begin:
8189 case Intrinsic::seh_try_end:
8190 case Intrinsic::seh_scope_end:
8191 // ignore
8192 return;
8193 case Intrinsic::experimental_stackmap:
8194 visitStackmap(I);
8195 return;
8196 case Intrinsic::experimental_patchpoint_void:
8197 case Intrinsic::experimental_patchpoint:
8198 visitPatchpoint(I);
8199 return;
8200 case Intrinsic::experimental_gc_statepoint:
8202 return;
8203 case Intrinsic::experimental_gc_result:
8204 visitGCResult(cast<GCResultInst>(I));
8205 return;
8206 case Intrinsic::experimental_gc_relocate:
8207 visitGCRelocate(cast<GCRelocateInst>(I));
8208 return;
8209 case Intrinsic::instrprof_cover:
8210 llvm_unreachable("instrprof failed to lower a cover");
8211 case Intrinsic::instrprof_increment:
8212 llvm_unreachable("instrprof failed to lower an increment");
8213 case Intrinsic::instrprof_timestamp:
8214 llvm_unreachable("instrprof failed to lower a timestamp");
8215 case Intrinsic::instrprof_value_profile:
8216 llvm_unreachable("instrprof failed to lower a value profiling call");
8217 case Intrinsic::instrprof_mcdc_parameters:
8218 llvm_unreachable("instrprof failed to lower mcdc parameters");
8219 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8220 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8221 case Intrinsic::localescape: {
8222 MachineFunction &MF = DAG.getMachineFunction();
8223 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8224
8225 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8226 // is the same on all targets.
8227 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8228 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8229 if (isa<ConstantPointerNull>(Arg))
8230 continue; // Skip null pointers. They represent a hole in index space.
8231 AllocaInst *Slot = cast<AllocaInst>(Arg);
8232 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8233 "can only escape static allocas");
8234 int FI = FuncInfo.StaticAllocaMap[Slot];
8235 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8238 TII->get(TargetOpcode::LOCAL_ESCAPE))
8239 .addSym(FrameAllocSym)
8240 .addFrameIndex(FI);
8241 }
8242
8243 return;
8244 }
8245
8246 case Intrinsic::localrecover: {
8247 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8248 MachineFunction &MF = DAG.getMachineFunction();
8249
8250 // Get the symbol that defines the frame offset.
8251 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8252 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8253 unsigned IdxVal =
8254 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8255 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8257
8258 Value *FP = I.getArgOperand(1);
8259 SDValue FPVal = getValue(FP);
8260 EVT PtrVT = FPVal.getValueType();
8261
8262 // Create a MCSymbol for the label to avoid any target lowering
8263 // that would make this PC relative.
8264 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8265 SDValue OffsetVal =
8266 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8267
8268 // Add the offset to the FP.
8269 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8270 setValue(&I, Add);
8271
8272 return;
8273 }
8274
8275 case Intrinsic::fake_use: {
8276 Value *V = I.getArgOperand(0);
8277 SDValue Ops[2];
8278 // For Values not declared or previously used in this basic block, the
8279 // NodeMap will not have an entry, and `getValue` will assert if V has no
8280 // valid register value.
8281 auto FakeUseValue = [&]() -> SDValue {
8282 SDValue &N = NodeMap[V];
8283 if (N.getNode())
8284 return N;
8285
8286 // If there's a virtual register allocated and initialized for this
8287 // value, use it.
8288 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8289 return copyFromReg;
8290 // FIXME: Do we want to preserve constants? It seems pointless.
8291 if (isa<Constant>(V))
8292 return getValue(V);
8293 return SDValue();
8294 }();
8295 if (!FakeUseValue || FakeUseValue.isUndef())
8296 return;
8297 Ops[0] = getRoot();
8298 Ops[1] = FakeUseValue;
8299 // Also, do not translate a fake use with an undef operand, or any other
8300 // empty SDValues.
8301 if (!Ops[1] || Ops[1].isUndef())
8302 return;
8303 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8304 return;
8305 }
8306
8307 case Intrinsic::reloc_none: {
8308 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8309 StringRef SymbolName = cast<MDString>(MD)->getString();
8310 SDValue Ops[2] = {
8311 getRoot(),
8312 DAG.getTargetExternalSymbol(
8313 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8314 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8315 return;
8316 }
8317
8318 case Intrinsic::cond_loop: {
8319 SDValue InputChain = DAG.getRoot();
8320 SDValue P = getValue(I.getArgOperand(0));
8321 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8322 {InputChain, P});
8323 setValue(&I, Res);
8324 DAG.setRoot(Res);
8325 return;
8326 }
8327
8328 case Intrinsic::eh_exceptionpointer:
8329 case Intrinsic::eh_exceptioncode: {
8330 // Get the exception pointer vreg, copy from it, and resize it to fit.
8331 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8332 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8333 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8334 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8335 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8336 if (Intrinsic == Intrinsic::eh_exceptioncode)
8337 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8338 setValue(&I, N);
8339 return;
8340 }
8341 case Intrinsic::xray_customevent: {
8342 // Here we want to make sure that the intrinsic behaves as if it has a
8343 // specific calling convention.
8344 const auto &Triple = DAG.getTarget().getTargetTriple();
8345 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8346 Triple.getArch() != Triple::hexagon)
8347 return;
8348
8350
8351 // We want to say that we always want the arguments in registers.
8352 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8353 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8354 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8355 SDValue Chain = getRoot();
8356 Ops.push_back(LogEntryVal);
8357 Ops.push_back(StrSizeVal);
8358 Ops.push_back(Chain);
8359
8360 // We need to enforce the calling convention for the callsite, so that
8361 // argument ordering is enforced correctly, and that register allocation can
8362 // see that some registers may be assumed clobbered and have to preserve
8363 // them across calls to the intrinsic.
8364 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8365 sdl, NodeTys, Ops);
8366 SDValue patchableNode = SDValue(MN, 0);
8367 DAG.setRoot(patchableNode);
8368 setValue(&I, patchableNode);
8369 return;
8370 }
8371 case Intrinsic::xray_typedevent: {
8372 // Here we want to make sure that the intrinsic behaves as if it has a
8373 // specific calling convention.
8374 const auto &Triple = DAG.getTarget().getTargetTriple();
8375 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8376 Triple.getArch() != Triple::hexagon)
8377 return;
8378
8380
8381 // We want to say that we always want the arguments in registers.
8382 // It's unclear to me how manipulating the selection DAG here forces callers
8383 // to provide arguments in registers instead of on the stack.
8384 SDValue LogTypeId = getValue(I.getArgOperand(0));
8385 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8386 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8387 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8388 SDValue Chain = getRoot();
8389 Ops.push_back(LogTypeId);
8390 Ops.push_back(LogEntryVal);
8391 Ops.push_back(StrSizeVal);
8392 Ops.push_back(Chain);
8393
8394 // We need to enforce the calling convention for the callsite, so that
8395 // argument ordering is enforced correctly, and that register allocation can
8396 // see that some registers may be assumed clobbered and have to preserve
8397 // them across calls to the intrinsic.
8398 MachineSDNode *MN = DAG.getMachineNode(
8399 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8400 SDValue patchableNode = SDValue(MN, 0);
8401 DAG.setRoot(patchableNode);
8402 setValue(&I, patchableNode);
8403 return;
8404 }
8405 case Intrinsic::experimental_deoptimize:
8407 return;
8408 case Intrinsic::stepvector:
8409 visitStepVector(I);
8410 return;
8411 case Intrinsic::vector_reduce_fadd:
8412 case Intrinsic::vector_reduce_fmul:
8413 case Intrinsic::vector_reduce_add:
8414 case Intrinsic::vector_reduce_mul:
8415 case Intrinsic::vector_reduce_and:
8416 case Intrinsic::vector_reduce_or:
8417 case Intrinsic::vector_reduce_xor:
8418 case Intrinsic::vector_reduce_smax:
8419 case Intrinsic::vector_reduce_smin:
8420 case Intrinsic::vector_reduce_umax:
8421 case Intrinsic::vector_reduce_umin:
8422 case Intrinsic::vector_reduce_fmax:
8423 case Intrinsic::vector_reduce_fmin:
8424 case Intrinsic::vector_reduce_fmaximum:
8425 case Intrinsic::vector_reduce_fminimum:
8426 case Intrinsic::vector_reduce_fmaximumnum:
8427 case Intrinsic::vector_reduce_fminimumnum:
8428 visitVectorReduce(I, Intrinsic);
8429 return;
8430
8431 case Intrinsic::icall_branch_funnel: {
8433 Ops.push_back(getValue(I.getArgOperand(0)));
8434
8435 int64_t Offset;
8437 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8438 if (!Base)
8440 "llvm.icall.branch.funnel operand must be a GlobalValue");
8441 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8442
8443 struct BranchFunnelTarget {
8444 int64_t Offset;
8446 };
8448
8449 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8451 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8452 if (ElemBase != Base)
8453 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8454 "to the same GlobalValue");
8455
8456 SDValue Val = getValue(I.getArgOperand(Op + 1));
8457 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8458 if (!GA)
8460 "llvm.icall.branch.funnel operand must be a GlobalValue");
8461 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8462 GA->getGlobal(), sdl, Val.getValueType(),
8463 GA->getOffset())});
8464 }
8465 llvm::sort(Targets,
8466 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8467 return T1.Offset < T2.Offset;
8468 });
8469
8470 for (auto &T : Targets) {
8471 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8472 Ops.push_back(T.Target);
8473 }
8474
8475 Ops.push_back(DAG.getRoot()); // Chain
8476 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8477 MVT::Other, Ops),
8478 0);
8479 DAG.setRoot(N);
8480 setValue(&I, N);
8481 HasTailCall = true;
8482 return;
8483 }
8484
8485 case Intrinsic::wasm_landingpad_index:
8486 // Information this intrinsic contained has been transferred to
8487 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8488 // delete it now.
8489 return;
8490
8491 case Intrinsic::aarch64_settag:
8492 case Intrinsic::aarch64_settag_zero: {
8493 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8494 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8496 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8497 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8498 ZeroMemory);
8499 DAG.setRoot(Val);
8500 setValue(&I, Val);
8501 return;
8502 }
8503 case Intrinsic::amdgcn_cs_chain: {
8504 // At this point we don't care if it's amdgpu_cs_chain or
8505 // amdgpu_cs_chain_preserve.
8507
8508 Type *RetTy = I.getType();
8509 assert(RetTy->isVoidTy() && "Should not return");
8510
8511 SDValue Callee = getValue(I.getOperand(0));
8512
8513 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8514 // We'll also tack the value of the EXEC mask at the end.
8516 Args.reserve(3);
8517
8518 for (unsigned Idx : {2, 3, 1}) {
8519 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8520 I.getOperand(Idx)->getType());
8521 Arg.setAttributes(&I, Idx);
8522 Args.push_back(Arg);
8523 }
8524
8525 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8526 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8527 Args[2].IsInReg = true; // EXEC should be inreg
8528
8529 // Forward the flags and any additional arguments.
8530 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8531 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8532 I.getOperand(Idx)->getType());
8533 Arg.setAttributes(&I, Idx);
8534 Args.push_back(Arg);
8535 }
8536
8537 TargetLowering::CallLoweringInfo CLI(DAG);
8538 CLI.setDebugLoc(getCurSDLoc())
8539 .setChain(getRoot())
8540 .setCallee(CC, RetTy, Callee, std::move(Args))
8541 .setNoReturn(true)
8542 .setTailCall(true)
8543 .setConvergent(I.isConvergent());
8544 CLI.CB = &I;
8545 std::pair<SDValue, SDValue> Result =
8546 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8547 (void)Result;
8548 assert(!Result.first.getNode() && !Result.second.getNode() &&
8549 "Should've lowered as tail call");
8550
8551 HasTailCall = true;
8552 return;
8553 }
8554 case Intrinsic::amdgcn_call_whole_wave: {
8556 bool isTailCall = I.isTailCall();
8557
8558 // The first argument is the callee. Skip it when assembling the call args.
8559 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8560 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8561 I.getArgOperand(Idx)->getType());
8562 Arg.setAttributes(&I, Idx);
8563
8564 // If we have an explicit sret argument that is an Instruction, (i.e., it
8565 // might point to function-local memory), we can't meaningfully tail-call.
8566 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8567 isTailCall = false;
8568
8569 Args.push_back(Arg);
8570 }
8571
8572 SDValue ConvControlToken;
8573 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8574 auto *Token = Bundle->Inputs[0].get();
8575 ConvControlToken = getValue(Token);
8576 }
8577
8578 TargetLowering::CallLoweringInfo CLI(DAG);
8579 CLI.setDebugLoc(getCurSDLoc())
8580 .setChain(getRoot())
8581 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8582 getValue(I.getArgOperand(0)), std::move(Args))
8583 .setTailCall(isTailCall && canTailCall(I))
8584 .setIsPreallocated(
8585 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8586 .setConvergent(I.isConvergent())
8587 .setConvergenceControlToken(ConvControlToken);
8588 CLI.CB = &I;
8589
8590 std::pair<SDValue, SDValue> Result =
8591 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8592
8593 if (Result.first.getNode())
8594 setValue(&I, Result.first);
8595 return;
8596 }
8597 case Intrinsic::ptrmask: {
8598 SDValue Ptr = getValue(I.getOperand(0));
8599 SDValue Mask = getValue(I.getOperand(1));
8600
8601 // On arm64_32, pointers are 32 bits when stored in memory, but
8602 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8603 // match the index type, but the pointer is 64 bits, so the mask must be
8604 // zero-extended up to 64 bits to match the pointer.
8605 EVT PtrVT =
8606 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8607 EVT MemVT =
8608 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8609 assert(PtrVT == Ptr.getValueType());
8610 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8611 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8612 // 128-bit, so we have to pad the mask with ones for unused bits.
8613 auto HighOnes = DAG.getNode(
8614 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8615 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8616 PtrVT, sdl));
8617 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8618 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8619 } else if (Mask.getValueType() != PtrVT)
8620 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8621
8622 assert(Mask.getValueType() == PtrVT);
8623 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8624 return;
8625 }
8626 case Intrinsic::threadlocal_address: {
8627 setValue(&I, getValue(I.getOperand(0)));
8628 return;
8629 }
8630 case Intrinsic::get_active_lane_mask: {
8631 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8632 SDValue Index = getValue(I.getOperand(0));
8633 SDValue TripCount = getValue(I.getOperand(1));
8634 EVT ElementVT = Index.getValueType();
8635
8636 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8637 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8638 TripCount));
8639 return;
8640 }
8641
8642 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8643 CCVT.getVectorElementCount());
8644
8645 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8646 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8647 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8648 SDValue VectorInduction = DAG.getNode(
8649 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8650 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8651 VectorTripCount, ISD::CondCode::SETULT);
8652 setValue(&I, SetCC);
8653 return;
8654 }
8655 case Intrinsic::mask_beforefirst: {
8656 SDValue Op = getValue(I.getOperand(0));
8657 setValue(&I,
8658 DAG.getNode(ISD::MASK_BEFOREFIRST, sdl, Op.getValueType(), Op));
8659 return;
8660 }
8661 case Intrinsic::experimental_get_vector_length: {
8662 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8663 "Expected positive VF");
8664 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8665 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8666
8667 SDValue Count = getValue(I.getOperand(0));
8668 EVT CountVT = Count.getValueType();
8669
8670 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8671 visitTargetIntrinsic(I, Intrinsic);
8672 return;
8673 }
8674
8675 // Expand to a umin between the trip count and the maximum elements the type
8676 // can hold.
8677 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8678
8679 // Extend the trip count to at least the result VT.
8680 if (CountVT.bitsLT(VT)) {
8681 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8682 CountVT = VT;
8683 }
8684
8685 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8687
8688 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8689 // Clip to the result type if needed.
8690 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8691
8692 setValue(&I, Trunc);
8693 return;
8694 }
8695 case Intrinsic::vector_partial_reduce_add: {
8696 SDValue Acc = getValue(I.getOperand(0));
8697 SDValue Input = getValue(I.getOperand(1));
8698 setValue(&I,
8699 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8700 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8701 return;
8702 }
8703 case Intrinsic::vector_partial_reduce_fadd: {
8704 SDNodeFlags Flags;
8705 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
8706 Flags.copyFMF(*FPOp);
8707 SDValue Acc = getValue(I.getOperand(0));
8708 SDValue Input = getValue(I.getOperand(1));
8709 setValue(&I, DAG.getNode(ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(),
8710 Acc, Input,
8711 DAG.getConstantFP(1.0, sdl, Input.getValueType()),
8712 Flags));
8713 return;
8714 }
8715 case Intrinsic::experimental_cttz_elts: {
8716 SDValue Op = getValue(I.getOperand(0));
8717 EVT OpVT = Op.getValueType();
8718 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8719 bool ZeroIsPoison =
8720 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8721 if (OpVT.getVectorElementType() != MVT::i1) {
8722 // Compare the input vector elements to zero & use to count trailing
8723 // zeros.
8724 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8725 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8726 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8727 }
8728 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8730 sdl, RetTy, Op));
8731 return;
8732 }
8733 case Intrinsic::vector_insert: {
8734 SDValue Vec = getValue(I.getOperand(0));
8735 SDValue SubVec = getValue(I.getOperand(1));
8736 SDValue Index = getValue(I.getOperand(2));
8737
8738 // The intrinsic's index type is i64, but the SDNode requires an index type
8739 // suitable for the target. Convert the index as required.
8740 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8741 if (Index.getValueType() != VectorIdxTy)
8742 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8743
8744 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8745 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8746 Index));
8747 return;
8748 }
8749 case Intrinsic::vector_extract: {
8750 SDValue Vec = getValue(I.getOperand(0));
8751 SDValue Index = getValue(I.getOperand(1));
8752 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8753
8754 // The intrinsic's index type is i64, but the SDNode requires an index type
8755 // suitable for the target. Convert the index as required.
8756 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8757 if (Index.getValueType() != VectorIdxTy)
8758 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8759
8760 setValue(&I,
8761 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8762 return;
8763 }
8764 case Intrinsic::experimental_vector_match: {
8765 SDValue Op1 = getValue(I.getOperand(0));
8766 SDValue Op2 = getValue(I.getOperand(1));
8767 SDValue Mask = getValue(I.getOperand(2));
8768 EVT ResVT = Mask.getValueType();
8769 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8770 return;
8771 }
8772 case Intrinsic::vector_reverse:
8773 visitVectorReverse(I);
8774 return;
8775 case Intrinsic::vector_splice_left:
8776 case Intrinsic::vector_splice_right:
8777 visitVectorSplice(I);
8778 return;
8779 case Intrinsic::callbr_landingpad:
8780 visitCallBrLandingPad(I);
8781 return;
8782 case Intrinsic::vector_interleave2:
8783 visitVectorInterleave(I, 2);
8784 return;
8785 case Intrinsic::vector_interleave3:
8786 visitVectorInterleave(I, 3);
8787 return;
8788 case Intrinsic::vector_interleave4:
8789 visitVectorInterleave(I, 4);
8790 return;
8791 case Intrinsic::vector_interleave5:
8792 visitVectorInterleave(I, 5);
8793 return;
8794 case Intrinsic::vector_interleave6:
8795 visitVectorInterleave(I, 6);
8796 return;
8797 case Intrinsic::vector_interleave7:
8798 visitVectorInterleave(I, 7);
8799 return;
8800 case Intrinsic::vector_interleave8:
8801 visitVectorInterleave(I, 8);
8802 return;
8803 case Intrinsic::vector_deinterleave2:
8804 visitVectorDeinterleave(I, 2);
8805 return;
8806 case Intrinsic::vector_deinterleave3:
8807 visitVectorDeinterleave(I, 3);
8808 return;
8809 case Intrinsic::vector_deinterleave4:
8810 visitVectorDeinterleave(I, 4);
8811 return;
8812 case Intrinsic::vector_deinterleave5:
8813 visitVectorDeinterleave(I, 5);
8814 return;
8815 case Intrinsic::vector_deinterleave6:
8816 visitVectorDeinterleave(I, 6);
8817 return;
8818 case Intrinsic::vector_deinterleave7:
8819 visitVectorDeinterleave(I, 7);
8820 return;
8821 case Intrinsic::vector_deinterleave8:
8822 visitVectorDeinterleave(I, 8);
8823 return;
8824 case Intrinsic::vector_repeat: {
8825 SDValue Vec = getValue(I.getOperand(0));
8826 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8827 setValue(&I, DAG.getNode(ISD::VECTOR_REPEAT, sdl, ResultVT, Vec));
8828 return;
8829 }
8830 case Intrinsic::experimental_vector_compress:
8831 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8832 getValue(I.getArgOperand(0)).getValueType(),
8833 getValue(I.getArgOperand(0)),
8834 getValue(I.getArgOperand(1)),
8835 getValue(I.getArgOperand(2)), Flags));
8836 return;
8837 case Intrinsic::vector_shuffle:
8838 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE_VAR, sdl,
8839 TLI.getValueType(DAG.getDataLayout(), I.getType()),
8840 getValue(I.getArgOperand(0)),
8841 getValue(I.getArgOperand(1)), Flags));
8842 return;
8843 case Intrinsic::experimental_convergence_anchor:
8844 case Intrinsic::experimental_convergence_entry:
8845 case Intrinsic::experimental_convergence_loop:
8846 visitConvergenceControl(I, Intrinsic);
8847 return;
8848 case Intrinsic::experimental_vector_histogram_add: {
8849 visitVectorHistogram(I, Intrinsic);
8850 return;
8851 }
8852 case Intrinsic::experimental_vector_extract_last_active: {
8853 visitVectorExtractLastActive(I, Intrinsic);
8854 return;
8855 }
8856 case Intrinsic::loop_dependence_war_mask:
8857 setValue(&I,
8859 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8860 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8861 DAG.getConstant(0, sdl, MVT::i64)));
8862 return;
8863 case Intrinsic::loop_dependence_raw_mask:
8864 setValue(&I,
8866 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8867 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8868 DAG.getConstant(0, sdl, MVT::i64)));
8869 return;
8870 case Intrinsic::masked_udiv:
8871 setValue(&I,
8872 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8873 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8874 getValue(I.getOperand(2))));
8875 return;
8876 case Intrinsic::masked_sdiv:
8877 setValue(&I,
8878 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8879 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8880 getValue(I.getOperand(2))));
8881 return;
8882 case Intrinsic::masked_urem:
8883 setValue(&I,
8884 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8885 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8886 getValue(I.getOperand(2))));
8887 return;
8888 case Intrinsic::masked_srem:
8889 setValue(&I,
8890 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8891 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8892 getValue(I.getOperand(2))));
8893 return;
8894 }
8895}
8896
8897void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8899 assert(Result.getNode()->getNumValues() == 2);
8900 SDValue OutChain = Result.getValue(1);
8901 assert(OutChain.getValueType() == MVT::Other);
8902
8903 // Instead of updating the root immediately, push the produced chain to the
8904 // appropriate list, deferring the update until the root is requested. In this
8905 // case, the nodes from the lists are chained using TokenFactor, indicating
8906 // that the operations are independent.
8907 //
8908 // In particular, the root is updated before any call that might access the
8909 // floating-point environment, except for constrained intrinsics.
8910 switch (EB) {
8913 PendingConstrainedFP.push_back(OutChain);
8914 break;
8916 PendingConstrainedFPStrict.push_back(OutChain);
8917 break;
8918 }
8919}
8920
8921void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8922 const ConstrainedFPIntrinsic &FPI) {
8923 SDLoc sdl = getCurSDLoc();
8924
8925 // We do not need to serialize constrained FP intrinsics against
8926 // each other or against (nonvolatile) loads, so they can be
8927 // chained like loads.
8929 SDValue Chain = getFPOperationRoot(EB);
8931 Opers.push_back(Chain);
8932 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8933 Opers.push_back(getValue(FPI.getArgOperand(I)));
8934
8935 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8936 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8937 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8938
8939 SDNodeFlags Flags;
8941 Flags.setNoFPExcept(true);
8942
8943 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8944 Flags.copyFMF(*FPOp);
8945
8946 unsigned Opcode;
8947 switch (FPI.getIntrinsicID()) {
8948 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8949#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8950 case Intrinsic::INTRINSIC: \
8951 Opcode = ISD::STRICT_##DAGN; \
8952 break;
8953#include "llvm/IR/ConstrainedOps.def"
8954 case Intrinsic::experimental_constrained_fmuladd: {
8955 Opcode = ISD::STRICT_FMA;
8956 // Break fmuladd into fmul and fadd.
8957 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8958 Opers.pop_back();
8959 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8960 pushFPOpOutChain(Mul, EB);
8961 Opcode = ISD::STRICT_FADD;
8962 Opers.clear();
8963 Opers.push_back(Mul.getValue(1));
8964 Opers.push_back(Mul.getValue(0));
8965 Opers.push_back(getValue(FPI.getArgOperand(2)));
8966 }
8967 break;
8968 }
8969 }
8970
8971 // A few strict DAG nodes carry additional operands that are not
8972 // set up by the default code above.
8973 switch (Opcode) {
8974 default: break;
8976 Opers.push_back(
8977 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8978 break;
8979 case ISD::STRICT_FSETCC:
8980 case ISD::STRICT_FSETCCS: {
8981 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8982 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8983 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8984 Condition = getFCmpCodeWithoutNaN(Condition);
8985 Opers.push_back(DAG.getCondCode(Condition));
8986 break;
8987 }
8988 }
8989
8990 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8991 pushFPOpOutChain(Result, EB);
8992
8993 SDValue FPResult = Result.getValue(0);
8994 setValue(&FPI, FPResult);
8995}
8996
8997static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8998 std::optional<unsigned> ResOPC;
8999 switch (VPIntrin.getIntrinsicID()) {
9000 case Intrinsic::vp_cttz_elts: {
9001 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
9002 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
9003 break;
9004 }
9005#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
9006 case Intrinsic::VPID: \
9007 ResOPC = ISD::VPSD; \
9008 break;
9009#include "llvm/IR/VPIntrinsics.def"
9010 }
9011
9012 if (!ResOPC)
9014 "Inconsistency: no SDNode available for this VPIntrinsic!");
9015
9016 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
9017 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
9018 if (VPIntrin.getFastMathFlags().allowReassoc())
9019 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
9020 : ISD::VP_REDUCE_FMUL;
9021 }
9022
9023 return *ResOPC;
9024}
9025
9026void SelectionDAGBuilder::visitVPLoad(
9027 const VPIntrinsic &VPIntrin, EVT VT,
9028 const SmallVectorImpl<SDValue> &OpValues) {
9029 SDLoc DL = getCurSDLoc();
9030 Value *PtrOperand = VPIntrin.getArgOperand(0);
9031 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9032 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9033 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9034 SDValue LD;
9035 // Do not serialize variable-length loads of constant memory with
9036 // anything.
9037 if (!Alignment)
9038 Alignment = DAG.getEVTAlign(VT);
9039 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9040 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9041 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9042 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9043 MachineMemOperand::Flags MMOFlags =
9045 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9046 MachinePointerInfo(PtrOperand), MMOFlags,
9048 MMOMetadata(AAInfo, Ranges));
9049 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9050 MMO, false /*IsExpanding */);
9051 if (AddToChain)
9052 PendingLoads.push_back(LD.getValue(1));
9053 setValue(&VPIntrin, LD);
9054}
9055
9056void SelectionDAGBuilder::visitVPLoadFF(
9057 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
9058 const SmallVectorImpl<SDValue> &OpValues) {
9059 assert(OpValues.size() == 3 && "Unexpected number of operands");
9060 SDLoc DL = getCurSDLoc();
9061 Value *PtrOperand = VPIntrin.getArgOperand(0);
9062 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9063 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9064 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
9065 SDValue LD;
9066 // Do not serialize variable-length loads of constant memory with
9067 // anything.
9068 if (!Alignment)
9069 Alignment = DAG.getEVTAlign(VT);
9070 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9071 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9072 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9073 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9074 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
9076 MMOMetadata(AAInfo, Ranges));
9077 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9078 MMO);
9079 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
9080 if (AddToChain)
9081 PendingLoads.push_back(LD.getValue(2));
9082 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
9083}
9084
9085void SelectionDAGBuilder::visitVPGather(
9086 const VPIntrinsic &VPIntrin, EVT VT,
9087 const SmallVectorImpl<SDValue> &OpValues) {
9088 SDLoc DL = getCurSDLoc();
9089 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9090 Value *PtrOperand = VPIntrin.getArgOperand(0);
9091 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9092 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9093 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9094 SDValue LD;
9095 if (!Alignment)
9096 Alignment = DAG.getEVTAlign(VT.getScalarType());
9097 unsigned AS =
9098 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9099 MachineMemOperand::Flags MMOFlags =
9101 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9102 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9103 *Alignment, MMOMetadata(AAInfo, Ranges));
9104 SDValue Base, Index, Scale;
9105 bool UniformBase =
9106 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9107 VT.getScalarStoreSize());
9108 if (!UniformBase) {
9109 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9110 Index = getValue(PtrOperand);
9111 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9112 }
9113 EVT IdxVT = Index.getValueType();
9114 EVT EltTy = IdxVT.getVectorElementType();
9115 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9116 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9117 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9118 }
9119 LD = DAG.getGatherVP(
9120 DAG.getVTList(VT, MVT::Other), VT, DL,
9121 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
9123 PendingLoads.push_back(LD.getValue(1));
9124 setValue(&VPIntrin, LD);
9125}
9126
9127void SelectionDAGBuilder::visitVPStore(
9128 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9129 SDLoc DL = getCurSDLoc();
9130 Value *PtrOperand = VPIntrin.getArgOperand(1);
9131 EVT VT = OpValues[0].getValueType();
9132 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9133 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9134 SDValue ST;
9135 if (!Alignment)
9136 Alignment = DAG.getEVTAlign(VT);
9137 SDValue Ptr = OpValues[1];
9138 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
9139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9140 MachineMemOperand::Flags MMOFlags =
9142 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9143 MachinePointerInfo(PtrOperand), MMOFlags,
9144 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
9145 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
9146 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
9147 /* IsTruncating */ false, /*IsCompressing*/ false);
9148 DAG.setRoot(ST);
9149 setValue(&VPIntrin, ST);
9150}
9151
9152void SelectionDAGBuilder::visitVPScatter(
9153 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9154 SDLoc DL = getCurSDLoc();
9155 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9156 Value *PtrOperand = VPIntrin.getArgOperand(1);
9157 EVT VT = OpValues[0].getValueType();
9158 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9159 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9160 SDValue ST;
9161 if (!Alignment)
9162 Alignment = DAG.getEVTAlign(VT.getScalarType());
9163 unsigned AS =
9164 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9165 MachineMemOperand::Flags MMOFlags =
9167 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9168 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9169 *Alignment, AAInfo);
9170 SDValue Base, Index, Scale;
9171 bool UniformBase =
9172 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9173 VT.getScalarStoreSize());
9174 if (!UniformBase) {
9175 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9176 Index = getValue(PtrOperand);
9177 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9178 }
9179 EVT IdxVT = Index.getValueType();
9180 EVT EltTy = IdxVT.getVectorElementType();
9181 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9182 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9183 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9184 }
9185 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
9186 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9187 OpValues[2], OpValues[3]},
9188 MMO, ISD::SIGNED_SCALED);
9189 DAG.setRoot(ST);
9190 setValue(&VPIntrin, ST);
9191}
9192
9193void SelectionDAGBuilder::visitVPStridedLoad(
9194 const VPIntrinsic &VPIntrin, EVT VT,
9195 const SmallVectorImpl<SDValue> &OpValues) {
9196 SDLoc DL = getCurSDLoc();
9197 Value *PtrOperand = VPIntrin.getArgOperand(0);
9198 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9199 if (!Alignment)
9200 Alignment = DAG.getEVTAlign(VT.getScalarType());
9201 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9202 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9203 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9204 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9205 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9206 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9207 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9208 MachineMemOperand::Flags MMOFlags =
9210 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9211 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9212 *Alignment, MMOMetadata(AAInfo, Ranges));
9213
9214 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
9215 OpValues[2], OpValues[3], MMO,
9216 false /*IsExpanding*/);
9217
9218 if (AddToChain)
9219 PendingLoads.push_back(LD.getValue(1));
9220 setValue(&VPIntrin, LD);
9221}
9222
9223void SelectionDAGBuilder::visitVPStridedStore(
9224 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9225 SDLoc DL = getCurSDLoc();
9226 Value *PtrOperand = VPIntrin.getArgOperand(1);
9227 EVT VT = OpValues[0].getValueType();
9228 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9229 if (!Alignment)
9230 Alignment = DAG.getEVTAlign(VT.getScalarType());
9231 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9232 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9233 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9234 MachineMemOperand::Flags MMOFlags =
9236 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9237 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9238 *Alignment, AAInfo);
9239
9240 SDValue ST = DAG.getStridedStoreVP(
9241 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9242 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9243 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9244 /*IsCompressing*/ false);
9245
9246 DAG.setRoot(ST);
9247 setValue(&VPIntrin, ST);
9248}
9249
9250void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9251 const VPIntrinsic &VPIntrin) {
9252 SDLoc DL = getCurSDLoc();
9253 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9254
9255 auto IID = VPIntrin.getIntrinsicID();
9256
9257 SmallVector<EVT, 4> ValueVTs;
9258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9259 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9260 SDVTList VTs = DAG.getVTList(ValueVTs);
9261
9262 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9263
9264 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9265 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9266 "Unexpected target EVL type");
9267
9268 // Request operands.
9269 SmallVector<SDValue, 7> OpValues;
9270 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9271 auto Op = getValue(VPIntrin.getArgOperand(I));
9272 if (I == EVLParamPos)
9273 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9274 OpValues.push_back(Op);
9275 }
9276
9277 switch (Opcode) {
9278 default: {
9279 SDNodeFlags SDFlags;
9280 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9281 SDFlags.copyFMF(*FPMO);
9282 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9283 setValue(&VPIntrin, Result);
9284 break;
9285 }
9286 case ISD::VP_LOAD:
9287 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9288 break;
9289 case ISD::VP_LOAD_FF:
9290 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9291 break;
9292 case ISD::VP_GATHER:
9293 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9294 break;
9295 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9296 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9297 break;
9298 case ISD::VP_STORE:
9299 visitVPStore(VPIntrin, OpValues);
9300 break;
9301 case ISD::VP_SCATTER:
9302 visitVPScatter(VPIntrin, OpValues);
9303 break;
9304 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9305 visitVPStridedStore(VPIntrin, OpValues);
9306 break;
9307 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9308 case ISD::VP_CTTZ_ELTS: {
9309 SDValue Result =
9310 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9311 setValue(&VPIntrin, Result);
9312 break;
9313 }
9314 }
9315}
9316
9318 const BasicBlock *EHPadBB,
9319 MCSymbol *&BeginLabel) {
9320 MachineFunction &MF = DAG.getMachineFunction();
9321
9322 // Skip emitting EH_LABEL on targets whose exception tables don't reference
9323 // them (32-bit x86 SEH, Wasm).
9325 FuncInfo.ExceptionModel)) {
9326 BeginLabel = nullptr;
9327 return Chain;
9328 }
9329
9330 // Insert a label before the invoke call to mark the try range. This can be
9331 // used to detect deletion of the invoke via the MachineModuleInfo.
9332 BeginLabel = MF.getContext().createTempSymbol();
9333
9334 // For SjLj, keep track of which landing pads go with which invokes
9335 // so as to maintain the ordering of pads in the LSDA.
9336 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9337 if (CallSiteIndex) {
9338 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9339 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9340
9341 // Now that the call site is handled, stop tracking it.
9342 FuncInfo.setCurrentCallSite(0);
9343 }
9344
9345 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9346}
9347
9348SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9349 const BasicBlock *EHPadBB,
9350 MCSymbol *BeginLabel) {
9351 // No labels were emitted.
9352 if (!BeginLabel)
9353 return Chain;
9354
9356
9357 // Insert a label at the end of the invoke call to mark the try range. This
9358 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9359 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9360 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9361
9362 // Inform MachineModuleInfo of range.
9364 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9365 // actually use outlined funclets and their LSDA info style.
9366 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9367 assert(II && "II should've been set");
9368 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9369 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9370 } else if (!isScopedEHPersonality(Pers)) {
9371 assert(EHPadBB);
9372 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9373 }
9374
9375 return Chain;
9376}
9377
9378std::pair<SDValue, SDValue>
9380 const BasicBlock *EHPadBB) {
9381 MCSymbol *BeginLabel = nullptr;
9382
9383 if (EHPadBB) {
9384 // Both PendingLoads and PendingExports must be flushed here;
9385 // this call might not return.
9386 (void)getRoot();
9387 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9388 CLI.setChain(getRoot());
9389 }
9390
9391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9392 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9393
9394 assert((CLI.IsTailCall || Result.second.getNode()) &&
9395 "Non-null chain expected with non-tail call!");
9396 assert((Result.second.getNode() || !Result.first.getNode()) &&
9397 "Null value expected with tail call!");
9398
9399 if (!Result.second.getNode()) {
9400 // As a special case, a null chain means that a tail call has been emitted
9401 // and the DAG root is already updated.
9402 HasTailCall = true;
9403
9404 // Since there's no actual continuation from this block, nothing can be
9405 // relying on us setting vregs for them.
9406 PendingExports.clear();
9407 } else {
9408 DAG.setRoot(Result.second);
9409 }
9410
9411 if (EHPadBB) {
9412 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9413 BeginLabel));
9414 Result.second = getRoot();
9415 }
9416
9417 return Result;
9418}
9419
9421 bool isMustTailCall = CB.isMustTailCall();
9422
9423 // Avoid emitting tail calls in functions with the disable-tail-calls
9424 // attribute.
9425 const Function *Caller = CB.getParent()->getParent();
9426 if (!isMustTailCall &&
9427 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9428 return false;
9429
9430 // We can't tail call inside a function with a swifterror argument. Lowering
9431 // does not support this yet. It would have to move into the swifterror
9432 // register before the call.
9433 if (DAG.hasSwiftErrorArg())
9434 return false;
9435
9436 // Check if target-independent constraints permit a tail call here.
9437 // Target-dependent constraints are checked within TLI->LowerCallTo.
9438 return isInTailCallPosition(CB, DAG.getTarget());
9439}
9440
9442 bool isTailCall, bool isMustTailCall,
9443 const BasicBlock *EHPadBB,
9444 const TargetLowering::PtrAuthInfo *PAI) {
9445 auto &DL = DAG.getDataLayout();
9446 FunctionType *FTy = CB.getFunctionType();
9447 Type *RetTy = CB.getType();
9448
9450 Args.reserve(CB.arg_size());
9451
9452 const Value *SwiftErrorVal = nullptr;
9453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9454
9455 if (isTailCall)
9456 isTailCall = canTailCall(CB);
9457
9458 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9459 const Value *V = *I;
9460
9461 // Skip empty types
9462 if (V->getType()->isEmptyTy())
9463 continue;
9464
9465 SDValue ArgNode = getValue(V);
9466 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9467 Entry.setAttributes(&CB, I - CB.arg_begin());
9468
9469 // Use swifterror virtual register as input to the call.
9470 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9471 SwiftErrorVal = V;
9472 // We find the virtual register for the actual swifterror argument.
9473 // Instead of using the Value, we use the virtual register instead.
9474 Entry.Node =
9475 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9476 EVT(TLI.getPointerTy(DL)));
9477 }
9478
9479 Args.push_back(Entry);
9480
9481 // If we have an explicit sret argument that is an Instruction, (i.e., it
9482 // might point to function-local memory), we can't meaningfully tail-call.
9483 if (Entry.IsSRet && isa<Instruction>(V))
9484 isTailCall = false;
9485 }
9486
9487 // If call site has a cfguardtarget operand bundle, create and add an
9488 // additional ArgListEntry.
9489 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9490 Value *V = Bundle->Inputs[0];
9492 Entry.IsCFGuardTarget = true;
9493 Args.push_back(Entry);
9494 }
9495
9496 // Disable tail calls if there is an swifterror argument. Targets have not
9497 // been updated to support tail calls.
9498 if (TLI.supportSwiftError() && SwiftErrorVal)
9499 isTailCall = false;
9500
9501 ConstantInt *CFIType = nullptr;
9502 if (CB.isIndirectCall()) {
9503 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9504 if (!TLI.supportKCFIBundles())
9506 "Target doesn't support calls with kcfi operand bundles.");
9507 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9508 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9509 }
9510 }
9511
9512 SDValue ConvControlToken;
9513 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9514 auto *Token = Bundle->Inputs[0].get();
9515 ConvControlToken = getValue(Token);
9516 }
9517
9518 GlobalValue *DeactivationSymbol = nullptr;
9520 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9521 }
9522
9525 .setChain(getRoot())
9526 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9527 .setTailCall(isTailCall)
9531 .setCFIType(CFIType)
9532 .setConvergenceControlToken(ConvControlToken)
9533 .setDeactivationSymbol(DeactivationSymbol);
9534
9535 // Set the pointer authentication info if we have it.
9536 if (PAI) {
9537 if (!TLI.supportPtrAuthBundles())
9539 "This target doesn't support calls with ptrauth operand bundles.");
9540 CLI.setPtrAuth(*PAI);
9541 }
9542
9543 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9544
9545 if (Result.first.getNode()) {
9546 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9547 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, CB, Result.first);
9548 setValue(&CB, Result.first);
9549 }
9550
9551 // The last element of CLI.InVals has the SDValue for swifterror return.
9552 // Here we copy it to a virtual register and update SwiftErrorMap for
9553 // book-keeping.
9554 if (SwiftErrorVal && TLI.supportSwiftError()) {
9555 // Get the last element of InVals.
9556 SDValue Src = CLI.InVals.back();
9557 Register VReg =
9558 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9559 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9560 DAG.setRoot(CopyNode);
9561 }
9562}
9563
9564static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9565 SelectionDAGBuilder &Builder) {
9566 // Check to see if this load can be trivially constant folded, e.g. if the
9567 // input is from a string literal.
9568 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9569 // Cast pointer to the type we really want to load.
9570 Type *LoadTy =
9571 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9572 if (LoadVT.isVector())
9573 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9574 if (const Constant *LoadCst =
9575 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9576 LoadTy, Builder.DAG.getDataLayout()))
9577 return Builder.getValue(LoadCst);
9578 }
9579
9580 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9581 // still constant memory, the input chain can be the entry node.
9582 SDValue Root;
9583 bool ConstantMemory = false;
9584
9585 // Do not serialize (non-volatile) loads of constant memory with anything.
9586 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9587 Root = Builder.DAG.getEntryNode();
9588 ConstantMemory = true;
9589 } else {
9590 // Do not serialize non-volatile loads against each other.
9591 Root = Builder.DAG.getRoot();
9592 }
9593
9594 SDValue Ptr = Builder.getValue(PtrVal);
9595 SDValue LoadVal =
9596 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9597 MachinePointerInfo(PtrVal), Align(1));
9598
9599 if (!ConstantMemory)
9600 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9601 return LoadVal;
9602}
9603
9604/// Record the value for an instruction that produces an integer result,
9605/// converting the type where necessary.
9606void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9607 SDValue Value,
9608 bool IsSigned) {
9609 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9610 I.getType(), true);
9611 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9612 setValue(&I, Value);
9613}
9614
9615/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9616/// true and lower it. Otherwise return false, and it will be lowered like a
9617/// normal call.
9618/// The caller already checked that \p I calls the appropriate LibFunc with a
9619/// correct prototype.
9620bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9621 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9622 const Value *Size = I.getArgOperand(2);
9623 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9624 if (CSize && CSize->getZExtValue() == 0) {
9625 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9626 I.getType(), true);
9627 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9628 return true;
9629 }
9630
9631 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9632 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9633 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9634 getValue(Size), &I);
9635 if (Res.first.getNode()) {
9636 processIntegerCallValue(I, Res.first, true);
9637 PendingLoads.push_back(Res.second);
9638 return true;
9639 }
9640
9641 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9642 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9643 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9644 return false;
9645
9646 // If the target has a fast compare for the given size, it will return a
9647 // preferred load type for that size. Require that the load VT is legal and
9648 // that the target supports unaligned loads of that type. Otherwise, return
9649 // INVALID.
9650 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9651 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9652 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9653 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9654 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9655 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9656 // TODO: Check alignment of src and dest ptrs.
9657 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9658 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9659 if (!TLI.isTypeLegal(LVT) ||
9660 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9663 }
9664
9665 return LVT;
9666 };
9667
9668 // This turns into unaligned loads. We only do this if the target natively
9669 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9670 // we'll only produce a small number of byte loads.
9671 MVT LoadVT;
9672 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9673 switch (NumBitsToCompare) {
9674 default:
9675 return false;
9676 case 16:
9677 LoadVT = MVT::i16;
9678 break;
9679 case 32:
9680 LoadVT = MVT::i32;
9681 break;
9682 case 64:
9683 case 128:
9684 case 256:
9685 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9686 break;
9687 }
9688
9689 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9690 return false;
9691
9692 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9693 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9694
9695 // Bitcast to a wide integer type if the loads are vectors.
9696 if (LoadVT.isVector()) {
9697 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9698 LoadL = DAG.getBitcast(CmpVT, LoadL);
9699 LoadR = DAG.getBitcast(CmpVT, LoadR);
9700 }
9701
9702 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9703 processIntegerCallValue(I, Cmp, false);
9704 return true;
9705}
9706
9707/// See if we can lower a memchr call into an optimized form. If so, return
9708/// true and lower it. Otherwise return false, and it will be lowered like a
9709/// normal call.
9710/// The caller already checked that \p I calls the appropriate LibFunc with a
9711/// correct prototype.
9712bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9713 const Value *Src = I.getArgOperand(0);
9714 const Value *Char = I.getArgOperand(1);
9715 const Value *Length = I.getArgOperand(2);
9716
9717 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9718 std::pair<SDValue, SDValue> Res =
9719 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9720 getValue(Src), getValue(Char), getValue(Length),
9721 MachinePointerInfo(Src));
9722 if (Res.first.getNode()) {
9723 setValue(&I, Res.first);
9724 PendingLoads.push_back(Res.second);
9725 return true;
9726 }
9727
9728 return false;
9729}
9730
9731/// See if we can lower a memccpy call into an optimized form. If so, return
9732/// true and lower it, otherwise return false and it will be lowered like a
9733/// normal call.
9734/// The caller already checked that \p I calls the appropriate LibFunc with a
9735/// correct prototype.
9736bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9737 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9738 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9739 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9740 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9741 getValue(I.getArgOperand(3)), &I);
9742
9743 if (Res.first) {
9744 processIntegerCallValue(I, Res.first, true);
9745 PendingLoads.push_back(Res.second);
9746 return true;
9747 }
9748 return false;
9749}
9750
9751/// See if we can lower a mempcpy call into an optimized form. If so, return
9752/// true and lower it. Otherwise return false, and it will be lowered like a
9753/// normal call.
9754/// The caller already checked that \p I calls the appropriate LibFunc with a
9755/// correct prototype.
9756bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9757 SDValue Dst = getValue(I.getArgOperand(0));
9758 SDValue Src = getValue(I.getArgOperand(1));
9759 SDValue Size = getValue(I.getArgOperand(2));
9760
9761 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9762 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9763
9764 SDLoc sdl = getCurSDLoc();
9765
9766 // In the mempcpy context we need to pass in a false value for isTailCall
9767 // because the return pointer needs to be adjusted by the size of
9768 // the copied memory.
9769 SDValue Root = getMemoryRoot();
9770 SDValue MC = DAG.getMemcpy(
9771 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9772 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9773 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9774 assert(MC.getNode() != nullptr &&
9775 "** memcpy should not be lowered as TailCall in mempcpy context **");
9776 DAG.setRoot(MC);
9777
9778 // Check if Size needs to be truncated or extended.
9779 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9780
9781 // Adjust return pointer to point just past the last dst byte.
9782 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9783 setValue(&I, DstPlusSize);
9784 return true;
9785}
9786
9787/// See if we can lower a strcpy call into an optimized form. If so, return
9788/// true and lower it, otherwise return false and it will be lowered like a
9789/// normal call.
9790/// The caller already checked that \p I calls the appropriate LibFunc with a
9791/// correct prototype.
9792bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9793 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9794
9795 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9796 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9797 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9798 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9799 if (Res.first.getNode()) {
9800 setValue(&I, Res.first);
9801 DAG.setRoot(Res.second);
9802 return true;
9803 }
9804
9805 return false;
9806}
9807
9808/// See if we can lower a strcmp call into an optimized form. If so, return
9809/// true and lower it, otherwise return false and it will be lowered like a
9810/// normal call.
9811/// The caller already checked that \p I calls the appropriate LibFunc with a
9812/// correct prototype.
9813bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9814 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9815
9816 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9817 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9818 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9819 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9820 if (Res.first.getNode()) {
9821 processIntegerCallValue(I, Res.first, true);
9822 PendingLoads.push_back(Res.second);
9823 return true;
9824 }
9825
9826 return false;
9827}
9828
9829/// See if we can lower a strlen call into an optimized form. If so, return
9830/// true and lower it, otherwise return false and it will be lowered like a
9831/// normal call.
9832/// The caller already checked that \p I calls the appropriate LibFunc with a
9833/// correct prototype.
9834bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9835 const Value *Arg0 = I.getArgOperand(0);
9836
9837 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9838 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9839 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9840 if (Res.first.getNode()) {
9841 processIntegerCallValue(I, Res.first, false);
9842 PendingLoads.push_back(Res.second);
9843 return true;
9844 }
9845
9846 return false;
9847}
9848
9849/// See if we can lower a strnlen call into an optimized form. If so, return
9850/// true and lower it, otherwise return false and it will be lowered like a
9851/// normal call.
9852/// The caller already checked that \p I calls the appropriate LibFunc with a
9853/// correct prototype.
9854bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9855 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9856
9857 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9858 std::pair<SDValue, SDValue> Res =
9859 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9860 getValue(Arg0), getValue(Arg1),
9861 MachinePointerInfo(Arg0));
9862 if (Res.first.getNode()) {
9863 processIntegerCallValue(I, Res.first, false);
9864 PendingLoads.push_back(Res.second);
9865 return true;
9866 }
9867
9868 return false;
9869}
9870
9871/// See if we can lower a Strstr call into an optimized form. If so, return
9872/// true and lower it, otherwise return false and it will be lowered like a
9873/// normal call.
9874/// The caller already checked that \p I calls the appropriate LibFunc with a
9875/// correct prototype.
9876bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9877 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9878 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9879 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9880 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9881 if (Res.first) {
9882 processIntegerCallValue(I, Res.first, false);
9883 PendingLoads.push_back(Res.second);
9884 return true;
9885 }
9886 return false;
9887}
9888
9889/// See if we can lower a unary floating-point operation into an SDNode with
9890/// the specified Opcode. If so, return true and lower it, otherwise return
9891/// false and it will be lowered like a normal call.
9892/// The caller already checked that \p I calls the appropriate LibFunc with a
9893/// correct prototype.
9894bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9895 unsigned Opcode) {
9896 // We already checked this call's prototype; verify it doesn't modify errno.
9897 // Do not perform optimizations for call sites that require strict
9898 // floating-point semantics.
9899 if (!I.onlyReadsMemory() || I.isStrictFP())
9900 return false;
9901
9902 SDNodeFlags Flags;
9903 Flags.copyFMF(cast<FPMathOperator>(I));
9904
9905 SDValue Tmp = getValue(I.getArgOperand(0));
9906 setValue(&I,
9907 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9908 return true;
9909}
9910
9911/// See if we can lower a binary floating-point operation into an SDNode with
9912/// the specified Opcode. If so, return true and lower it. Otherwise return
9913/// false, and it will be lowered like a normal call.
9914/// The caller already checked that \p I calls the appropriate LibFunc with a
9915/// correct prototype.
9916bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9917 unsigned Opcode) {
9918 // We already checked this call's prototype; verify it doesn't modify errno.
9919 // Do not perform optimizations for call sites that require strict
9920 // floating-point semantics.
9921 if (!I.onlyReadsMemory() || I.isStrictFP())
9922 return false;
9923
9924 SDNodeFlags Flags;
9925 Flags.copyFMF(cast<FPMathOperator>(I));
9926
9927 SDValue Tmp0 = getValue(I.getArgOperand(0));
9928 SDValue Tmp1 = getValue(I.getArgOperand(1));
9929 EVT VT = Tmp0.getValueType();
9930 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9931 return true;
9932}
9933
9934void SelectionDAGBuilder::visitCall(const CallInst &I) {
9935 // Handle inline assembly differently.
9936 if (I.isInlineAsm()) {
9937 visitInlineAsm(I);
9938 return;
9939 }
9940
9942
9943 if (Function *F = I.getCalledFunction()) {
9944 if (F->isDeclaration()) {
9945 // Is this an LLVM intrinsic?
9946 if (unsigned IID = F->getIntrinsicID()) {
9947 visitIntrinsicCall(I, IID);
9948 return;
9949 }
9950 }
9951
9952 // Check for well-known libc/libm calls. If the function is internal, it
9953 // can't be a library call. Don't do the check if marked as nobuiltin for
9954 // some reason.
9955 // This code should not handle libcalls that are already canonicalized to
9956 // intrinsics by the middle-end.
9957 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9958 ? LibInfo->getLibFunc(*F)
9959 : NotLibFunc;
9960 if (LibInfo->hasOptimizedCodeGen(Func)) {
9961 switch (Func) {
9962 default: break;
9963 case LibFunc_bcmp:
9964 if (visitMemCmpBCmpCall(I))
9965 return;
9966 break;
9967 case LibFunc_sin:
9968 case LibFunc_sinf:
9969 case LibFunc_sinl:
9970 if (visitUnaryFloatCall(I, ISD::FSIN))
9971 return;
9972 break;
9973 case LibFunc_cos:
9974 case LibFunc_cosf:
9975 case LibFunc_cosl:
9976 if (visitUnaryFloatCall(I, ISD::FCOS))
9977 return;
9978 break;
9979 case LibFunc_tan:
9980 case LibFunc_tanf:
9981 case LibFunc_tanl:
9982 if (visitUnaryFloatCall(I, ISD::FTAN))
9983 return;
9984 break;
9985 case LibFunc_asin:
9986 case LibFunc_asinf:
9987 case LibFunc_asinl:
9988 if (visitUnaryFloatCall(I, ISD::FASIN))
9989 return;
9990 break;
9991 case LibFunc_acos:
9992 case LibFunc_acosf:
9993 case LibFunc_acosl:
9994 if (visitUnaryFloatCall(I, ISD::FACOS))
9995 return;
9996 break;
9997 case LibFunc_atan:
9998 case LibFunc_atanf:
9999 case LibFunc_atanl:
10000 if (visitUnaryFloatCall(I, ISD::FATAN))
10001 return;
10002 break;
10003 case LibFunc_atan2:
10004 case LibFunc_atan2f:
10005 case LibFunc_atan2l:
10006 if (visitBinaryFloatCall(I, ISD::FATAN2))
10007 return;
10008 break;
10009 case LibFunc_sinh:
10010 case LibFunc_sinhf:
10011 case LibFunc_sinhl:
10012 if (visitUnaryFloatCall(I, ISD::FSINH))
10013 return;
10014 break;
10015 case LibFunc_cosh:
10016 case LibFunc_coshf:
10017 case LibFunc_coshl:
10018 if (visitUnaryFloatCall(I, ISD::FCOSH))
10019 return;
10020 break;
10021 case LibFunc_tanh:
10022 case LibFunc_tanhf:
10023 case LibFunc_tanhl:
10024 if (visitUnaryFloatCall(I, ISD::FTANH))
10025 return;
10026 break;
10027 case LibFunc_sqrt:
10028 case LibFunc_sqrtf:
10029 case LibFunc_sqrtl:
10030 case LibFunc_sqrt_finite:
10031 case LibFunc_sqrtf_finite:
10032 case LibFunc_sqrtl_finite:
10033 if (visitUnaryFloatCall(I, ISD::FSQRT))
10034 return;
10035 break;
10036 case LibFunc_log2:
10037 case LibFunc_log2f:
10038 case LibFunc_log2l:
10039 if (visitUnaryFloatCall(I, ISD::FLOG2))
10040 return;
10041 break;
10042 case LibFunc_exp2:
10043 case LibFunc_exp2f:
10044 case LibFunc_exp2l:
10045 if (visitUnaryFloatCall(I, ISD::FEXP2))
10046 return;
10047 break;
10048 case LibFunc_exp10:
10049 case LibFunc_exp10f:
10050 case LibFunc_exp10l:
10051 if (visitUnaryFloatCall(I, ISD::FEXP10))
10052 return;
10053 break;
10054 case LibFunc_strstr:
10055 if (visitStrstrCall(I))
10056 return;
10057 break;
10058 case LibFunc_memcmp:
10059 if (visitMemCmpBCmpCall(I))
10060 return;
10061 break;
10062 case LibFunc_memccpy:
10063 if (visitMemCCpyCall(I))
10064 return;
10065 break;
10066 case LibFunc_mempcpy:
10067 if (visitMemPCpyCall(I))
10068 return;
10069 break;
10070 case LibFunc_memchr:
10071 if (visitMemChrCall(I))
10072 return;
10073 break;
10074 case LibFunc_strcpy:
10075 if (visitStrCpyCall(I, false))
10076 return;
10077 break;
10078 case LibFunc_stpcpy:
10079 if (visitStrCpyCall(I, true))
10080 return;
10081 break;
10082 case LibFunc_strcmp:
10083 if (visitStrCmpCall(I))
10084 return;
10085 break;
10086 case LibFunc_strlen:
10087 if (visitStrLenCall(I))
10088 return;
10089 break;
10090 case LibFunc_strnlen:
10091 if (visitStrNLenCall(I))
10092 return;
10093 break;
10094 }
10095 }
10096 }
10097
10098 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
10099 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
10100 return;
10101 }
10102
10103 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
10104 // have to do anything here to lower funclet bundles.
10105 // CFGuardTarget bundles are lowered in LowerCallTo.
10107 I, "calls",
10112
10113 SDValue Callee = getValue(I.getCalledOperand());
10114
10115 if (I.hasDeoptState())
10116 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
10117 else
10118 // Check if we can potentially perform a tail call. More detailed checking
10119 // is be done within LowerCallTo, after more information about the call is
10120 // known.
10121 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
10122}
10123
10125 const CallBase &CB, const BasicBlock *EHPadBB) {
10126 auto PAB = CB.getOperandBundle("ptrauth");
10127 const Value *CalleeV = CB.getCalledOperand();
10128
10129 // Gather the call ptrauth data from the operand bundle:
10130 // [ i32 <key>, i64 <discriminator> ]
10131 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
10132 const Value *Discriminator = PAB->Inputs[1];
10133
10134 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
10135 assert(Discriminator->getType()->isIntegerTy(64) &&
10136 "Invalid ptrauth discriminator");
10137
10138 // Look through ptrauth constants to find the raw callee.
10139 // Do a direct unauthenticated call if we found it and everything matches.
10140 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
10141 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
10142 DAG.getDataLayout()))
10143 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
10144 CB.isMustTailCall(), EHPadBB);
10145
10146 // Functions should never be ptrauth-called directly.
10147 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
10148
10149 // Otherwise, do an authenticated indirect call.
10150 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
10151 getValue(Discriminator)};
10152
10153 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
10154 EHPadBB, &PAI);
10155}
10156
10157namespace {
10158
10159/// AsmOperandInfo - This contains information for each constraint that we are
10160/// lowering.
10161class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
10162public:
10163 /// CallOperand - If this is the result output operand or a clobber
10164 /// this is null, otherwise it is the incoming operand to the CallInst.
10165 /// This gets modified as the asm is processed.
10166 SDValue CallOperand;
10167
10168 /// AssignedRegs - If this is a register or register class operand, this
10169 /// contains the set of register corresponding to the operand.
10170 RegsForValue AssignedRegs;
10171
10172 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
10173 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
10174 }
10175
10176 /// Whether or not this operand accesses memory
10177 bool hasMemory(const TargetLowering &TLI) const {
10178 // Indirect operand accesses access memory.
10179 if (isIndirect)
10180 return true;
10181
10182 for (const auto &Code : Codes)
10183 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
10184 return true;
10185
10186 return false;
10187 }
10188};
10189
10190
10191} // end anonymous namespace
10192
10193/// Make sure that the output operand \p OpInfo and its corresponding input
10194/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10195/// out).
10196static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10197 SDISelAsmOperandInfo &MatchingOpInfo,
10198 SelectionDAG &DAG) {
10199 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10200 return;
10201
10203 const auto &TLI = DAG.getTargetLoweringInfo();
10204
10205 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10206 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
10207 OpInfo.ConstraintVT);
10208 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10209 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
10210 MatchingOpInfo.ConstraintVT);
10211 const bool OutOpIsIntOrFP =
10212 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10213 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10214 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10215 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10216 // FIXME: error out in a more elegant fashion
10217 report_fatal_error("Unsupported asm: input constraint"
10218 " with a matching output constraint of"
10219 " incompatible type!");
10220 }
10221 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10222}
10223
10224/// Get a direct memory input to behave well as an indirect operand.
10225/// This may introduce stores, hence the need for a \p Chain.
10226/// \return The (possibly updated) chain.
10227static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10228 SDISelAsmOperandInfo &OpInfo,
10229 SelectionDAG &DAG) {
10231
10232 // If we don't have an indirect input, put it in the constpool if we can,
10233 // otherwise spill it to a stack slot.
10234 // TODO: This isn't quite right. We need to handle these according to
10235 // the addressing mode that the constraint wants. Also, this may take
10236 // an additional register for the computation and we don't want that
10237 // either.
10238
10239 // If the operand is a float, integer, or vector constant, spill to a
10240 // constant pool entry to get its address.
10241 const Value *OpVal = OpInfo.CallOperandVal;
10242 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10244 OpInfo.CallOperand = DAG.getConstantPool(
10245 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10246 return Chain;
10247 }
10248
10249 // Otherwise, create a stack slot and emit a store to it before the asm.
10250 Type *Ty = OpVal->getType();
10251 auto &DL = DAG.getDataLayout();
10252 TypeSize TySize = DL.getTypeAllocSize(Ty);
10255 int StackID = 0;
10256 if (TySize.isScalable())
10257 StackID = TFI->getStackIDForScalableVectors();
10258 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10259 DL.getPrefTypeAlign(Ty), false,
10260 nullptr, StackID);
10261 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10262 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10264 TLI.getMemValueType(DL, Ty));
10265 OpInfo.CallOperand = StackSlot;
10266
10267 return Chain;
10268}
10269
10270/// GetRegistersForValue - Assign registers (virtual or physical) for the
10271/// specified operand. We prefer to assign virtual registers, to allow the
10272/// register allocator to handle the assignment process. However, if the asm
10273/// uses features that we can't model on machineinstrs, we have SDISel do the
10274/// allocation. This produces generally horrible, but correct, code.
10275///
10276/// OpInfo describes the operand
10277/// RefOpInfo describes the matching operand if any, the operand otherwise
10278static std::optional<unsigned>
10280 SDISelAsmOperandInfo &OpInfo,
10281 SDISelAsmOperandInfo &RefOpInfo) {
10282 LLVMContext &Context = *DAG.getContext();
10284
10288
10289 // No work to do for memory/address operands.
10290 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10291 OpInfo.ConstraintType == TargetLowering::C_Address)
10292 return std::nullopt;
10293
10294 // If this is a constraint for a single physreg, or a constraint for a
10295 // register class, find it.
10296 unsigned AssignedReg;
10297 const TargetRegisterClass *RC;
10298 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10299 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10300 // RC is unset only on failure. Return immediately.
10301 if (!RC)
10302 return std::nullopt;
10303
10304 // Get the actual register value type. This is important, because the user
10305 // may have asked for (e.g.) the AX register in i32 type. We need to
10306 // remember that AX is actually i16 to get the right extension.
10307 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10308
10309 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10310 // If this is an FP operand in an integer register (or visa versa), or more
10311 // generally if the operand value disagrees with the register class we plan
10312 // to stick it in, fix the operand type.
10313 //
10314 // If this is an input value, the bitcast to the new type is done now.
10315 // Bitcast for output value is done at the end of visitInlineAsm().
10316 if ((OpInfo.Type == InlineAsm::isOutput ||
10317 OpInfo.Type == InlineAsm::isInput) &&
10318 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10319 // Try to convert to the first EVT that the reg class contains. If the
10320 // types are identical size, use a bitcast to convert (e.g. two differing
10321 // vector types). Note: output bitcast is done at the end of
10322 // visitInlineAsm().
10323 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10324 // Exclude indirect inputs while they are unsupported because the code
10325 // to perform the load is missing and thus OpInfo.CallOperand still
10326 // refers to the input address rather than the pointed-to value.
10327 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10328 OpInfo.CallOperand =
10329 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10330 OpInfo.ConstraintVT = RegVT;
10331 // If the operand is an FP value and we want it in integer registers,
10332 // use the corresponding integer type. This turns an f64 value into
10333 // i64, which can be passed with two i32 values on a 32-bit machine.
10334 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10335 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10336 // No integer type of that size to bitcast to (e.g. f80).
10337 if (!VT.isValid())
10338 return std::nullopt;
10339 if (OpInfo.Type == InlineAsm::isInput)
10340 OpInfo.CallOperand =
10341 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10342 OpInfo.ConstraintVT = VT;
10343 }
10344 }
10345 }
10346
10347 // No need to allocate a matching input constraint since the constraint it's
10348 // matching to has already been allocated.
10349 if (OpInfo.isMatchingInputConstraint())
10350 return std::nullopt;
10351
10352 EVT ValueVT = OpInfo.ConstraintVT;
10353 if (OpInfo.ConstraintVT == MVT::Other)
10354 ValueVT = RegVT;
10355
10356 // Initialize NumRegs.
10357 unsigned NumRegs = 1;
10358 if (OpInfo.ConstraintVT != MVT::Other)
10359 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10360
10361 // If this is a constraint for a specific physical register, like {r17},
10362 // assign it now.
10363
10364 // If this associated to a specific register, initialize iterator to correct
10365 // place. If virtual, make sure we have enough registers
10366
10367 // Initialize iterator if necessary
10370
10371 // Do not check for single registers.
10372 if (AssignedReg) {
10373 I = std::find(I, RC->end(), AssignedReg);
10374 if (I == RC->end()) {
10375 // RC does not contain the selected register, which indicates a
10376 // mismatch between the register and the required type/bitwidth.
10377 return {AssignedReg};
10378 }
10379 }
10380
10381 for (; NumRegs; --NumRegs, ++I) {
10382 assert(I != RC->end() && "Ran out of registers to allocate!");
10383 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10384 Regs.push_back(R);
10385 }
10386
10387 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10388 return std::nullopt;
10389}
10390
10391static unsigned
10393 const std::vector<SDValue> &AsmNodeOperands) {
10394 // Scan until we find the definition we already emitted of this operand.
10395 unsigned CurOp = InlineAsm::Op_FirstOperand;
10396 for (; OperandNo; --OperandNo) {
10397 // Advance to the next operand.
10398 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10399 const InlineAsm::Flag F(OpFlag);
10400 assert(
10401 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10402 "Skipped past definitions?");
10403 CurOp += F.getNumOperandRegisters() + 1;
10404 }
10405 return CurOp;
10406}
10407
10408namespace {
10409
10410class ExtraFlags {
10411 unsigned Flags = 0;
10412
10413public:
10414 explicit ExtraFlags(const CallBase &Call) {
10415 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10416 if (IA->hasSideEffects())
10418 if (IA->isAlignStack())
10420 if (IA->canThrow())
10422 if (Call.isConvergent())
10424 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10425 }
10426
10427 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10428 // Ideally, we would only check against memory constraints. However, the
10429 // meaning of an Other constraint can be target-specific and we can't easily
10430 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10431 // for Other constraints as well.
10434 if (OpInfo.Type == InlineAsm::isInput)
10436 else if (OpInfo.Type == InlineAsm::isOutput)
10438 else if (OpInfo.Type == InlineAsm::isClobber)
10440 }
10441 }
10442
10443 unsigned get() const { return Flags; }
10444};
10445
10446} // end anonymous namespace
10447
10448static bool isFunction(SDValue Op) {
10449 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10450 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10451 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10452
10453 // In normal "call dllimport func" instruction (non-inlineasm) it force
10454 // indirect access by specifing call opcode. And usually specially print
10455 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10456 // not do in this way now. (In fact, this is similar with "Data Access"
10457 // action). So here we ignore dllimport function.
10458 if (Fn && !Fn->hasDLLImportStorageClass())
10459 return true;
10460 }
10461 }
10462 return false;
10463}
10464
10465namespace {
10466
10467struct ConstraintDecisionInfo {
10468 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10469 std::vector<SDValue> AsmNodeOperands;
10470 SDValue Glue, Chain;
10471 bool HasSideEffect = false;
10472 MCSymbol *BeginLabel = nullptr;
10473
10474 SmallVector<char> Buffer;
10475 raw_svector_ostream ErrorMsg;
10476
10477 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10478};
10479
10480} // end anonymous namespace
10481
10482/// Construct operand info objects.
10483static bool
10484constructOperandInfo(ConstraintDecisionInfo &Info,
10485 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10486 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10487 ExtraFlags &ExtraInfo) {
10488 for (auto &T : TargetConstraints) {
10489 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10490 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10491
10492 if (OpInfo.CallOperandVal)
10493 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10494
10495 if (!Info.HasSideEffect)
10496 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10497
10498 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10499 // FIXME: Could we compute this on OpInfo rather than T?
10500
10501 // Compute the constraint code and ConstraintType to use.
10502 TLI.ComputeConstraintToUse(T, SDValue());
10503
10504 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10505 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10506 // We've delayed emitting a diagnostic like the "n" constraint because
10507 // inlining could cause an integer showing up.
10508 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10509 << "' expects an integer constant expression";
10510 return true;
10511 }
10512
10513 ExtraInfo.update(T);
10514 }
10515
10516 return false;
10517}
10518
10519/// Compute which constraint option to use for each operand.
10520static void
10521computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10522 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10523 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10524 const TargetMachine &TM, SelectionDAG &DAG) {
10525 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10527 IA->collectAsmStrs(AsmStrs);
10528
10529 int OpNo = -1;
10530 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10531 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10532 OpNo++;
10533
10534 // If this is an output operand with a matching input operand, look up the
10535 // matching input. If their types mismatch, e.g. one is an integer, the
10536 // other is floating point, or their sizes are different, flag it as an
10537 // error.
10538 if (OpInfo.hasMatchingInput()) {
10539 SDISelAsmOperandInfo &Input =
10540 Info.ConstraintOperands[OpInfo.MatchingInput];
10541 patchMatchingInput(OpInfo, Input, DAG);
10542 }
10543
10544 // Compute the constraint code and ConstraintType to use.
10545 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10546
10547 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10548 OpInfo.Type == InlineAsm::isClobber) ||
10549 OpInfo.ConstraintType == TargetLowering::C_Address)
10550 continue;
10551
10552 // In Linux PIC model, there are 4 cases about value/label addressing:
10553 //
10554 // 1: Function call or Label jmp inside the module.
10555 // 2: Data access (such as global variable, static variable) inside module.
10556 // 3: Function call or Label jmp outside the module.
10557 // 4: Data access (such as global variable) outside the module.
10558 //
10559 // Due to current llvm inline asm architecture designed to not "recognize"
10560 // the asm code, there are quite troubles for us to treat mem addressing
10561 // differently for same value/adress used in different instructions.
10562 // For example, in pic model, call a func may in plt way or direclty
10563 // pc-related, but lea/mov a function adress may use got.
10564 //
10565 // Here we try to "recognize" function call for the case 1 and case 3 in
10566 // inline asm. And try to adjust the constraint for them.
10567 //
10568 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10569 // label, so here we don't handle jmp function label now, but we need to
10570 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10571 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10572 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10574 OpInfo.isIndirect = false;
10575 OpInfo.ConstraintType = TargetLowering::C_Address;
10576 }
10577
10578 // If this is a memory input, and if the operand is not indirect, do what we
10579 // need to provide an address for the memory input.
10580 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10581 !OpInfo.isIndirect) {
10582 assert((OpInfo.isMultipleAlternative ||
10583 (OpInfo.Type == InlineAsm::isInput)) &&
10584 "Can only indirectify direct input operands!");
10585
10586 // Memory operands really want the address of the value.
10587 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10588 OpInfo, DAG);
10589
10590 // There is no longer a Value* corresponding to this operand.
10591 OpInfo.CallOperandVal = nullptr;
10592
10593 // It is now an indirect operand.
10594 OpInfo.isIndirect = true;
10595 }
10596 }
10597}
10598
10599/// Prepare DAG-level operands. As part of this, assign virtual and physical
10600/// registers for inputs and output.
10601static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10602 const CallBase &Call,
10603 SelectionDAGBuilder &Builder,
10604 const TargetLowering &TLI,
10605 SelectionDAG &DAG) {
10606 SDLoc DL = Builder.getCurSDLoc();
10607 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10608 // Assign Registers.
10609 SDISelAsmOperandInfo &RefOpInfo =
10610 OpInfo.isMatchingInputConstraint()
10611 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10612 : OpInfo;
10613 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10614 if (RegError) {
10615 const MachineFunction &MF = DAG.getMachineFunction();
10617 const char *RegName = TRI.getName(*RegError);
10618 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10619 << OpInfo.ConstraintCode
10620 << "' does not match required type";
10621 return true;
10622 }
10623
10624 auto DetectWriteToReservedRegister = [&]() {
10625 const MachineFunction &MF = DAG.getMachineFunction();
10627
10628 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10629 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10630 Info.ErrorMsg << "write to reserved register '"
10631 << TRI.getRegAsmName(Reg) << "'";
10632 return true;
10633 }
10634 }
10635
10636 return false;
10637 };
10638 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10639 (OpInfo.Type == InlineAsm::isInput &&
10640 !OpInfo.isMatchingInputConstraint())) &&
10641 "Only address as input operand is allowed.");
10642
10643 switch (OpInfo.Type) {
10645 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10646 const InlineAsm::ConstraintCode ConstraintID =
10647 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10649 "Failed to convert memory constraint code to constraint id.");
10650
10651 // Add information to the INLINEASM node to know about this output.
10653 OpFlags.setMemConstraint(ConstraintID);
10654 Info.AsmNodeOperands.push_back(
10655 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10656 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10657 } else {
10658 // Otherwise, this outputs to a register (directly for C_Register /
10659 // C_RegisterClass, and a target-defined fashion for
10660 // C_Immediate/C_Other). Find a register that we can use.
10661 if (OpInfo.AssignedRegs.Regs.empty()) {
10662 Info.ErrorMsg << "could not allocate output register for "
10663 << "constraint '" << OpInfo.ConstraintCode << "'";
10664 return true;
10665 }
10666
10667 if (DetectWriteToReservedRegister())
10668 return true;
10669
10670 // Add information to the INLINEASM node to know that this register is
10671 // set.
10672 OpInfo.AssignedRegs.AddInlineAsmOperands(
10673 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10675 false, 0, DL, DAG, Info.AsmNodeOperands);
10676 }
10677 break;
10678
10679 case InlineAsm::isInput:
10680 case InlineAsm::isLabel: {
10681 SDValue InOperandVal = OpInfo.CallOperand;
10682
10683 if (OpInfo.isMatchingInputConstraint()) {
10684 // If this is required to match an output register we have already set,
10685 // just use its register.
10686 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10687 Info.AsmNodeOperands);
10688 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10689 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10690 if (OpInfo.isIndirect) {
10691 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10692 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10693 << "tied indirect register inputs";
10694 return true;
10695 }
10696
10701 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10702 Register TiedReg = R->getReg();
10703 MVT RegVT = R->getSimpleValueType(0);
10704 const TargetRegisterClass *RC;
10705 if (TiedReg.isVirtual()) {
10706 RC = MRI.getRegClass(TiedReg);
10707 } else if (RegVT == MVT::Untyped) {
10708 RC = TRI.getMinimalPhysRegClass(TiedReg);
10709 } else {
10710 RC = TLI.getRegClassFor(RegVT);
10711 if (!RC->contains(TiedReg)) {
10712 const TargetRegisterClass *PhysRC =
10713 TRI.getMinimalPhysRegClass(TiedReg);
10714 if (PhysRC->isAllocatable())
10715 RC = PhysRC;
10716 }
10717 }
10718
10719 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10720 Regs.push_back(MRI.createVirtualRegister(RC));
10721
10722 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10723
10724 // Use the produced MatchedRegs object to
10725 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10726 &Info.Glue, &Call);
10728 OpInfo.getMatchedOperand(), DL, DAG,
10729 Info.AsmNodeOperands);
10730 break;
10731 }
10732
10733 assert(Flag.isMemKind() && "Unknown matching constraint!");
10734 assert(Flag.getNumOperandRegisters() == 1 &&
10735 "Unexpected number of operands");
10736
10737 // Add information to the INLINEASM node to know about this input.
10738 // See InlineAsm.h isUseOperandTiedToDef.
10739 Flag.clearMemConstraint();
10740 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10741 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10742 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10743 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10744 break;
10745 }
10746
10747 // Treat indirect 'X' constraint as memory.
10748 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10749 OpInfo.isIndirect)
10750 OpInfo.ConstraintType = TargetLowering::C_Memory;
10751
10752 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10753 OpInfo.ConstraintType == TargetLowering::C_Other) {
10754 std::vector<SDValue> Ops;
10755 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10756 Ops, DAG);
10757 if (Ops.empty()) {
10758 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10759 if (isa<ConstantSDNode>(InOperandVal)) {
10760 Info.ErrorMsg << "value out of range for constraint '"
10761 << OpInfo.ConstraintCode << "'";
10762 return true;
10763 }
10764
10765 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10766 << OpInfo.ConstraintCode << "'";
10767 return true;
10768 }
10769
10770 // Add information to the INLINEASM node to know about this input.
10771 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10772 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10773 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10774 llvm::append_range(Info.AsmNodeOperands, Ops);
10775 break;
10776 }
10777
10778 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10779 assert((OpInfo.isIndirect ||
10780 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10781 "Operand must be indirect to be a mem!");
10782 assert(InOperandVal.getValueType() ==
10783 TLI.getPointerTy(DAG.getDataLayout()) &&
10784 "Memory operands expect pointer values");
10785
10786 const InlineAsm::ConstraintCode ConstraintID =
10787 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10789 "Failed to convert memory constraint code to constraint id.");
10790
10791 // Add information to the INLINEASM node to know about this input.
10793 ResOpType.setMemConstraint(ConstraintID);
10794 Info.AsmNodeOperands.push_back(
10795 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10796 Info.AsmNodeOperands.push_back(InOperandVal);
10797 break;
10798 }
10799
10800 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10801 const InlineAsm::ConstraintCode ConstraintID =
10802 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10804 "Failed to convert memory constraint code to constraint id.");
10805
10807
10808 SDValue AsmOp = InOperandVal;
10809 if (TLI.supportsInlineAsmFuncOperands() && isFunction(InOperandVal)) {
10810 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10811 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10812 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10813 InOperandVal.getValueType(),
10814 GA->getOffset());
10815 }
10816
10817 // Add information to the INLINEASM node to know about this input.
10818 ResOpType.setMemConstraint(ConstraintID);
10819
10820 Info.AsmNodeOperands.push_back(
10821 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10822 Info.AsmNodeOperands.push_back(AsmOp);
10823 break;
10824 }
10825
10826 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10827 OpInfo.ConstraintType != TargetLowering::C_Register) {
10828 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10829 << "'";
10830 return true;
10831 }
10832
10833 // TODO: Support this.
10834 if (OpInfo.isIndirect) {
10835 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10836 << "constraint '" << OpInfo.ConstraintCode << "'";
10837 return true;
10838 }
10839
10840 // Copy the input into the appropriate registers.
10841 if (OpInfo.AssignedRegs.Regs.empty()) {
10842 Info.ErrorMsg << "could not allocate input reg for constraint '"
10843 << OpInfo.ConstraintCode << "'";
10844 return true;
10845 }
10846
10847 if (DetectWriteToReservedRegister())
10848 return true;
10849
10850 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10851 &Info.Glue, &Call);
10852 OpInfo.AssignedRegs.AddInlineAsmOperands(
10853 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10854 break;
10855 }
10856
10858 // Add the clobbered value to the operand list, so that the register
10859 // allocator is aware that the physreg got clobbered.
10860 if (!OpInfo.AssignedRegs.Regs.empty())
10861 OpInfo.AssignedRegs.AddInlineAsmOperands(
10862 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10863 break;
10864 }
10865 }
10866
10867 return false;
10868}
10869
10870/// DetermineConstraints - Find the constraints to use for inline asm operands.
10871static bool
10872determineConstraints(ConstraintDecisionInfo &Info,
10873 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10874 const CallBase &Call, SelectionDAGBuilder &Builder,
10875 const TargetLowering &TLI, const TargetMachine &TM,
10876 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10877 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10878 ExtraFlags ExtraInfo(Call);
10879
10880 // First pass: Construct operand info objects.
10881 Info.HasSideEffect = IA->hasSideEffects();
10882 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10883 return true;
10884
10885 // We won't need to flush pending loads if this asm doesn't touch
10886 // memory and is nonvolatile.
10887 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10888
10889 bool IsCallBr = isa<CallBrInst>(Call);
10890 bool EmitEHLabels = isa<InvokeInst>(Call);
10891 if (IsCallBr || EmitEHLabels)
10892 // If this is a callbr or invoke we need to flush pending exports since
10893 // inlineasm_br and invoke are terminators.
10894 // We need to do this before nodes are glued to the inlineasm_br node.
10895 Info.Chain = Builder.getControlRoot();
10896
10897 if (EmitEHLabels)
10898 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10899
10900 // Second pass: Compute which constraint option to use.
10901 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10902
10903 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10904 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10905 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10906 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10907
10908 // If we have a !srcloc metadata node associated with it, we want to attach
10909 // this to the ultimately generated inline asm machineinstr. To do this, we
10910 // pass in the third operand as this (potentially null) inline asm MDNode.
10911 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10912 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10913
10914 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10915 // bits as operand 3.
10916 Info.AsmNodeOperands.push_back(
10917 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10918 TLI.getPointerTy(DAG.getDataLayout())));
10919
10920 // Third pass: Prepare DAG-level operands
10921 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10922}
10923
10924/// visitInlineAsm - Handle a call to an InlineAsm object.
10925void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10926 const BasicBlock *EHPadBB) {
10927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10929 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
10930
10931 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10932 "InvokeInst must have an EHPadBB");
10933
10934 ConstraintDecisionInfo Info;
10935 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
10936 EHPadBB))
10937 return emitInlineAsmError(Call, Info.ErrorMsg.str());
10938
10939 SDValue Glue = Info.Glue;
10940 SDValue Chain = Info.Chain;
10941
10942 // Finish up input operands. Set the input chain and add the flag last.
10943 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10944 if (Glue.getNode())
10945 Info.AsmNodeOperands.push_back(Glue);
10946
10947 bool IsCallBr = isa<CallBrInst>(Call);
10948 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10949 Chain =
10950 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
10951 Info.AsmNodeOperands);
10952 Glue = Chain.getValue(1);
10953
10954 // Do additional work to generate outputs.
10955
10956 SmallVector<EVT, 1> ResultVTs;
10957 SmallVector<SDValue, 1> ResultValues;
10958 SmallVector<SDValue, 8> OutChains;
10959
10960 llvm::Type *CallResultType = Call.getType();
10961 ArrayRef<Type *> ResultTypes;
10962 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10963 ResultTypes = StructResult->elements();
10964 else if (!CallResultType->isVoidTy())
10965 ResultTypes = ArrayRef(CallResultType);
10966
10967 auto CurResultType = ResultTypes.begin();
10968 auto handleRegAssign = [&](SDValue V) {
10969 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10970 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10971 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10972 ++CurResultType;
10973 // If the type of the inline asm call site return value is different but has
10974 // same size as the type of the asm output bitcast it. One example of this
10975 // is for vectors with different width / number of elements. This can
10976 // happen for register classes that can contain multiple different value
10977 // types. The preg or vreg allocated may not have the same VT as was
10978 // expected.
10979 //
10980 // This can also happen for a return value that disagrees with the register
10981 // class it is put in, eg. a double in a general-purpose register on a
10982 // 32-bit machine.
10983 if (ResultVT != V.getValueType() &&
10984 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10985 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10986 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10987 V.getValueType().isInteger()) {
10988 // If a result value was tied to an input value, the computed result
10989 // may have a wider width than the expected result. Extract the
10990 // relevant portion.
10991 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10992 }
10993 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10994 ResultVTs.push_back(ResultVT);
10995 ResultValues.push_back(V);
10996 };
10997
10998 // Deal with output operands.
10999 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
11000 if (OpInfo.Type == InlineAsm::isOutput) {
11001 SDValue Val;
11002 // Skip trivial output operands.
11003 if (OpInfo.AssignedRegs.Regs.empty())
11004 continue;
11005
11006 switch (OpInfo.ConstraintType) {
11009 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
11010 Chain, &Glue, &Call);
11011 break;
11014 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
11015 OpInfo, DAG);
11016 break;
11018 break; // Already handled.
11020 break; // Silence warning.
11022 assert(false && "Unexpected unknown constraint");
11023 }
11024
11025 // Indirect output manifest as stores. Record output chains.
11026 if (OpInfo.isIndirect) {
11027 const Value *Ptr = OpInfo.CallOperandVal;
11028 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
11029 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
11030 MachinePointerInfo(Ptr));
11031 OutChains.push_back(Store);
11032 } else {
11033 // generate CopyFromRegs to associated registers.
11034 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
11035 if (Val.getOpcode() == ISD::MERGE_VALUES) {
11036 for (const SDValue &V : Val->op_values())
11037 handleRegAssign(V);
11038 } else
11039 handleRegAssign(Val);
11040 }
11041 }
11042 }
11043
11044 // Set results.
11045 if (!ResultValues.empty()) {
11046 assert(CurResultType == ResultTypes.end() &&
11047 "Mismatch in number of ResultTypes");
11048 assert(ResultValues.size() == ResultTypes.size() &&
11049 "Mismatch in number of output operands in asm result");
11050
11052 DAG.getVTList(ResultVTs), ResultValues);
11053 setValue(&Call, V);
11054 }
11055
11056 // Collect store chains.
11057 if (!OutChains.empty())
11058 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
11059
11060 if (const auto *II = dyn_cast<InvokeInst>(&Call))
11061 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
11062
11063 // Only Update Root if inline assembly has a memory effect.
11064 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
11065 IsCallBr || isa<InvokeInst>(Call))
11066 DAG.setRoot(Chain);
11067}
11068
11069void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
11070 const Twine &Message) {
11071 LLVMContext &Ctx = *DAG.getContext();
11072 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
11073
11074 // Make sure we leave the DAG in a valid state
11075 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11076 SmallVector<EVT, 1> ValueVTs;
11077 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
11078
11079 if (ValueVTs.empty())
11080 return;
11081
11083 for (const EVT &VT : ValueVTs)
11084 Ops.push_back(DAG.getUNDEF(VT));
11085
11086 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
11087}
11088
11089void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
11090 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
11091 MVT::Other, getRoot(),
11092 getValue(I.getArgOperand(0)),
11093 DAG.getSrcValue(I.getArgOperand(0))));
11094}
11095
11096void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
11097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11098 const DataLayout &DL = DAG.getDataLayout();
11099 SDValue V = DAG.getVAArg(
11100 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
11101 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
11102 DL.getABITypeAlign(I.getType()).value());
11103 DAG.setRoot(V.getValue(1));
11104
11105 if (I.getType()->isPointerTy())
11106 V = DAG.getPtrExtOrTrunc(
11107 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
11108 setValue(&I, V);
11109}
11110
11111void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
11112 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
11113 MVT::Other, getRoot(),
11114 getValue(I.getArgOperand(0)),
11115 DAG.getSrcValue(I.getArgOperand(0))));
11116}
11117
11118void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
11119 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
11120 MVT::Other, getRoot(),
11121 getValue(I.getArgOperand(0)),
11122 getValue(I.getArgOperand(1)),
11123 DAG.getSrcValue(I.getArgOperand(0)),
11124 DAG.getSrcValue(I.getArgOperand(1))));
11125}
11126
11128 const Instruction &I,
11129 SDValue Op) {
11130 std::optional<ConstantRange> CR = getRange(I);
11131
11132 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
11133 return Op;
11134
11135 APInt Hi = CR->getUnsignedMax();
11136 unsigned Bits = std::max(Hi.getActiveBits(),
11137 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
11138
11139 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11140
11141 SDLoc SL = getCurSDLoc();
11142
11143 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
11144 DAG.getValueType(SmallVT));
11145 unsigned NumVals = Op.getNode()->getNumValues();
11146 if (NumVals == 1)
11147 return ZExt;
11148
11150
11151 Ops.push_back(ZExt);
11152 for (unsigned I = 1; I != NumVals; ++I)
11153 Ops.push_back(Op.getValue(I));
11154
11155 return DAG.getMergeValues(Ops, SL);
11156}
11157
11159 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
11160 FPClassTest Classes = getNoFPClass(I);
11161 if (Classes == fcNone)
11162 return Op;
11163
11164 SDLoc SL = getCurSDLoc();
11165 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
11166
11167 if (Op.getOpcode() != ISD::MERGE_VALUES) {
11168 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
11169 TestConst);
11170 }
11171
11172 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
11173 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
11174 SDValue MergeOp = Op.getOperand(I);
11175 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
11176 MergeOp, TestConst);
11177 }
11178
11179 return DAG.getMergeValues(Ops, SL);
11180}
11181
11182/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
11183/// the call being lowered.
11184///
11185/// This is a helper for lowering intrinsics that follow a target calling
11186/// convention or require stack pointer adjustment. Only a subset of the
11187/// intrinsic's operands need to participate in the calling convention.
11190 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11191 AttributeSet RetAttrs, bool IsPatchPoint) {
11193 Args.reserve(NumArgs);
11194
11195 // Populate the argument list.
11196 // Attributes for args start at offset 1, after the return attribute.
11197 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11198 ArgI != ArgE; ++ArgI) {
11199 const Value *V = Call->getOperand(ArgI);
11200
11201 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11202
11203 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11204 Entry.setAttributes(Call, ArgI);
11205 Args.push_back(Entry);
11206 }
11207
11209 .setChain(getRoot())
11210 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
11211 RetAttrs)
11212 .setDiscardResult(Call->use_empty())
11213 .setIsPatchPoint(IsPatchPoint)
11215 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
11216}
11217
11218/// Add a stack map intrinsic call's live variable operands to a stackmap
11219/// or patchpoint target node's operand list.
11220///
11221/// Constants are converted to TargetConstants purely as an optimization to
11222/// avoid constant materialization and register allocation.
11223///
11224/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11225/// generate addess computation nodes, and so FinalizeISel can convert the
11226/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11227/// address materialization and register allocation, but may also be required
11228/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11229/// alloca in the entry block, then the runtime may assume that the alloca's
11230/// StackMap location can be read immediately after compilation and that the
11231/// location is valid at any point during execution (this is similar to the
11232/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11233/// only available in a register, then the runtime would need to trap when
11234/// execution reaches the StackMap in order to read the alloca's location.
11235static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11237 SelectionDAGBuilder &Builder) {
11238 SelectionDAG &DAG = Builder.DAG;
11239 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11240 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11241
11242 // Things on the stack are pointer-typed, meaning that they are already
11243 // legal and can be emitted directly to target nodes.
11245 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11246 } else {
11247 // Otherwise emit a target independent node to be legalised.
11248 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11249 }
11250 }
11251}
11252
11253/// Lower llvm.experimental.stackmap.
11254void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11255 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11256 // [live variables...])
11257
11258 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11259
11260 SDValue Chain, InGlue, Callee;
11262
11263 SDLoc DL = getCurSDLoc();
11265
11266 // The stackmap intrinsic only records the live variables (the arguments
11267 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11268 // intrinsic, this won't be lowered to a function call. This means we don't
11269 // have to worry about calling conventions and target specific lowering code.
11270 // Instead we perform the call lowering right here.
11271 //
11272 // chain, flag = CALLSEQ_START(chain, 0, 0)
11273 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11274 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11275 //
11276 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11277 InGlue = Chain.getValue(1);
11278
11279 // Add the STACKMAP operands, starting with DAG house-keeping.
11280 Ops.push_back(Chain);
11281 Ops.push_back(InGlue);
11282
11283 // Add the <id>, <numShadowBytes> operands.
11284 //
11285 // These do not require legalisation, and can be emitted directly to target
11286 // constant nodes.
11288 assert(ID.getValueType() == MVT::i64);
11289 SDValue IDConst =
11290 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11291 Ops.push_back(IDConst);
11292
11293 SDValue Shad = getValue(CI.getArgOperand(1));
11294 assert(Shad.getValueType() == MVT::i32);
11295 SDValue ShadConst =
11296 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11297 Ops.push_back(ShadConst);
11298
11299 // Add the live variables.
11300 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11301
11302 // Create the STACKMAP node.
11303 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11304 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11305 InGlue = Chain.getValue(1);
11306
11307 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11308
11309 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11310
11311 // Set the root to the target-lowered call chain.
11312 DAG.setRoot(Chain);
11313
11314 // Inform the Frame Information that we have a stackmap in this function.
11315 FuncInfo.MF->getFrameInfo().setHasStackMap();
11316}
11317
11318/// Lower llvm.experimental.patchpoint directly to its target opcode.
11319void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11320 const BasicBlock *EHPadBB) {
11321 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11322 // i32 <numBytes>,
11323 // i8* <target>,
11324 // i32 <numArgs>,
11325 // [Args...],
11326 // [live variables...])
11327
11329 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11330 bool HasDef = !CB.getType()->isVoidTy();
11331 SDLoc dl = getCurSDLoc();
11333
11334 // Handle immediate and symbolic callees.
11335 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11336 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11337 /*isTarget=*/true);
11338 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11339 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11340 SDLoc(SymbolicCallee),
11341 SymbolicCallee->getValueType(0));
11342
11343 // Get the real number of arguments participating in the call <numArgs>
11345 unsigned NumArgs = NArgVal->getAsZExtVal();
11346
11347 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11348 // Intrinsics include all meta-operands up to but not including CC.
11349 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11350 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11351 "Not enough arguments provided to the patchpoint intrinsic");
11352
11353 // For AnyRegCC the arguments are lowered later on manually.
11354 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11355 Type *ReturnTy =
11356 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11357
11358 TargetLowering::CallLoweringInfo CLI(DAG);
11359 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11360 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11361 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11362
11363 SDNode *CallEnd = Result.second.getNode();
11364 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11365 CallEnd = CallEnd->getOperand(0).getNode();
11366 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11367 CallEnd = CallEnd->getOperand(0).getNode();
11368
11369 /// Get a call instruction from the call sequence chain.
11370 /// Tail calls are not allowed.
11371 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11372 "Expected a callseq node.");
11373 SDNode *Call = CallEnd->getOperand(0).getNode();
11374 bool HasGlue = Call->getGluedNode();
11375
11376 // Replace the target specific call node with the patchable intrinsic.
11378
11379 // Push the chain.
11380 Ops.push_back(*(Call->op_begin()));
11381
11382 // Optionally, push the glue (if any).
11383 if (HasGlue)
11384 Ops.push_back(*(Call->op_end() - 1));
11385
11386 // Push the register mask info.
11387 if (HasGlue)
11388 Ops.push_back(*(Call->op_end() - 2));
11389 else
11390 Ops.push_back(*(Call->op_end() - 1));
11391
11392 // Add the <id> and <numBytes> constants.
11394 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11396 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11397
11398 // Add the callee.
11399 Ops.push_back(Callee);
11400
11401 // Adjust <numArgs> to account for any arguments that have been passed on the
11402 // stack instead.
11403 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11404 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11405 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11406 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11407
11408 // Add the calling convention
11409 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11410
11411 // Add the arguments we omitted previously. The register allocator should
11412 // place these in any free register.
11413 if (IsAnyRegCC)
11414 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11415 Ops.push_back(getValue(CB.getArgOperand(i)));
11416
11417 // Push the arguments from the call instruction.
11418 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11419 Ops.append(Call->op_begin() + 2, e);
11420
11421 // Push live variables for the stack map.
11422 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11423
11424 SDVTList NodeTys;
11425 if (IsAnyRegCC && HasDef) {
11426 // Create the return types based on the intrinsic definition
11427 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11428 SmallVector<EVT, 3> ValueVTs;
11429 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11430 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11431
11432 // There is always a chain and a glue type at the end
11433 ValueVTs.push_back(MVT::Other);
11434 ValueVTs.push_back(MVT::Glue);
11435 NodeTys = DAG.getVTList(ValueVTs);
11436 } else
11437 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11438
11439 // Replace the target specific call node with a PATCHPOINT node.
11440 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11441
11442 // Update the NodeMap.
11443 if (HasDef) {
11444 if (IsAnyRegCC)
11445 setValue(&CB, SDValue(PPV.getNode(), 0));
11446 else
11447 setValue(&CB, Result.first);
11448 }
11449
11450 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11451 // call sequence. Furthermore the location of the chain and glue can change
11452 // when the AnyReg calling convention is used and the intrinsic returns a
11453 // value.
11454 if (IsAnyRegCC && HasDef) {
11455 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11456 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11457 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11458 } else
11459 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11460 DAG.DeleteNode(Call);
11461
11462 // Inform the Frame Information that we have a patchpoint in this function.
11463 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11464}
11465
11466void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11467 unsigned Intrinsic) {
11468 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11469 SDValue Op1 = getValue(I.getArgOperand(0));
11470 SDValue Op2;
11471 if (I.arg_size() > 1)
11472 Op2 = getValue(I.getArgOperand(1));
11473 SDLoc dl = getCurSDLoc();
11474 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11475 SDValue Res;
11476 SDNodeFlags SDFlags;
11477 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11478 SDFlags.copyFMF(*FPMO);
11479
11480 switch (Intrinsic) {
11481 case Intrinsic::vector_reduce_fadd:
11482 if (SDFlags.hasAllowReassociation())
11483 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11484 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11485 SDFlags);
11486 else
11487 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11488 break;
11489 case Intrinsic::vector_reduce_fmul:
11490 if (SDFlags.hasAllowReassociation())
11491 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11492 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11493 SDFlags);
11494 else
11495 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11496 break;
11497 case Intrinsic::vector_reduce_add:
11498 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11499 break;
11500 case Intrinsic::vector_reduce_mul:
11501 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11502 break;
11503 case Intrinsic::vector_reduce_and:
11504 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11505 break;
11506 case Intrinsic::vector_reduce_or:
11507 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11508 break;
11509 case Intrinsic::vector_reduce_xor:
11510 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11511 break;
11512 case Intrinsic::vector_reduce_smax:
11513 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11514 break;
11515 case Intrinsic::vector_reduce_smin:
11516 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11517 break;
11518 case Intrinsic::vector_reduce_umax:
11519 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11520 break;
11521 case Intrinsic::vector_reduce_umin:
11522 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11523 break;
11524 case Intrinsic::vector_reduce_fmax:
11525 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11526 break;
11527 case Intrinsic::vector_reduce_fmin:
11528 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11529 break;
11530 case Intrinsic::vector_reduce_fmaximum:
11531 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11532 break;
11533 case Intrinsic::vector_reduce_fminimum:
11534 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11535 break;
11536 case Intrinsic::vector_reduce_fmaximumnum:
11537 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11538 break;
11539 case Intrinsic::vector_reduce_fminimumnum:
11540 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11541 break;
11542 default:
11543 llvm_unreachable("Unhandled vector reduce intrinsic");
11544 }
11545 setValue(&I, Res);
11546}
11547
11548/// Returns an AttributeList representing the attributes applied to the return
11549/// value of the given call.
11552 if (CLI.RetSExt)
11553 Attrs.push_back(Attribute::SExt);
11554 if (CLI.RetZExt)
11555 Attrs.push_back(Attribute::ZExt);
11556 if (CLI.IsInReg)
11557 Attrs.push_back(Attribute::InReg);
11558
11559 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11560 Attrs);
11561}
11562
11563/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11564/// implementation, which just calls LowerCall.
11565/// FIXME: When all targets are
11566/// migrated to using LowerCall, this hook should be integrated into SDISel.
11567std::pair<SDValue, SDValue>
11569 LLVMContext &Context = CLI.RetTy->getContext();
11570
11571 // Handle the incoming return values from the call.
11572 CLI.Ins.clear();
11573 SmallVector<Type *, 4> RetOrigTys;
11575 auto &DL = CLI.DAG.getDataLayout();
11576 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11577
11578 SmallVector<EVT, 4> RetVTs;
11579 if (CLI.RetTy != CLI.OrigRetTy) {
11580 assert(RetOrigTys.size() == 1 &&
11581 "Only supported for non-aggregate returns");
11582 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11583 } else {
11584 for (Type *Ty : RetOrigTys)
11585 RetVTs.push_back(getValueType(DL, Ty));
11586 }
11587
11588 if (CLI.IsPostTypeLegalization) {
11589 // If we are lowering a libcall after legalization, split the return type.
11590 SmallVector<Type *, 4> OldRetOrigTys;
11591 SmallVector<EVT, 4> OldRetVTs;
11592 SmallVector<TypeSize, 4> OldOffsets;
11593 RetOrigTys.swap(OldRetOrigTys);
11594 RetVTs.swap(OldRetVTs);
11595 Offsets.swap(OldOffsets);
11596
11597 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11598 EVT RetVT = OldRetVTs[i];
11599 uint64_t Offset = OldOffsets[i];
11600 MVT RegisterVT = getRegisterType(Context, RetVT);
11601 unsigned NumRegs = getNumRegisters(Context, RetVT);
11602 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11603 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11604 RetVTs.append(NumRegs, RegisterVT);
11605 for (unsigned j = 0; j != NumRegs; ++j)
11606 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11607 }
11608 }
11609
11611 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11612
11613 bool CanLowerReturn =
11615 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11616
11617 SDValue DemoteStackSlot;
11618 int DemoteStackIdx = -100;
11619 if (!CanLowerReturn) {
11620 // FIXME: equivalent assert?
11621 // assert(!CS.hasInAllocaArgument() &&
11622 // "sret demotion is incompatible with inalloca");
11623 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11624 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11626 DemoteStackIdx =
11627 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11628 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11629
11630 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11631 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11632 Entry.IsSRet = true;
11633 Entry.Alignment = Alignment;
11634 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11635 CLI.NumFixedArgs += 1;
11636 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11637 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(Context);
11638
11639 // sret demotion isn't compatible with tail-calls, since the sret argument
11640 // points into the callers stack frame.
11641 CLI.IsTailCall = false;
11642 } else {
11643 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11644 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11645 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11646 ISD::ArgFlagsTy Flags;
11647 if (NeedsRegBlock) {
11648 Flags.setInConsecutiveRegs();
11649 if (I == RetVTs.size() - 1)
11650 Flags.setInConsecutiveRegsLast();
11651 }
11652 EVT VT = RetVTs[I];
11653 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11654 unsigned NumRegs =
11655 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11656 for (unsigned i = 0; i != NumRegs; ++i) {
11657 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11659 if (CLI.RetTy->isPointerTy()) {
11660 Ret.Flags.setPointer();
11662 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11663 }
11664 if (CLI.RetSExt)
11665 Ret.Flags.setSExt();
11666 if (CLI.RetZExt)
11667 Ret.Flags.setZExt();
11668 if (CLI.IsInReg)
11669 Ret.Flags.setInReg();
11670 CLI.Ins.push_back(Ret);
11671 }
11672 }
11673 }
11674
11675 // We push in swifterror return as the last element of CLI.Ins.
11676 ArgListTy &Args = CLI.getArgs();
11677 if (supportSwiftError()) {
11678 for (const ArgListEntry &Arg : Args) {
11679 if (Arg.IsSwiftError) {
11680 ISD::ArgFlagsTy Flags;
11681 Flags.setSwiftError();
11683 PointerType::getUnqual(Context),
11684 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11685 CLI.Ins.push_back(Ret);
11686 }
11687 }
11688 }
11689
11690 // Handle all of the outgoing arguments.
11691 CLI.Outs.clear();
11692 CLI.OutVals.clear();
11693 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11694 SmallVector<Type *, 4> OrigArgTys;
11695 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11696 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11697 Type *FinalType = Args[i].Ty;
11698 if (Args[i].IsByVal)
11699 FinalType = Args[i].IndirectType;
11700 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11701 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11702 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11703 ++Value) {
11704 Type *OrigArgTy = OrigArgTys[Value];
11705 Type *ArgTy = OrigArgTy;
11706 if (Args[i].Ty != Args[i].OrigTy) {
11707 assert(Value == 0 && "Only supported for non-aggregate arguments");
11708 ArgTy = Args[i].Ty;
11709 }
11710
11711 EVT VT = getValueType(DL, ArgTy);
11712 SDValue Op = SDValue(Args[i].Node.getNode(),
11713 Args[i].Node.getResNo() + Value);
11714 ISD::ArgFlagsTy Flags;
11715
11716 // Certain targets (such as MIPS), may have a different ABI alignment
11717 // for a type depending on the context. Give the target a chance to
11718 // specify the alignment it wants.
11719 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11720 Flags.setOrigAlign(OriginalAlignment);
11721
11722 if (i >= CLI.NumFixedArgs)
11723 Flags.setVarArg();
11724 if (ArgTy->isPointerTy()) {
11725 Flags.setPointer();
11726 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11727 }
11728 if (Args[i].IsZExt)
11729 Flags.setZExt();
11730 if (Args[i].IsSExt)
11731 Flags.setSExt();
11732 if (Args[i].IsNoExt)
11733 Flags.setNoExt();
11734 if (Args[i].IsInReg) {
11735 // If we are using vectorcall calling convention, a structure that is
11736 // passed InReg - is surely an HVA
11738 isa<StructType>(FinalType)) {
11739 // The first value of a structure is marked
11740 if (0 == Value)
11741 Flags.setHvaStart();
11742 Flags.setHva();
11743 }
11744 // Set InReg Flag
11745 Flags.setInReg();
11746 }
11747 if (Args[i].IsSRet)
11748 Flags.setSRet();
11749 if (Args[i].IsSwiftSelf)
11750 Flags.setSwiftSelf();
11751 if (Args[i].IsSwiftAsync)
11752 Flags.setSwiftAsync();
11753 if (Args[i].IsSwiftError)
11754 Flags.setSwiftError();
11755 if (Args[i].IsCFGuardTarget)
11756 Flags.setCFGuardTarget();
11757 if (Args[i].IsByVal)
11758 Flags.setByVal();
11759 if (Args[i].IsByRef)
11760 Flags.setByRef();
11761 if (Args[i].IsPreallocated) {
11762 Flags.setPreallocated();
11763 // Set the byval flag for CCAssignFn callbacks that don't know about
11764 // preallocated. This way we can know how many bytes we should've
11765 // allocated and how many bytes a callee cleanup function will pop. If
11766 // we port preallocated to more targets, we'll have to add custom
11767 // preallocated handling in the various CC lowering callbacks.
11768 Flags.setByVal();
11769 }
11770 if (Args[i].IsInAlloca) {
11771 Flags.setInAlloca();
11772 // Set the byval flag for CCAssignFn callbacks that don't know about
11773 // inalloca. This way we can know how many bytes we should've allocated
11774 // and how many bytes a callee cleanup function will pop. If we port
11775 // inalloca to more targets, we'll have to add custom inalloca handling
11776 // in the various CC lowering callbacks.
11777 Flags.setByVal();
11778 }
11779 Align MemAlign;
11780 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11781 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11782 Flags.setByValSize(FrameSize);
11783
11784 // info is not there but there are cases it cannot get right.
11785 if (auto MA = Args[i].Alignment)
11786 MemAlign = *MA;
11787 else
11788 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11789 } else if (auto MA = Args[i].Alignment) {
11790 MemAlign = *MA;
11791 } else {
11792 MemAlign = OriginalAlignment;
11793 }
11794 Flags.setMemAlign(MemAlign);
11795 if (Args[i].IsNest)
11796 Flags.setNest();
11797 if (NeedsRegBlock)
11798 Flags.setInConsecutiveRegs();
11799
11800 MVT PartVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11801 unsigned NumParts =
11802 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11805
11806 if (Args[i].IsSExt)
11808 else if (Args[i].IsZExt)
11810
11811 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11812 // for now.
11813 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11815 assert((CLI.RetTy == Args[i].Ty ||
11816 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11818 Args[i].Ty->getPointerAddressSpace())) &&
11819 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11820 // Before passing 'returned' to the target lowering code, ensure that
11821 // either the register MVT and the actual EVT are the same size or that
11822 // the return value and argument are extended in the same way; in these
11823 // cases it's safe to pass the argument register value unchanged as the
11824 // return register value (although it's at the target's option whether
11825 // to do so)
11826 // TODO: allow code generation to take advantage of partially preserved
11827 // registers rather than clobbering the entire register when the
11828 // parameter extension method is not compatible with the return
11829 // extension method
11830 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11831 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11832 CLI.RetZExt == Args[i].IsZExt))
11833 Flags.setReturned();
11834 }
11835
11836 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11837 CLI.CallConv, ExtendKind);
11838
11839 for (unsigned j = 0; j != NumParts; ++j) {
11840 // if it isn't first piece, alignment must be 1
11841 // For scalable vectors the scalable part is currently handled
11842 // by individual targets, so we just use the known minimum size here.
11843 ISD::OutputArg MyFlags(
11844 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11845 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11846 if (NumParts > 1 && j == 0)
11847 MyFlags.Flags.setSplit();
11848 else if (j != 0) {
11849 MyFlags.Flags.setOrigAlign(Align(1));
11850 if (j == NumParts - 1)
11851 MyFlags.Flags.setSplitEnd();
11852 }
11853
11854 CLI.Outs.push_back(MyFlags);
11855 CLI.OutVals.push_back(Parts[j]);
11856 }
11857
11858 if (NeedsRegBlock && Value == NumValues - 1)
11859 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11860 }
11861 }
11862
11864 CLI.Chain = LowerCall(CLI, InVals);
11865
11866 // Update CLI.InVals to use outside of this function.
11867 CLI.InVals = InVals;
11868
11869 // Verify that the target's LowerCall behaved as expected.
11870 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11871 "LowerCall didn't return a valid chain!");
11872 assert((!CLI.IsTailCall || InVals.empty()) &&
11873 "LowerCall emitted a return value for a tail call!");
11874 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11875 "LowerCall didn't emit the correct number of values!");
11876
11877 // For a tail call, the return value is merely live-out and there aren't
11878 // any nodes in the DAG representing it. Return a special value to
11879 // indicate that a tail call has been emitted and no more Instructions
11880 // should be processed in the current block.
11881 if (CLI.IsTailCall) {
11882 CLI.DAG.setRoot(CLI.Chain);
11883 return std::make_pair(SDValue(), SDValue());
11884 }
11885
11886#ifndef NDEBUG
11887 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11888 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11889 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11890 "LowerCall emitted a value with the wrong type!");
11891 }
11892#endif
11893
11894 SmallVector<SDValue, 4> ReturnValues;
11895 if (!CanLowerReturn) {
11896 // The instruction result is the result of loading from the
11897 // hidden sret parameter.
11898 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11899
11900 unsigned NumValues = RetVTs.size();
11901 ReturnValues.resize(NumValues);
11902 SmallVector<SDValue, 4> Chains(NumValues);
11903
11904 // An aggregate return value cannot wrap around the address space, so
11905 // offsets to its parts don't wrap either.
11907 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11908 for (unsigned i = 0; i < NumValues; ++i) {
11910 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11912 SDValue L = CLI.DAG.getLoad(
11913 RetVTs[i], CLI.DL, CLI.Chain, Add,
11915 DemoteStackIdx, Offsets[i]),
11916 HiddenSRetAlign);
11917 ReturnValues[i] = L;
11918 Chains[i] = L.getValue(1);
11919 }
11920
11921 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11922 } else {
11923 // Collect the legal value parts into potentially illegal values
11924 // that correspond to the original function's return values.
11925 std::optional<ISD::NodeType> AssertOp;
11926 if (CLI.RetSExt)
11927 AssertOp = ISD::AssertSext;
11928 else if (CLI.RetZExt)
11929 AssertOp = ISD::AssertZext;
11930 unsigned CurReg = 0;
11931 for (EVT VT : RetVTs) {
11932 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11933 unsigned NumRegs =
11934 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11935
11936 ReturnValues.push_back(getCopyFromParts(
11937 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11938 CLI.Chain, CLI.CallConv, AssertOp));
11939 CurReg += NumRegs;
11940 }
11941
11942 // For a function returning void, there is no return value. We can't create
11943 // such a node, so we just return a null return value in that case. In
11944 // that case, nothing will actually look at the value.
11945 if (ReturnValues.empty())
11946 return std::make_pair(SDValue(), CLI.Chain);
11947 }
11948
11949 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11950 CLI.DAG.getVTList(RetVTs), ReturnValues);
11951 return std::make_pair(Res, CLI.Chain);
11952}
11953
11954/// Places new result values for the node in Results (their number
11955/// and types must exactly match those of the original return values of
11956/// the node), or leaves Results empty, which indicates that the node is not
11957/// to be custom lowered after all.
11960 SelectionDAG &DAG) const {
11961 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11962
11963 if (!Res.getNode())
11964 return;
11965
11966 // If the original node has one result, take the return value from
11967 // LowerOperation as is. It might not be result number 0.
11968 if (N->getNumValues() == 1) {
11969 Results.push_back(Res);
11970 return;
11971 }
11972
11973 // If the original node has multiple results, then the return node should
11974 // have the same number of results.
11975 assert((N->getNumValues() == Res->getNumValues()) &&
11976 "Lowering returned the wrong number of results!");
11977
11978 // Places new result values base on N result number.
11979 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11980 Results.push_back(Res.getValue(I));
11981}
11982
11984 llvm_unreachable("LowerOperation not implemented for this target!");
11985}
11986
11988 Register Reg,
11989 ISD::NodeType ExtendType) {
11991 assert((Op.getOpcode() != ISD::CopyFromReg ||
11992 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11993 "Copy from a reg to the same reg!");
11994 assert(!Reg.isPhysical() && "Is a physreg");
11995
11996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11997 // If this is an InlineAsm we have to match the registers required, not the
11998 // notional registers required by the type.
11999
12000 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
12001 std::nullopt); // This is not an ABI copy.
12002 SDValue Chain = DAG.getEntryNode();
12003
12004 if (ExtendType == ISD::ANY_EXTEND) {
12005 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
12006 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
12007 ExtendType = PreferredExtendIt->second;
12008 }
12009 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
12010 PendingExports.push_back(Chain);
12011}
12012
12014
12015/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
12016/// entry block, return true. This includes arguments used by switches, since
12017/// the switch may expand into multiple basic blocks.
12018static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
12019 // With FastISel active, we may be splitting blocks, so force creation
12020 // of virtual registers for all non-dead arguments.
12021 if (FastISel)
12022 return A->use_empty();
12023
12024 const BasicBlock &Entry = A->getParent()->front();
12025 for (const User *U : A->users())
12026 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
12027 return false; // Use not in entry block.
12028
12029 return true;
12030}
12031
12033 DenseMap<const Argument *,
12034 std::pair<const AllocaInst *, const StoreInst *>>;
12035
12036/// Scan the entry block of the function in FuncInfo for arguments that look
12037/// like copies into a local alloca. Record any copied arguments in
12038/// ArgCopyElisionCandidates.
12039static void
12041 FunctionLoweringInfo *FuncInfo,
12042 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
12043 // Record the state of every static alloca used in the entry block. Argument
12044 // allocas are all used in the entry block, so we need approximately as many
12045 // entries as we have arguments.
12046 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
12048 unsigned NumArgs = FuncInfo->Fn->arg_size();
12049 StaticAllocas.reserve(NumArgs * 2);
12050
12051 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
12052 if (!V)
12053 return nullptr;
12054 V = V->stripPointerCasts();
12055 const auto *AI = dyn_cast<AllocaInst>(V);
12056 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
12057 return nullptr;
12058 auto Iter = StaticAllocas.insert({AI, Unknown});
12059 return &Iter.first->second;
12060 };
12061
12062 // Look for stores of arguments to static allocas. Look through bitcasts and
12063 // GEPs to handle type coercions, as long as the alloca is fully initialized
12064 // by the store. Any non-store use of an alloca escapes it and any subsequent
12065 // unanalyzed store might write it.
12066 // FIXME: Handle structs initialized with multiple stores.
12067 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
12068 // Look for stores, and handle non-store uses conservatively.
12069 const auto *SI = dyn_cast<StoreInst>(&I);
12070 if (!SI) {
12071 // We will look through cast uses, so ignore them completely.
12072 if (I.isCast())
12073 continue;
12074 // Ignore pseudo op intrinsics, they don't escape or store to allocas.
12076 continue;
12077 // This is an unknown instruction. Assume it escapes or writes to all
12078 // static alloca operands.
12079 for (const Use &U : I.operands()) {
12080 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
12081 *Info = StaticAllocaInfo::Clobbered;
12082 }
12083 continue;
12084 }
12085
12086 // If the stored value is a static alloca, mark it as escaped.
12087 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
12088 *Info = StaticAllocaInfo::Clobbered;
12089
12090 // Check if the destination is a static alloca.
12091 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
12092 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
12093 if (!Info)
12094 continue;
12095 const AllocaInst *AI = cast<AllocaInst>(Dst);
12096
12097 // Skip allocas that have been initialized or clobbered.
12098 if (*Info != StaticAllocaInfo::Unknown)
12099 continue;
12100
12101 // Check if the stored value is an argument, and that this store fully
12102 // initializes the alloca.
12103 // If the argument type has padding bits we can't directly forward a pointer
12104 // as the upper bits may contain garbage.
12105 // Don't elide copies from the same argument twice.
12106 const Value *Val = SI->getValueOperand()->stripPointerCasts();
12107 const auto *Arg = dyn_cast<Argument>(Val);
12108 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
12109 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
12110 Arg->getType()->isEmptyTy() || !AllocaSize ||
12111 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
12112 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
12113 ArgCopyElisionCandidates.count(Arg)) {
12114 *Info = StaticAllocaInfo::Clobbered;
12115 continue;
12116 }
12117
12118 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
12119 << '\n');
12120
12121 // Mark this alloca and store for argument copy elision.
12122 *Info = StaticAllocaInfo::Elidable;
12123 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
12124
12125 // Stop scanning if we've seen all arguments. This will happen early in -O0
12126 // builds, which is useful, because -O0 builds have large entry blocks and
12127 // many allocas.
12128 if (ArgCopyElisionCandidates.size() == NumArgs)
12129 break;
12130 }
12131}
12132
12133/// Try to elide argument copies from memory into a local alloca. Succeeds if
12134/// ArgVal is a load from a suitable fixed stack object.
12137 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
12138 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
12139 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
12140 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
12141 // Check if this is a load from a fixed stack object.
12142 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
12143 if (!LNode)
12144 return;
12145 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
12146 if (!FINode)
12147 return;
12148
12149 // Check that the fixed stack object is the right size and alignment.
12150 // Look at the alignment that the user wrote on the alloca instead of looking
12151 // at the stack object.
12152 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
12153 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
12154 const AllocaInst *AI = ArgCopyIter->second.first;
12155 int FixedIndex = FINode->getIndex();
12156 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
12157 int OldIndex = AllocaIndex;
12158 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
12159 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
12160 LLVM_DEBUG(
12161 dbgs() << " argument copy elision failed due to bad fixed stack "
12162 "object size\n");
12163 return;
12164 }
12165 Align RequiredAlignment = AI->getAlign();
12166 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
12167 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
12168 "greater than stack argument alignment ("
12169 << DebugStr(RequiredAlignment) << " vs "
12170 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
12171 return;
12172 }
12173
12174 // Perform the elision. Delete the old stack object and replace its only use
12175 // in the variable info map. Mark the stack object as mutable and aliased.
12176 LLVM_DEBUG({
12177 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
12178 << " Replacing frame index " << OldIndex << " with " << FixedIndex
12179 << '\n';
12180 });
12181 MFI.RemoveStackObject(OldIndex);
12182 MFI.setIsImmutableObjectIndex(FixedIndex, false);
12183 MFI.setIsAliasedObjectIndex(FixedIndex, true);
12184 AllocaIndex = FixedIndex;
12185 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
12186 for (SDValue ArgVal : ArgVals)
12187 Chains.push_back(ArgVal.getValue(1));
12188
12189 // Avoid emitting code for the store implementing the copy.
12190 const StoreInst *SI = ArgCopyIter->second.second;
12191 ElidedArgCopyInstrs.insert(SI);
12192
12193 // Check for uses of the argument again so that we can avoid exporting ArgVal
12194 // if it is't used by anything other than the store.
12195 for (const Value *U : Arg.users()) {
12196 if (U != SI) {
12197 ArgHasUses = true;
12198 break;
12199 }
12200 }
12201}
12202
12203void SelectionDAGISel::LowerArguments(const Function &F, bool FastISel) {
12204 SelectionDAG &DAG = SDB->DAG;
12205 SDLoc dl = SDB->getCurSDLoc();
12206 const DataLayout &DL = DAG.getDataLayout();
12208
12209 // In Naked functions we aren't going to save any registers.
12210 if (F.hasFnAttribute(Attribute::Naked))
12211 return;
12212
12213 if (!FuncInfo->CanLowerReturn) {
12214 // Put in an sret pointer parameter before all the other parameters.
12215 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12216
12217 ISD::ArgFlagsTy Flags;
12218 Flags.setSRet();
12219 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
12220 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12222 Ins.push_back(RetArg);
12223 }
12224
12225 // Look for stores of arguments to static allocas. Mark such arguments with a
12226 // flag to ask the target to give us the memory location of that argument if
12227 // available.
12228 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12230 ArgCopyElisionCandidates);
12231
12232 // Set up the incoming argument description vector.
12233 for (const Argument &Arg : F.args()) {
12234 unsigned ArgNo = Arg.getArgNo();
12236 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12237 bool isArgValueUsed = !Arg.use_empty();
12238 Type *FinalType = Arg.getType();
12239 if (Arg.hasAttribute(Attribute::ByVal))
12240 FinalType = Arg.getParamByValType();
12241 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12242 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12243 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12244 ++Value) {
12245 Type *ArgTy = Types[Value];
12246 EVT VT = TLI->getValueType(DL, ArgTy);
12247 ISD::ArgFlagsTy Flags;
12248
12249 if (ArgTy->isPointerTy()) {
12250 Flags.setPointer();
12251 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12252 }
12253 if (Arg.hasAttribute(Attribute::ZExt))
12254 Flags.setZExt();
12255 if (Arg.hasAttribute(Attribute::SExt))
12256 Flags.setSExt();
12257 if (Arg.hasAttribute(Attribute::InReg)) {
12258 // If we are using vectorcall calling convention, a structure that is
12259 // passed InReg - is surely an HVA
12260 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12261 isa<StructType>(Arg.getType())) {
12262 // The first value of a structure is marked
12263 if (0 == Value)
12264 Flags.setHvaStart();
12265 Flags.setHva();
12266 }
12267 // Set InReg Flag
12268 Flags.setInReg();
12269 }
12270 if (Arg.hasAttribute(Attribute::StructRet))
12271 Flags.setSRet();
12272 if (Arg.hasAttribute(Attribute::SwiftSelf))
12273 Flags.setSwiftSelf();
12274 if (Arg.hasAttribute(Attribute::SwiftAsync))
12275 Flags.setSwiftAsync();
12276 if (Arg.hasAttribute(Attribute::SwiftError))
12277 Flags.setSwiftError();
12278 if (Arg.hasAttribute(Attribute::ByVal))
12279 Flags.setByVal();
12280 if (Arg.hasAttribute(Attribute::ByRef))
12281 Flags.setByRef();
12282 if (Arg.hasAttribute(Attribute::InAlloca)) {
12283 Flags.setInAlloca();
12284 // Set the byval flag for CCAssignFn callbacks that don't know about
12285 // inalloca. This way we can know how many bytes we should've allocated
12286 // and how many bytes a callee cleanup function will pop. If we port
12287 // inalloca to more targets, we'll have to add custom inalloca handling
12288 // in the various CC lowering callbacks.
12289 Flags.setByVal();
12290 }
12291 if (Arg.hasAttribute(Attribute::Preallocated)) {
12292 Flags.setPreallocated();
12293 // Set the byval flag for CCAssignFn callbacks that don't know about
12294 // preallocated. This way we can know how many bytes we should've
12295 // allocated and how many bytes a callee cleanup function will pop. If
12296 // we port preallocated to more targets, we'll have to add custom
12297 // preallocated handling in the various CC lowering callbacks.
12298 Flags.setByVal();
12299 }
12300
12301 // Certain targets (such as MIPS), may have a different ABI alignment
12302 // for a type depending on the context. Give the target a chance to
12303 // specify the alignment it wants.
12304 const Align OriginalAlignment(
12305 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12306 Flags.setOrigAlign(OriginalAlignment);
12307
12308 Align MemAlign;
12309 Type *ArgMemTy = nullptr;
12310 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12311 Flags.isByRef()) {
12312 if (!ArgMemTy)
12313 ArgMemTy = Arg.getPointeeInMemoryValueType();
12314
12315 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12316
12317 // For in-memory arguments, size and alignment should be passed from FE.
12318 // BE will guess if this info is not there but there are cases it cannot
12319 // get right.
12320 if (auto ParamAlign = Arg.getParamStackAlign())
12321 MemAlign = *ParamAlign;
12322 else if ((ParamAlign = Arg.getParamAlign()))
12323 MemAlign = *ParamAlign;
12324 else
12325 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12326 if (Flags.isByRef())
12327 Flags.setByRefSize(MemSize);
12328 else
12329 Flags.setByValSize(MemSize);
12330 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12331 MemAlign = *ParamAlign;
12332 } else {
12333 MemAlign = OriginalAlignment;
12334 }
12335 Flags.setMemAlign(MemAlign);
12336
12337 if (Arg.hasAttribute(Attribute::Nest))
12338 Flags.setNest();
12339 if (NeedsRegBlock)
12340 Flags.setInConsecutiveRegs();
12341 if (ArgCopyElisionCandidates.count(&Arg))
12342 Flags.setCopyElisionCandidate();
12343 if (Arg.hasAttribute(Attribute::Returned))
12344 Flags.setReturned();
12345
12346 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12347 *CurDAG->getContext(), F.getCallingConv(), VT);
12348 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12349 *CurDAG->getContext(), F.getCallingConv(), VT);
12350 for (unsigned i = 0; i != NumRegs; ++i) {
12351 // For scalable vectors, use the minimum size; individual targets
12352 // are responsible for handling scalable vector arguments and
12353 // return values.
12354 ISD::InputArg MyFlags(
12355 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12356 i * RegisterVT.getStoreSize().getKnownMinValue());
12357 if (NumRegs > 1 && i == 0)
12358 MyFlags.Flags.setSplit();
12359 // if it isn't first piece, alignment must be 1
12360 else if (i > 0) {
12361 MyFlags.Flags.setOrigAlign(Align(1));
12362 if (i == NumRegs - 1)
12363 MyFlags.Flags.setSplitEnd();
12364 }
12365 Ins.push_back(MyFlags);
12366 }
12367 if (NeedsRegBlock && Value == NumValues - 1)
12368 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12369 }
12370 }
12371
12372 // Call the target to set up the argument values.
12374 SDValue NewRoot = TLI->LowerFormalArguments(
12375 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12376
12377 // Verify that the target's LowerFormalArguments behaved as expected.
12378 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12379 "LowerFormalArguments didn't return a valid chain!");
12380 assert(InVals.size() == Ins.size() &&
12381 "LowerFormalArguments didn't emit the correct number of values!");
12382 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12383 "LowerFormalArguments emitted a null value!");
12384
12385 // Update the DAG with the new chain value resulting from argument lowering.
12386 DAG.setRoot(NewRoot);
12387
12388 // Set up the argument values.
12389 unsigned i = 0;
12390 if (!FuncInfo->CanLowerReturn) {
12391 // Create a virtual register for the sret pointer, and put in a copy
12392 // from the sret argument into it.
12393 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12394 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12395 std::optional<ISD::NodeType> AssertOp;
12396 SDValue ArgValue =
12397 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12398 F.getCallingConv(), AssertOp);
12399
12400 MachineFunction& MF = SDB->DAG.getMachineFunction();
12401 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12402 Register SRetReg =
12403 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12404 FuncInfo->DemoteRegister = SRetReg;
12405 NewRoot =
12406 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12407 DAG.setRoot(NewRoot);
12408
12409 // i indexes lowered arguments. Bump it past the hidden sret argument.
12410 ++i;
12411 }
12412
12414 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12415 for (const Argument &Arg : F.args()) {
12416 SmallVector<SDValue, 4> ArgValues;
12417 SmallVector<EVT, 4> ValueVTs;
12418 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12419 unsigned NumValues = ValueVTs.size();
12420 if (NumValues == 0)
12421 continue;
12422
12423 bool ArgHasUses = !Arg.use_empty();
12424
12425 // Elide the copying store if the target loaded this argument from a
12426 // suitable fixed stack object.
12427 if (Ins[i].Flags.isCopyElisionCandidate()) {
12428 unsigned NumParts = 0;
12429 for (EVT VT : ValueVTs)
12430 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12431 F.getCallingConv(), VT);
12432
12433 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12434 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12435 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12436 }
12437
12438 // If this argument is unused then remember its value. It is used to generate
12439 // debugging information.
12440 bool isSwiftErrorArg =
12441 TLI->supportSwiftError() &&
12442 Arg.hasAttribute(Attribute::SwiftError);
12443 if (!ArgHasUses && !isSwiftErrorArg) {
12444 SDB->setUnusedArgValue(&Arg, InVals[i]);
12445
12446 // Also remember any frame index for use in FastISel.
12447 if (FrameIndexSDNode *FI =
12449 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12450 }
12451
12452 for (unsigned Val = 0; Val != NumValues; ++Val) {
12453 EVT VT = ValueVTs[Val];
12454 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12455 F.getCallingConv(), VT);
12456 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12457 *CurDAG->getContext(), F.getCallingConv(), VT);
12458
12459 // Even an apparent 'unused' swifterror argument needs to be returned. So
12460 // we do generate a copy for it that can be used on return from the
12461 // function.
12462 if (ArgHasUses || isSwiftErrorArg) {
12463 std::optional<ISD::NodeType> AssertOp;
12464 if (Arg.hasAttribute(Attribute::SExt))
12465 AssertOp = ISD::AssertSext;
12466 else if (Arg.hasAttribute(Attribute::ZExt))
12467 AssertOp = ISD::AssertZext;
12468
12469 SDValue OutVal =
12470 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12471 NewRoot, F.getCallingConv(), AssertOp);
12472
12473 FPClassTest NoFPClass = Arg.getNoFPClass();
12474 if (NoFPClass != fcNone) {
12475 SDValue SDNoFPClass = DAG.getTargetConstant(
12476 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12477 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12478 OutVal, SDNoFPClass);
12479 }
12480 ArgValues.push_back(OutVal);
12481 }
12482
12483 i += NumParts;
12484 }
12485
12486 // We don't need to do anything else for unused arguments.
12487 if (ArgValues.empty())
12488 continue;
12489
12490 // Note down frame index.
12491 if (FrameIndexSDNode *FI =
12492 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12493 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12494
12495 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12496 SDB->getCurSDLoc());
12497
12498 SDB->setValue(&Arg, Res);
12499 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12500 // We want to associate the argument with the frame index, among
12501 // involved operands, that correspond to the lowest address. The
12502 // getCopyFromParts function, called earlier, is swapping the order of
12503 // the operands to BUILD_PAIR depending on endianness. The result of
12504 // that swapping is that the least significant bits of the argument will
12505 // be in the first operand of the BUILD_PAIR node, and the most
12506 // significant bits will be in the second operand.
12507 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12508 if (LoadSDNode *LNode =
12509 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12510 if (FrameIndexSDNode *FI =
12511 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12512 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12513 }
12514
12515 // Analyses past this point are naive and don't expect an assertion.
12516 if (Res.getOpcode() == ISD::AssertZext)
12517 Res = Res.getOperand(0);
12518
12519 // Update the SwiftErrorVRegDefMap.
12520 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12521 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12522 if (Reg.isVirtual())
12523 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12524 Reg);
12525 }
12526
12527 // If this argument is live outside of the entry block, insert a copy from
12528 // wherever we got it to the vreg that other BB's will reference it as.
12529 if (Res.getOpcode() == ISD::CopyFromReg) {
12530 // If we can, though, try to skip creating an unnecessary vreg.
12531 // FIXME: This isn't very clean... it would be nice to make this more
12532 // general.
12533 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12534 if (Reg.isVirtual()) {
12535 FuncInfo->ValueMap[&Arg] = Reg;
12536 continue;
12537 }
12538 }
12539 if (!isOnlyUsedInEntryBlock(&Arg, FastISel)) {
12540 FuncInfo->InitializeRegForValue(&Arg);
12541 SDB->CopyToExportRegsIfNeeded(&Arg);
12542 }
12543 }
12544
12545 if (!Chains.empty()) {
12546 Chains.push_back(NewRoot);
12547 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12548 }
12549
12550 DAG.setRoot(NewRoot);
12551
12552 assert(i == InVals.size() && "Argument register count mismatch!");
12553
12554 // If any argument copy elisions occurred and we have debug info, update the
12555 // stale frame indices used in the dbg.declare variable info table.
12556 if (!ArgCopyElisionFrameIndexMap.empty()) {
12557 for (MachineFunction::VariableDbgInfo &VI :
12558 MF->getInStackSlotVariableDbgInfo()) {
12559 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12560 if (I != ArgCopyElisionFrameIndexMap.end())
12561 VI.updateStackSlot(I->second);
12562 }
12563 }
12564
12565 // Finally, if the target has anything special to do, allow it to do so.
12567}
12568
12569/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12570/// ensure constants are generated when needed. Remember the virtual registers
12571/// that need to be added to the Machine PHI nodes as input. We cannot just
12572/// directly add them, because expansion might result in multiple MBB's for one
12573/// BB. As such, the start of the BB might correspond to a different MBB than
12574/// the end.
12575void
12576SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12578
12579 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12580
12581 // Check PHI nodes in successors that expect a value to be available from this
12582 // block.
12583 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12584 if (!isa<PHINode>(SuccBB->begin())) continue;
12585 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12586
12587 // If this terminator has multiple identical successors (common for
12588 // switches), only handle each succ once.
12589 if (!SuccsHandled.insert(SuccMBB).second)
12590 continue;
12591
12593
12594 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12595 // nodes and Machine PHI nodes, but the incoming operands have not been
12596 // emitted yet.
12597 for (const PHINode &PN : SuccBB->phis()) {
12598 // Ignore dead phi's.
12599 if (PN.use_empty())
12600 continue;
12601
12602 // Skip empty types
12603 if (PN.getType()->isEmptyTy())
12604 continue;
12605
12606 Register Reg;
12607 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12608
12609 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12610 Register &RegOut = ConstantsOut[C];
12611 if (!RegOut) {
12612 RegOut = FuncInfo.CreateRegs(PHIOp);
12613 // We need to zero/sign extend ConstantInt phi operands to match
12614 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12615 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12616 if (auto *CI = dyn_cast<ConstantInt>(C))
12617 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12619 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12620 }
12621 Reg = RegOut;
12622 } else {
12623 auto I = FuncInfo.ValueMap.find(PHIOp);
12624 if (I != FuncInfo.ValueMap.end())
12625 Reg = I->second;
12626 else {
12627 assert(isa<AllocaInst>(PHIOp) &&
12628 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12629 "Didn't codegen value into a register!??");
12630 Reg = FuncInfo.CreateRegs(PHIOp);
12632 }
12633 }
12634
12635 // Remember that this register needs to added to the machine PHI node as
12636 // the input for this MBB.
12637 SmallVector<EVT, 4> ValueVTs;
12638 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12639 for (EVT VT : ValueVTs) {
12640 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12641 for (unsigned i = 0; i != NumRegisters; ++i)
12642 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12643 Reg += NumRegisters;
12644 }
12645 }
12646 }
12647
12648 ConstantsOut.clear();
12649}
12650
12651MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12653 if (++I == FuncInfo.MF->end())
12654 return nullptr;
12655 return &*I;
12656}
12657
12658/// During lowering new call nodes can be created (such as memset, etc.).
12659/// Those will become new roots of the current DAG, but complications arise
12660/// when they are tail calls. In such cases, the call lowering will update
12661/// the root, but the builder still needs to know that a tail call has been
12662/// lowered in order to avoid generating an additional return.
12663void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12664 // If the node is null, we do have a tail call.
12665 if (MaybeTC.getNode() != nullptr)
12666 DAG.setRoot(MaybeTC);
12667 else
12668 HasTailCall = true;
12669}
12670
12671void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12672 MachineBasicBlock *SwitchMBB,
12673 MachineBasicBlock *DefaultMBB) {
12674 MachineFunction *CurMF = FuncInfo.MF;
12675 MachineBasicBlock *NextMBB = nullptr;
12677 if (++BBI != FuncInfo.MF->end())
12678 NextMBB = &*BBI;
12679
12680 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12681
12682 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12683
12684 if (Size == 2 && W.MBB == SwitchMBB) {
12685 // If any two of the cases has the same destination, and if one value
12686 // is the same as the other, but has one bit unset that the other has set,
12687 // use bit manipulation to do two compares at once. For example:
12688 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12689 // TODO: This could be extended to merge any 2 cases in switches with 3
12690 // cases.
12691 // TODO: Handle cases where W.CaseBB != SwitchBB.
12692 CaseCluster &Small = *W.FirstCluster;
12693 CaseCluster &Big = *W.LastCluster;
12694
12695 if (Small.Low == Small.High && Big.Low == Big.High &&
12696 Small.MBB == Big.MBB) {
12697 const APInt &SmallValue = Small.Low->getValue();
12698 const APInt &BigValue = Big.Low->getValue();
12699
12700 // Check that there is only one bit different.
12701 APInt CommonBit = BigValue ^ SmallValue;
12702 if (CommonBit.isPowerOf2()) {
12703 SDValue CondLHS = getValue(Cond);
12704 EVT VT = CondLHS.getValueType();
12705 SDLoc DL = getCurSDLoc();
12706
12707 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12708 DAG.getConstant(CommonBit, DL, VT));
12709 SDValue Cond = DAG.getSetCC(
12710 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12711 ISD::SETEQ);
12712
12713 // Update successor info.
12714 // Both Small and Big will jump to Small.BB, so we sum up the
12715 // probabilities.
12716 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12717 if (BPI)
12718 addSuccessorWithProb(
12719 SwitchMBB, DefaultMBB,
12720 // The default destination is the first successor in IR.
12721 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12722 else
12723 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12724
12725 // Insert the true branch.
12726 SDValue BrCond =
12727 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12728 DAG.getBasicBlock(Small.MBB));
12729 // Insert the false branch.
12730 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12731 DAG.getBasicBlock(DefaultMBB));
12732
12733 DAG.setRoot(BrCond);
12734 return;
12735 }
12736 }
12737 }
12738
12739 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12740 // Here, we order cases by probability so the most likely case will be
12741 // checked first. However, two clusters can have the same probability in
12742 // which case their relative ordering is non-deterministic. So we use Low
12743 // as a tie-breaker as clusters are guaranteed to never overlap.
12744 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12745 [](const CaseCluster &a, const CaseCluster &b) {
12746 return a.Prob != b.Prob ?
12747 a.Prob > b.Prob :
12748 a.Low->getValue().slt(b.Low->getValue());
12749 });
12750
12751 // Rearrange the case blocks so that the last one falls through if possible
12752 // without changing the order of probabilities.
12753 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12754 --I;
12755 if (I->Prob > W.LastCluster->Prob)
12756 break;
12757 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12758 std::swap(*I, *W.LastCluster);
12759 break;
12760 }
12761 }
12762 }
12763
12764 // Compute total probability.
12765 BranchProbability DefaultProb = W.DefaultProb;
12766 BranchProbability UnhandledProbs = DefaultProb;
12767 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12768 UnhandledProbs += I->Prob;
12769
12770 MachineBasicBlock *CurMBB = W.MBB;
12771 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12772 bool FallthroughUnreachable = false;
12773 MachineBasicBlock *Fallthrough;
12774 if (I == W.LastCluster) {
12775 // For the last cluster, fall through to the default destination.
12776 Fallthrough = DefaultMBB;
12777 FallthroughUnreachable =
12779 } else {
12780 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12781 CurMF->insert(BBI, Fallthrough);
12782 // Put Cond in a virtual register to make it available from the new blocks.
12784 }
12785 UnhandledProbs -= I->Prob;
12786
12787 switch (I->Kind) {
12788 case CC_JumpTable: {
12789 // FIXME: Optimize away range check based on pivot comparisons.
12790 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12791 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12792
12793 // The jump block hasn't been inserted yet; insert it here.
12794 MachineBasicBlock *JumpMBB = JT->MBB;
12795 CurMF->insert(BBI, JumpMBB);
12796
12797 auto JumpProb = I->Prob;
12798 auto FallthroughProb = UnhandledProbs;
12799
12800 // If the default statement is a target of the jump table, we evenly
12801 // distribute the default probability to successors of CurMBB. Also
12802 // update the probability on the edge from JumpMBB to Fallthrough.
12803 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12804 SE = JumpMBB->succ_end();
12805 SI != SE; ++SI) {
12806 if (*SI == DefaultMBB) {
12807 JumpProb += DefaultProb / 2;
12808 FallthroughProb -= DefaultProb / 2;
12809 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12810 JumpMBB->normalizeSuccProbs();
12811 break;
12812 }
12813 }
12814
12815 // If the default clause is unreachable, propagate that knowledge into
12816 // JTH->FallthroughUnreachable which will use it to suppress the range
12817 // check.
12818 //
12819 // However, don't do this if we're doing branch target enforcement
12820 // (e.g. Arm BTI, or the cf-protection-branch module flag used by
12821 // RISC-V Zicfilp and X86 IBT), because a table branch _without_ a
12822 // range check can be a tempting JOP gadget - out-of-bounds inputs
12823 // that are impossible in correct execution become possible again if
12824 // an attacker can influence the control flow. So if an attacker
12825 // doesn't already have a branch target enforcement bypass available,
12826 // we don't want them to be able to get one out of this table branch.
12827 if (FallthroughUnreachable) {
12828 Function &CurFunc = CurMF->getFunction();
12829 bool HasCFBranch = false;
12830 if (auto *CFBranch = mdconst::extract_or_null<ConstantInt>(
12831 CurFunc.getParent()->getModuleFlag("cf-protection-branch")))
12832 HasCFBranch = !CFBranch->isZero();
12833 if (!HasCFBranch &&
12834 !CurFunc.hasFnAttribute("branch-target-enforcement"))
12835 JTH->FallthroughUnreachable = true;
12836 }
12837
12838 if (!JTH->FallthroughUnreachable)
12839 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12840 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12841 CurMBB->normalizeSuccProbs();
12842
12843 // The jump table header will be inserted in our current block, do the
12844 // range check, and fall through to our fallthrough block.
12845 JTH->HeaderBB = CurMBB;
12846 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12847
12848 // If we're in the right place, emit the jump table header right now.
12849 if (CurMBB == SwitchMBB) {
12850 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12851 JTH->Emitted = true;
12852 }
12853 break;
12854 }
12855 case CC_BitTests: {
12856 // FIXME: Optimize away range check based on pivot comparisons.
12857 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12858
12859 // The bit test blocks haven't been inserted yet; insert them here.
12860 for (BitTestCase &BTC : BTB->Cases)
12861 CurMF->insert(BBI, BTC.ThisBB);
12862
12863 // Fill in fields of the BitTestBlock.
12864 BTB->Parent = CurMBB;
12865 BTB->Default = Fallthrough;
12866
12867 BTB->DefaultProb = UnhandledProbs;
12868 // If the cases in bit test don't form a contiguous range, we evenly
12869 // distribute the probability on the edge to Fallthrough to two
12870 // successors of CurMBB.
12871 if (!BTB->ContiguousRange) {
12872 BTB->Prob += DefaultProb / 2;
12873 BTB->DefaultProb -= DefaultProb / 2;
12874 }
12875
12876 if (FallthroughUnreachable)
12877 BTB->FallthroughUnreachable = true;
12878
12879 // If we're in the right place, emit the bit test header right now.
12880 if (CurMBB == SwitchMBB) {
12881 visitBitTestHeader(*BTB, SwitchMBB);
12882 BTB->Emitted = true;
12883 }
12884 break;
12885 }
12886 case CC_Range: {
12887 const Value *RHS, *LHS, *MHS;
12889 if (I->Low == I->High) {
12890 // Check Cond == I->Low.
12891 CC = ISD::SETEQ;
12892 LHS = Cond;
12893 RHS=I->Low;
12894 MHS = nullptr;
12895 } else {
12896 // Check I->Low <= Cond <= I->High.
12897 CC = ISD::SETLE;
12898 LHS = I->Low;
12899 MHS = Cond;
12900 RHS = I->High;
12901 }
12902
12903 // If Fallthrough is unreachable, fold away the comparison.
12904 if (FallthroughUnreachable)
12905 CC = ISD::SETTRUE;
12906
12907 // The false probability is the sum of all unhandled cases.
12908 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12909 getCurSDLoc(), I->Prob, UnhandledProbs);
12910
12911 if (CurMBB == SwitchMBB)
12912 visitSwitchCase(CB, SwitchMBB);
12913 else
12914 SL->SwitchCases.push_back(CB);
12915
12916 break;
12917 }
12918 }
12919 CurMBB = Fallthrough;
12920 }
12921}
12922
12923void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12924 const SwitchWorkListItem &W,
12925 Value *Cond,
12926 MachineBasicBlock *SwitchMBB) {
12927 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12928 "Clusters not sorted?");
12929 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12930
12931 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12932 SL->computeSplitWorkItemInfo(W);
12933
12934 // Use the first element on the right as pivot since we will make less-than
12935 // comparisons against it.
12936 CaseClusterIt PivotCluster = FirstRight;
12937 assert(PivotCluster > W.FirstCluster);
12938 assert(PivotCluster <= W.LastCluster);
12939
12940 CaseClusterIt FirstLeft = W.FirstCluster;
12941 CaseClusterIt LastRight = W.LastCluster;
12942
12943 const ConstantInt *Pivot = PivotCluster->Low;
12944
12945 // New blocks will be inserted immediately after the current one.
12947 ++BBI;
12948
12949 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12950 // we can branch to its destination directly if it's squeezed exactly in
12951 // between the known lower bound and Pivot - 1.
12952 MachineBasicBlock *LeftMBB;
12953 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12954 FirstLeft->Low == W.GE &&
12955 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12956 LeftMBB = FirstLeft->MBB;
12957 } else {
12958 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12959 FuncInfo.MF->insert(BBI, LeftMBB);
12960 WorkList.push_back(
12961 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12962 // Put Cond in a virtual register to make it available from the new blocks.
12964 }
12965
12966 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12967 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12968 // directly if RHS.High equals the current upper bound.
12969 MachineBasicBlock *RightMBB;
12970 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12971 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12972 RightMBB = FirstRight->MBB;
12973 } else {
12974 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12975 FuncInfo.MF->insert(BBI, RightMBB);
12976 WorkList.push_back(
12977 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12978 // Put Cond in a virtual register to make it available from the new blocks.
12980 }
12981
12982 // Create the CaseBlock record that will be used to lower the branch.
12983 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12984 getCurSDLoc(), LeftProb, RightProb);
12985
12986 if (W.MBB == SwitchMBB)
12987 visitSwitchCase(CB, SwitchMBB);
12988 else
12989 SL->SwitchCases.push_back(CB);
12990}
12991
12992// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12993// from the swith statement.
12995 BranchProbability PeeledCaseProb) {
12996 if (PeeledCaseProb == BranchProbability::getOne())
12998 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12999
13000 uint32_t Numerator = CaseProb.getNumerator();
13001 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
13002 return BranchProbability(Numerator, std::max(Numerator, Denominator));
13003}
13004
13005// Try to peel the top probability case if it exceeds the threshold.
13006// Return current MachineBasicBlock for the switch statement if the peeling
13007// does not occur.
13008// If the peeling is performed, return the newly created MachineBasicBlock
13009// for the peeled switch statement. Also update Clusters to remove the peeled
13010// case. PeeledCaseProb is the BranchProbability for the peeled case.
13011MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
13012 const SwitchInst &SI, CaseClusterVector &Clusters,
13013 BranchProbability &PeeledCaseProb) {
13014 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13015 // Don't perform if there is only one cluster or optimizing for size.
13016 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
13017 TM.getOptLevel() == CodeGenOptLevel::None ||
13018 SwitchMBB->getParent()->getFunction().hasMinSize())
13019 return SwitchMBB;
13020
13021 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
13022 unsigned PeeledCaseIndex = 0;
13023 bool SwitchPeeled = false;
13024 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
13025 CaseCluster &CC = Clusters[Index];
13026 if (CC.Prob < TopCaseProb)
13027 continue;
13028 TopCaseProb = CC.Prob;
13029 PeeledCaseIndex = Index;
13030 SwitchPeeled = true;
13031 }
13032 if (!SwitchPeeled)
13033 return SwitchMBB;
13034
13035 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
13036 << TopCaseProb << "\n");
13037
13038 // Record the MBB for the peeled switch statement.
13039 MachineFunction::iterator BBI(SwitchMBB);
13040 ++BBI;
13041 MachineBasicBlock *PeeledSwitchMBB =
13042 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
13043 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
13044
13045 ExportFromCurrentBlock(SI.getCondition());
13046 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
13047 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
13048 nullptr, nullptr, TopCaseProb.getCompl()};
13049 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
13050
13051 Clusters.erase(PeeledCaseIt);
13052 for (CaseCluster &CC : Clusters) {
13053 LLVM_DEBUG(
13054 dbgs() << "Scale the probablity for one cluster, before scaling: "
13055 << CC.Prob << "\n");
13056 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
13057 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
13058 }
13059 PeeledCaseProb = TopCaseProb;
13060 return PeeledSwitchMBB;
13061}
13062
13063void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
13064 // Extract cases from the switch.
13065 BranchProbabilityInfo *BPI = FuncInfo.BPI;
13066 CaseClusterVector Clusters;
13067 Clusters.reserve(SI.getNumCases());
13068 for (auto I : SI.cases()) {
13069 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
13070 const ConstantInt *CaseVal = I.getCaseValue();
13071 BranchProbability Prob =
13072 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
13073 : BranchProbability(1, SI.getNumCases() + 1);
13074 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
13075 }
13076
13077 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
13078
13079 // Cluster adjacent cases with the same destination. We do this at all
13080 // optimization levels because it's cheap to do and will make codegen faster
13081 // if there are many clusters.
13082 sortAndRangeify(Clusters);
13083
13084 // The branch probablity of the peeled case.
13085 BranchProbability PeeledCaseProb = BranchProbability::getZero();
13086 MachineBasicBlock *PeeledSwitchMBB =
13087 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
13088
13089 // If there is only the default destination, jump there directly.
13090 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13091 if (Clusters.empty()) {
13092 assert(PeeledSwitchMBB == SwitchMBB);
13093 SwitchMBB->addSuccessor(DefaultMBB);
13094 if (DefaultMBB != NextBlock(SwitchMBB)) {
13095 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
13096 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
13097 }
13098 return;
13099 }
13100
13101 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
13102 DAG.getBFI());
13103 SL->findBitTestClusters(Clusters, &SI);
13104
13105 LLVM_DEBUG({
13106 dbgs() << "Case clusters: ";
13107 for (const CaseCluster &C : Clusters) {
13108 if (C.Kind == CC_JumpTable)
13109 dbgs() << "JT:";
13110 if (C.Kind == CC_BitTests)
13111 dbgs() << "BT:";
13112
13113 C.Low->getValue().print(dbgs(), true);
13114 if (C.Low != C.High) {
13115 dbgs() << '-';
13116 C.High->getValue().print(dbgs(), true);
13117 }
13118 dbgs() << ' ';
13119 }
13120 dbgs() << '\n';
13121 });
13122
13123 assert(!Clusters.empty());
13124 SwitchWorkList WorkList;
13125 CaseClusterIt First = Clusters.begin();
13126 CaseClusterIt Last = Clusters.end() - 1;
13127 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
13128 // Scale the branchprobability for DefaultMBB if the peel occurs and
13129 // DefaultMBB is not replaced.
13130 if (PeeledCaseProb != BranchProbability::getZero() &&
13131 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
13132 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
13133 WorkList.push_back(
13134 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
13135
13136 while (!WorkList.empty()) {
13137 SwitchWorkListItem W = WorkList.pop_back_val();
13138 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
13139
13140 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
13141 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
13142 // For optimized builds, lower large range as a balanced binary tree.
13143 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
13144 continue;
13145 }
13146
13147 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
13148 }
13149}
13150
13151void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
13152 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13153 auto DL = getCurSDLoc();
13154 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13155 setValue(&I, DAG.getStepVector(DL, ResultVT));
13156}
13157
13158void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
13159 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13160 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13161
13162 SDLoc DL = getCurSDLoc();
13163 SDValue V = getValue(I.getOperand(0));
13164 assert(VT == V.getValueType() && "Malformed vector.reverse!");
13165
13166 if (VT.isScalableVector()) {
13167 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
13168 return;
13169 }
13170
13171 // Use VECTOR_SHUFFLE for the fixed-length vector
13172 // to maintain existing behavior.
13173 SmallVector<int, 8> Mask;
13174 unsigned NumElts = VT.getVectorMinNumElements();
13175 for (unsigned i = 0; i != NumElts; ++i)
13176 Mask.push_back(NumElts - 1 - i);
13177
13178 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
13179}
13180
13181void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
13182 unsigned Factor) {
13183 auto DL = getCurSDLoc();
13184 SDValue InVec = getValue(I.getOperand(0));
13185
13186 SmallVector<EVT, 4> ValueVTs;
13187 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13188 ValueVTs);
13189
13190 EVT OutVT = ValueVTs[0];
13191 unsigned OutNumElts = OutVT.getVectorMinNumElements();
13192
13193 SmallVector<SDValue, 4> SubVecs(Factor);
13194 for (unsigned i = 0; i != Factor; ++i) {
13195 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13196 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
13197 DAG.getVectorIdxConstant(OutNumElts * i, DL));
13198 }
13199
13200 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
13201 DAG.getVTList(ValueVTs), SubVecs);
13202 setValue(&I, Res);
13203}
13204
13205void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13206 unsigned Factor) {
13207 auto DL = getCurSDLoc();
13208 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13209 EVT InVT = getValue(I.getOperand(0)).getValueType();
13210 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13211
13212 SmallVector<SDValue, 8> InVecs(Factor);
13213 for (unsigned i = 0; i < Factor; ++i) {
13214 InVecs[i] = getValue(I.getOperand(i));
13215 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13216 "Expected VTs to be the same");
13217 }
13218
13219 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13220 SDValue Res =
13221 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13222
13224 for (unsigned i = 0; i < Factor; ++i)
13225 Results[i] = Res.getValue(i);
13226
13227 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13228 setValue(&I, Res);
13229}
13230
13231void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13232 SmallVector<EVT, 4> ValueVTs;
13233 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13234 ValueVTs);
13235 unsigned NumValues = ValueVTs.size();
13236 if (NumValues == 0) return;
13237
13239 SDValue Op = getValue(I.getOperand(0));
13240
13241 for (unsigned i = 0; i != NumValues; ++i)
13242 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13243 SDValue(Op.getNode(), Op.getResNo() + i));
13244
13246 DAG.getVTList(ValueVTs), Values));
13247}
13248
13249void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13251 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13252
13253 SDLoc DL = getCurSDLoc();
13254 SDValue V1 = getValue(I.getOperand(0));
13255 SDValue V2 = getValue(I.getOperand(1));
13256 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13257
13258 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13259 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13260 SDValue Offset = DAG.getZExtOrTrunc(
13261 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13262 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13264 DL, VT, V1, V2, Offset));
13265 return;
13266 }
13267 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13268
13269 unsigned NumElts = VT.getVectorNumElements();
13270
13271 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13272
13273 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13274 SmallVector<int, 8> Mask;
13275 for (unsigned i = 0; i < NumElts; ++i)
13276 Mask.push_back(Idx + i);
13277 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13278}
13279
13280// Consider the following MIR after SelectionDAG, which produces output in
13281// phyregs in the first case or virtregs in the second case.
13282//
13283// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13284// %5:gr32 = COPY $ebx
13285// %6:gr32 = COPY $edx
13286// %1:gr32 = COPY %6:gr32
13287// %0:gr32 = COPY %5:gr32
13288//
13289// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13290// %1:gr32 = COPY %6:gr32
13291// %0:gr32 = COPY %5:gr32
13292//
13293// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13294// Given %1, we'd like to return $edx in the first case and %6 in the second.
13295//
13296// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13297// to a single virtreg (such as %0). The remaining outputs monotonically
13298// increase in virtreg number from there. If a callbr has no outputs, then it
13299// should not have a corresponding callbr landingpad; in fact, the callbr
13300// landingpad would not even be able to refer to such a callbr.
13302 MachineInstr *MI = MRI.def_begin(Reg)->getParent();
13303 // There is definitely at least one copy.
13304 assert(MI->getOpcode() == TargetOpcode::COPY &&
13305 "start of copy chain MUST be COPY");
13306 Reg = MI->getOperand(1).getReg();
13307
13308 // If the copied register in the first copy must be virtual.
13309 assert(Reg.isVirtual() && "expected COPY of virtual register");
13310 MI = MRI.def_begin(Reg)->getParent();
13311
13312 // There may be an optional second copy.
13313 if (MI->getOpcode() == TargetOpcode::COPY) {
13314 assert(Reg.isVirtual() && "expected COPY of virtual register");
13315 Reg = MI->getOperand(1).getReg();
13316 assert(Reg.isPhysical() && "expected COPY of physical register");
13317 } else {
13318 // The start of the chain must be an INLINEASM_BR.
13319 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13320 "end of copy chain MUST be INLINEASM_BR");
13321 }
13322
13323 return Reg;
13324}
13325
13326// We must do this walk rather than the simpler
13327// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13328// otherwise we will end up with copies of virtregs only valid along direct
13329// edges.
13330void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13331 SmallVector<EVT, 8> ResultVTs;
13332 SmallVector<SDValue, 8> ResultValues;
13333 const auto *CBR =
13334 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13335
13336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13337 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13338 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13339
13340 Register InitialDef = FuncInfo.ValueMap[CBR];
13341 SDValue Chain = DAG.getRoot();
13342
13343 // Re-parse the asm constraints string.
13344 TargetLowering::AsmOperandInfoVector TargetConstraints =
13345 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
13346 for (auto &T : TargetConstraints) {
13347 SDISelAsmOperandInfo OpInfo(T);
13348 if (OpInfo.Type != InlineAsm::isOutput)
13349 continue;
13350
13351 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13352 // individual constraint.
13353 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
13354
13355 switch (OpInfo.ConstraintType) {
13358 // Fill in OpInfo.AssignedRegs.Regs.
13359 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
13360
13361 // getRegistersForValue may produce 1 to many registers based on whether
13362 // the OpInfo.ConstraintVT is legal on the target or not.
13363 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13364 Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
13365 if (OriginalDef.isPhysical())
13366 FuncInfo.MBB->addLiveIn(OriginalDef);
13367 // Update the assigned registers to use the original defs.
13368 Reg = OriginalDef;
13369 }
13370
13371 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13372 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
13373 ResultValues.push_back(V);
13374 ResultVTs.push_back(OpInfo.ConstraintVT);
13375 break;
13376 }
13378 SDValue Flag;
13380 OpInfo, DAG);
13381 ++InitialDef;
13382 ResultValues.push_back(V);
13383 ResultVTs.push_back(OpInfo.ConstraintVT);
13384 break;
13385 }
13386 default:
13387 break;
13388 }
13389 }
13391 DAG.getVTList(ResultVTs), ResultValues);
13392 setValue(&I, V);
13393}
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!")
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
const HexagonInstrInfo * TII
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
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static const Function * getCalledFunction(const Value *V)
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)
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
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 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 getUnderlyingArgRegs(SmallVectorImpl< std::pair< Register, TypeSize > > &Regs, const SDValue &N)
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 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 Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg)
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 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:305
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:6393
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,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
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:171
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:237
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:64
bool isBigEndian() const
Definition DataLayout.h:218
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:843
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:414
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.
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:686
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:411
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:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
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
Representation of each machine instruction.
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:184
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:358
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:887
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:112
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)
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().
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
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 ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
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:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
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:296
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:303
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.
@ ATOMIC_LOAD_FMINIMUMNUM
@ 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.
@ ATOMIC_LOAD_USUB_COND
@ 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...
@ ATOMIC_LOAD_USUB_SAT
@ 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.
@ ATOMIC_LOAD_FMAXIMUM
@ 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
@ ATOMIC_LOAD_FMINIMUM
@ 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.
@ ATOMIC_LOAD_FMAXIMUMNUM
@ 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
@ ATOMIC_LOAD_UDEC_WRAP
@ 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
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ 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
@ ATOMIC_LOAD_UINC_WRAP
@ 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....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
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:694
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
@ 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:642
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
Definition LoopInfo.cpp:61
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:2570
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:2224
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
@ 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 const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
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 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:2353
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...
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
@ 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:656
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:623
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:2208
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:128
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 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)