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/IntrinsicsWebAssembly.h"
82#include "llvm/IR/LLVMContext.h"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Operator.h"
88#include "llvm/IR/Statepoint.h"
89#include "llvm/IR/Type.h"
90#include "llvm/IR/User.h"
91#include "llvm/IR/Value.h"
92#include "llvm/MC/MCAsmInfo.h"
93#include "llvm/MC/MCContext.h"
98#include "llvm/Support/Debug.h"
106#include <cstddef>
107#include <limits>
108#include <optional>
109#include <tuple>
110
111using namespace llvm;
112using namespace PatternMatch;
113using namespace SwitchCG;
114
115#define DEBUG_TYPE "isel"
116
117/// LimitFloatPrecision - Generate low-precision inline sequences for
118/// some float libcalls (6, 8 or 12 bits).
119static unsigned LimitFloatPrecision;
120
121static cl::opt<bool>
122 InsertAssertAlign("insert-assert-align", cl::init(true),
123 cl::desc("Insert the experimental `assertalign` node."),
125
127 LimitFPPrecision("limit-float-precision",
128 cl::desc("Generate low-precision inline sequences "
129 "for some float libcalls"),
131 cl::init(0));
132
134 "switch-peel-threshold", cl::Hidden, cl::init(66),
135 cl::desc("Set the case probability threshold for peeling the case from a "
136 "switch statement. A value greater than 100 will void this "
137 "optimization"));
138
139// Limit the width of DAG chains. This is important in general to prevent
140// DAG-based analysis from blowing up. For example, alias analysis and
141// load clustering may not complete in reasonable time. It is difficult to
142// recognize and avoid this situation within each individual analysis, and
143// future analyses are likely to have the same behavior. Limiting DAG width is
144// the safe approach and will be especially important with global DAGs.
145//
146// MaxParallelChains default is arbitrarily high to avoid affecting
147// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148// sequence over this should have been converted to llvm.memcpy by the
149// frontend. It is easy to induce this behavior with .ll code such as:
150// %buffer = alloca [4096 x i8]
151// %data = load [4096 x i8]* %argPtr
152// store [4096 x i8] %data, [4096 x i8]* %buffer
153static const unsigned MaxParallelChains = 64;
154
156 const SDValue *Parts, unsigned NumParts,
157 MVT PartVT, EVT ValueVT, const Value *V,
158 SDValue InChain,
159 std::optional<CallingConv::ID> CC);
160
161/// getCopyFromParts - Create a value that contains the specified legal parts
162/// combined into the value they represent. If the parts combine to a type
163/// larger than ValueVT then AssertOp can be used to specify whether the extra
164/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
165/// (ISD::AssertSext).
166static SDValue
167getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
168 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
169 SDValue InChain,
170 std::optional<CallingConv::ID> CC = std::nullopt,
171 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
172 // Let the target assemble the parts if it wants to
173 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
174 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
175 PartVT, ValueVT, CC))
176 return Val;
177
178 if (ValueVT.isVector())
179 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
180 InChain, CC);
181
182 assert(NumParts > 0 && "No parts to assemble!");
183 SDValue Val = Parts[0];
184
185 if (NumParts > 1) {
186 // Assemble the value from multiple parts.
187 if (ValueVT.isInteger()) {
188 unsigned PartBits = PartVT.getSizeInBits();
189 unsigned ValueBits = ValueVT.getSizeInBits();
190
191 // Assemble the power of 2 part.
192 unsigned RoundParts = llvm::bit_floor(NumParts);
193 unsigned RoundBits = PartBits * RoundParts;
194 EVT RoundVT = RoundBits == ValueBits ?
195 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
196 SDValue Lo, Hi;
197
198 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
199
200 if (RoundParts > 2) {
201 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
202 InChain);
203 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
204 PartVT, HalfVT, V, InChain);
205 } else {
206 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
207 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
208 }
209
210 if (DAG.getDataLayout().isBigEndian())
211 std::swap(Lo, Hi);
212
213 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
214
215 if (RoundParts < NumParts) {
216 // Assemble the trailing non-power-of-2 part.
217 unsigned OddParts = NumParts - RoundParts;
218 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
219 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
220 OddVT, V, InChain, CC);
221
222 // Combine the round and odd parts.
223 Lo = Val;
224 if (DAG.getDataLayout().isBigEndian())
225 std::swap(Lo, Hi);
226 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
227 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
228 Hi = DAG.getNode(
229 ISD::SHL, DL, TotalVT, Hi,
230 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
231 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233 }
234 } else if (PartVT.isFloatingPoint()) {
235 // FP split into multiple FP parts (for ppcf128)
236 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237 "Unexpected split");
238 SDValue Lo, Hi;
239 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242 std::swap(Lo, Hi);
243 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244 } else {
245 // FP split into integer parts (soft fp)
246 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247 !PartVT.isVector() && "Unexpected split");
248 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
250 InChain, CC);
251 }
252 }
253
254 // There is now one part, held in Val. Correct it to match ValueVT.
255 // PartEVT is the type of the register class that holds the value.
256 // ValueVT is the type of the inline asm operation.
257 EVT PartEVT = Val.getValueType();
258
259 if (PartEVT == ValueVT)
260 return Val;
261
262 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
263 ValueVT.bitsLT(PartEVT)) {
264 // For an FP value in an integer part, we need to truncate to the right
265 // width first.
266 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
267 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
268 }
269
270 // Handle types that have the same size.
271 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
272 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
273
274 // Handle types with different sizes.
275 if (PartEVT.isInteger() && ValueVT.isInteger()) {
276 if (ValueVT.bitsLT(PartEVT)) {
277 // For a truncate, see if we have any information to
278 // indicate whether the truncated bits will always be
279 // zero or sign-extension.
280 if (AssertOp)
281 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
282 DAG.getValueType(ValueVT));
283 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
284 }
285 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
286 }
287
288 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
289 // FP_ROUND's are always exact here.
290 if (ValueVT.bitsLT(Val.getValueType())) {
291
292 SDValue NoChange =
294
295 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
296 llvm::Attribute::StrictFP)) {
297 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
298 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
299 NoChange);
300 }
301
302 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
303 }
304
305 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
306 }
307
308 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
309 // then truncating.
310 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
311 ValueVT.bitsLT(PartEVT)) {
312 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
313 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
314 }
315
316 report_fatal_error("Unknown mismatch in getCopyFromParts!");
317}
318
320 const Twine &ErrMsg) {
322 if (!I)
323 return Ctx.emitError(ErrMsg);
324
325 if (const CallInst *CI = dyn_cast<CallInst>(I))
326 if (CI->isInlineAsm()) {
327 return Ctx.diagnose(DiagnosticInfoInlineAsm(
328 *CI, ErrMsg + ", possible invalid constraint for vector type"));
329 }
330
331 return Ctx.emitError(I, ErrMsg);
332}
333
334/// getCopyFromPartsVector - Create a value that contains the specified legal
335/// parts combined into the value they represent. If the parts combine to a
336/// type larger than ValueVT then AssertOp can be used to specify whether the
337/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
338/// ValueVT (ISD::AssertSext).
340 const SDValue *Parts, unsigned NumParts,
341 MVT PartVT, EVT ValueVT, const Value *V,
342 SDValue InChain,
343 std::optional<CallingConv::ID> CallConv) {
344 assert(ValueVT.isVector() && "Not a vector value");
345 assert(NumParts > 0 && "No parts to assemble!");
346 const bool IsABIRegCopy = CallConv.has_value();
347
348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
349 SDValue Val = Parts[0];
350
351 // Handle a multi-element vector.
352 if (NumParts > 1) {
353 EVT IntermediateVT;
354 MVT RegisterVT;
355 unsigned NumIntermediates;
356 unsigned NumRegs;
357
358 if (IsABIRegCopy) {
360 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
361 NumIntermediates, RegisterVT);
362 } else {
363 NumRegs =
364 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
365 NumIntermediates, RegisterVT);
366 }
367
368 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
369 NumParts = NumRegs; // Silence a compiler warning.
370 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
371 assert(RegisterVT.getSizeInBits() ==
372 Parts[0].getSimpleValueType().getSizeInBits() &&
373 "Part type sizes don't match!");
374
375 // Assemble the parts into intermediate operands.
376 SmallVector<SDValue, 8> Ops(NumIntermediates);
377 if (NumIntermediates == NumParts) {
378 // If the register was not expanded, truncate or copy the value,
379 // as appropriate.
380 for (unsigned i = 0; i != NumParts; ++i)
381 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
382 V, InChain, CallConv);
383 } else if (NumParts > 0) {
384 // If the intermediate type was expanded, build the intermediate
385 // operands from the parts.
386 assert(NumParts % NumIntermediates == 0 &&
387 "Must expand into a divisible number of parts!");
388 unsigned Factor = NumParts / NumIntermediates;
389 for (unsigned i = 0; i != NumIntermediates; ++i)
390 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
391 IntermediateVT, V, InChain, CallConv);
392 }
393
394 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
395 // intermediate operands.
396 EVT BuiltVectorTy =
397 IntermediateVT.isVector()
399 *DAG.getContext(), IntermediateVT.getScalarType(),
400 IntermediateVT.getVectorElementCount() * NumParts)
402 IntermediateVT.getScalarType(),
403 NumIntermediates);
404 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
406 DL, BuiltVectorTy, Ops);
407 }
408
409 // There is now one part, held in Val. Correct it to match ValueVT.
410 EVT PartEVT = Val.getValueType();
411
412 if (PartEVT == ValueVT)
413 return Val;
414
415 if (PartEVT.isVector()) {
416 // Vector/Vector bitcast.
417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419
420 // If the parts vector has more elements than the value vector, then we
421 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
422 // Extract the elements we want.
423 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
426 (PartEVT.getVectorElementCount().isScalable() ==
427 ValueVT.getVectorElementCount().isScalable()) &&
428 "Cannot narrow, it would be a lossy transformation");
429 PartEVT =
431 ValueVT.getVectorElementCount());
432 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
433 DAG.getVectorIdxConstant(0, DL));
434 if (PartEVT == ValueVT)
435 return Val;
436 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438
439 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
440 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
441 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
442 }
443
444 // Promoted vector extract
445 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
446 }
447
448 // Trivial bitcast if the types are the same size and the destination
449 // vector type is legal.
450 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
451 TLI.isTypeLegal(ValueVT))
452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453
454 if (ValueVT.getVectorNumElements() != 1) {
455 // Certain ABIs require that vectors are passed as integers. For vectors
456 // are the same size, this is an obvious bitcast.
457 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
458 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
459 } else if (ValueVT.bitsLT(PartEVT)) {
460 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462 // Drop the extra bits.
463 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
464 return DAG.getBitcast(ValueVT, Val);
465 }
466
468 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
469 return DAG.getUNDEF(ValueVT);
470 }
471
472 // Handle cases such as i8 -> <1 x i1>
473 EVT ValueSVT = ValueVT.getVectorElementType();
474 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
475 unsigned ValueSize = ValueSVT.getSizeInBits();
476 if (ValueSize == PartEVT.getSizeInBits()) {
477 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
478 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
479 // It's possible a scalar floating point type gets softened to integer and
480 // then promoted to a larger integer. If PartEVT is the larger integer
481 // we need to truncate it and then bitcast to the FP type.
482 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
483 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
484 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
485 Val = DAG.getBitcast(ValueSVT, Val);
486 } else {
487 Val = ValueVT.isFloatingPoint()
488 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490 }
491 }
492
493 return DAG.getBuildVector(ValueVT, DL, Val);
494}
495
496static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
497 SDValue Val, SDValue *Parts, unsigned NumParts,
498 MVT PartVT, const Value *V,
499 std::optional<CallingConv::ID> CallConv);
500
501/// getCopyToParts - Create a series of nodes that contain the specified value
502/// split into legal parts. If the parts contain more bits than Val, then, for
503/// integers, ExtendKind can be used to specify how to generate the extra bits.
504static void
506 unsigned NumParts, MVT PartVT, const Value *V,
507 std::optional<CallingConv::ID> CallConv = std::nullopt,
508 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
509 // Let the target split the parts if it wants to
510 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
511 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
512 CallConv))
513 return;
514 EVT ValueVT = Val.getValueType();
515
516 // Handle the vector case separately.
517 if (ValueVT.isVector())
518 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
519 CallConv);
520
521 unsigned OrigNumParts = NumParts;
523 "Copying to an illegal type!");
524
525 if (NumParts == 0)
526 return;
527
528 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
529 EVT PartEVT = PartVT;
530 if (PartEVT == ValueVT) {
531 assert(NumParts == 1 && "No-op copy with multiple parts!");
532 Parts[0] = Val;
533 return;
534 }
535
536 unsigned PartBits = PartVT.getSizeInBits();
537 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
538 // If the parts cover more bits than the value has, promote the value.
539 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
540 assert(NumParts == 1 && "Do not know what to promote to!");
541 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
542 } else {
543 if (ValueVT.isFloatingPoint()) {
544 // FP values need to be bitcast, then extended if they are being put
545 // into a larger container.
546 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
547 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
548 }
549 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
550 ValueVT.isInteger() &&
551 "Unknown mismatch!");
552 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
553 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
554 if (PartVT == MVT::x86mmx)
555 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
556 }
557 } else if (PartBits == ValueVT.getSizeInBits()) {
558 // Different types of the same size.
559 assert(NumParts == 1 && PartEVT != ValueVT);
560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
562 // If the parts cover less bits than value has, truncate the value.
563 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
564 ValueVT.isInteger() &&
565 "Unknown mismatch!");
566 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
567 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
568 if (PartVT == MVT::x86mmx)
569 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
570 }
571
572 // The value may have changed - recompute ValueVT.
573 ValueVT = Val.getValueType();
574 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
575 "Failed to tile the value with PartVT!");
576
577 if (NumParts == 1) {
578 if (PartEVT != ValueVT) {
580 "scalar-to-vector conversion failed");
581 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
582 }
583
584 Parts[0] = Val;
585 return;
586 }
587
588 // Expand the value into multiple parts.
589 if (NumParts & (NumParts - 1)) {
590 // The number of parts is not a power of 2. Split off and copy the tail.
591 assert(PartVT.isInteger() && ValueVT.isInteger() &&
592 "Do not know what to expand to!");
593 unsigned RoundParts = llvm::bit_floor(NumParts);
594 unsigned RoundBits = RoundParts * PartBits;
595 unsigned OddParts = NumParts - RoundParts;
596 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
597 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
598
599 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
600 CallConv);
601
602 if (DAG.getDataLayout().isBigEndian())
603 // The odd parts were reversed by getCopyToParts - unreverse them.
604 std::reverse(Parts + RoundParts, Parts + NumParts);
605
606 NumParts = RoundParts;
607 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
608 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
609 }
610
611 // The number of parts is a power of 2. Repeatedly bisect the value using
612 // EXTRACT_ELEMENT.
613 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
615 ValueVT.getSizeInBits()),
616 Val);
617
618 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
619 for (unsigned i = 0; i < NumParts; i += StepSize) {
620 unsigned ThisBits = StepSize * PartBits / 2;
621 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
622 SDValue &Part0 = Parts[i];
623 SDValue &Part1 = Parts[i+StepSize/2];
624
625 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
626 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
627 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
629
630 if (ThisBits == PartBits && ThisVT != PartVT) {
631 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
632 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
633 }
634 }
635 }
636
637 if (DAG.getDataLayout().isBigEndian())
638 std::reverse(Parts, Parts + OrigNumParts);
639}
640
642 const SDLoc &DL, EVT PartVT) {
643 if (!PartVT.isVector())
644 return SDValue();
645
646 EVT ValueVT = Val.getValueType();
647 EVT PartEVT = PartVT.getVectorElementType();
648 EVT ValueEVT = ValueVT.getVectorElementType();
649 ElementCount PartNumElts = PartVT.getVectorElementCount();
650 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
651
652 // We only support widening vectors with equivalent element types and
653 // fixed/scalable properties. If a target needs to widen a fixed-length type
654 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
655 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
656 PartNumElts.isScalable() != ValueNumElts.isScalable())
657 return SDValue();
658
659 // Have a try for bf16 because some targets share its ABI with fp16.
660 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
662 "Cannot widen to illegal type");
663 Val = DAG.getNode(
665 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
666 } else if (PartEVT != ValueEVT) {
667 return SDValue();
668 }
669
670 // Widening a scalable vector to another scalable vector is done by inserting
671 // the vector into a larger undef one.
672 if (PartNumElts.isScalable())
673 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
674 Val, DAG.getVectorIdxConstant(0, DL));
675
676 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
677 // undef elements.
679 DAG.ExtractVectorElements(Val, Ops);
680 SDValue EltUndef = DAG.getUNDEF(PartEVT);
681 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
682
683 // FIXME: Use CONCAT for 2x -> 4x.
684 return DAG.getBuildVector(PartVT, DL, Ops);
685}
686
687/// getCopyToPartsVector - Create a series of nodes that contain the specified
688/// value split into legal parts.
689static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
690 SDValue Val, SDValue *Parts, unsigned NumParts,
691 MVT PartVT, const Value *V,
692 std::optional<CallingConv::ID> CallConv) {
693 EVT ValueVT = Val.getValueType();
694 assert(ValueVT.isVector() && "Not a vector");
695 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
696 const bool IsABIRegCopy = CallConv.has_value();
697
698 if (NumParts == 1) {
699 EVT PartEVT = PartVT;
700 if (PartEVT == ValueVT) {
701 // Nothing to do.
702 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
703 // Bitconvert vector->vector case.
704 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
705 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
706 Val = Widened;
707 } else if (PartVT.isVector() &&
709 ValueVT.getVectorElementType()) &&
710 PartEVT.getVectorElementCount() ==
711 ValueVT.getVectorElementCount()) {
712
713 // Promoted vector extract
714 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
715 } else if (PartEVT.isVector() &&
716 PartEVT.getVectorElementType() !=
717 ValueVT.getVectorElementType() &&
718 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
720 // Combination of widening and promotion.
721 EVT WidenVT =
723 PartVT.getVectorElementCount());
724 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
725 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
726 } else {
727 // Don't extract an integer from a float vector. This can happen if the
728 // FP type gets softened to integer and then promoted. The promotion
729 // prevents it from being picked up by the earlier bitcast case.
730 if (ValueVT.getVectorElementCount().isScalar() &&
731 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
732 // If we reach this condition and PartVT is FP, this means that
733 // ValueVT is also FP and both have a different size, otherwise we
734 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
735 // would be invalid since that would mean the smaller FP type has to
736 // be extended to the larger one.
737 if (PartVT.isFloatingPoint()) {
738 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
739 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
740 } else
741 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
742 DAG.getVectorIdxConstant(0, DL));
743 } else {
744 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
745 assert(PartVT.getFixedSizeInBits() > ValueSize &&
746 "lossy conversion of vector to scalar type");
747 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
748 Val = DAG.getBitcast(IntermediateType, Val);
749 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
750 }
751 }
752
753 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
754 Parts[0] = Val;
755 return;
756 }
757
758 // Handle a multi-element vector.
759 EVT IntermediateVT;
760 MVT RegisterVT;
761 unsigned NumIntermediates;
762 unsigned NumRegs;
763 if (IsABIRegCopy) {
765 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
766 RegisterVT);
767 } else {
768 NumRegs =
769 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
770 NumIntermediates, RegisterVT);
771 }
772
773 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
774 NumParts = NumRegs; // Silence a compiler warning.
775 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
776
777 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
778 "Mixing scalable and fixed vectors when copying in parts");
779
780 std::optional<ElementCount> DestEltCnt;
781
782 if (IntermediateVT.isVector())
783 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
784 else
785 DestEltCnt = ElementCount::getFixed(NumIntermediates);
786
787 EVT BuiltVectorTy = EVT::getVectorVT(
788 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
789
790 if (ValueVT == BuiltVectorTy) {
791 // Nothing to do.
792 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
793 // Bitconvert vector->vector case.
794 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
795 } else {
796 if (BuiltVectorTy.getVectorElementType().bitsGT(
797 ValueVT.getVectorElementType())) {
798 // Integer promotion.
799 ValueVT = EVT::getVectorVT(*DAG.getContext(),
800 BuiltVectorTy.getVectorElementType(),
801 ValueVT.getVectorElementCount());
802 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
803 }
804
805 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
806 Val = Widened;
807 }
808 }
809
810 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
811
812 // Split the vector into intermediate operands.
813 SmallVector<SDValue, 8> Ops(NumIntermediates);
814 for (unsigned i = 0; i != NumIntermediates; ++i) {
815 if (IntermediateVT.isVector()) {
816 // This does something sensible for scalable vectors - see the
817 // definition of EXTRACT_SUBVECTOR for further details.
818 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
819 Ops[i] =
820 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
821 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
822 } else {
823 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
824 DAG.getVectorIdxConstant(i, DL));
825 }
826 }
827
828 // Split the intermediate operands into legal parts.
829 if (NumParts == NumIntermediates) {
830 // If the register was not expanded, promote or copy the value,
831 // as appropriate.
832 for (unsigned i = 0; i != NumParts; ++i)
833 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
834 } else if (NumParts > 0) {
835 // If the intermediate type was expanded, split each the value into
836 // legal parts.
837 assert(NumIntermediates != 0 && "division by zero");
838 assert(NumParts % NumIntermediates == 0 &&
839 "Must expand into a divisible number of parts!");
840 unsigned Factor = NumParts / NumIntermediates;
841 for (unsigned i = 0; i != NumIntermediates; ++i)
842 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
843 CallConv);
844 }
845}
846
847static void failForInvalidBundles(const CallBase &I, StringRef Name,
848 ArrayRef<uint32_t> AllowedBundles) {
849 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
850 ListSeparator LS;
851 std::string Error;
853 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
854 OperandBundleUse U = I.getOperandBundleAt(i);
855 if (!is_contained(AllowedBundles, U.getTagID()))
856 OS << LS << U.getTagName();
857 }
859 Twine("cannot lower ", Name)
860 .concat(Twine(" with arbitrary operand bundles: ", Error)));
861 }
862}
863
865 EVT valuevt, std::optional<CallingConv::ID> CC)
866 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
867 RegCount(1, regs.size()), CallConv(CC) {}
868
870 const DataLayout &DL, Register Reg, Type *Ty,
871 std::optional<CallingConv::ID> CC) {
872 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
873
874 CallConv = CC;
875
876 for (EVT ValueVT : ValueVTs) {
877 unsigned NumRegs =
879 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
880 : TLI.getNumRegisters(Context, ValueVT);
881 MVT RegisterVT =
883 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
884 : TLI.getRegisterType(Context, ValueVT);
885 for (unsigned i = 0; i != NumRegs; ++i)
886 Regs.push_back(Reg + i);
887 RegVTs.push_back(RegisterVT);
888 RegCount.push_back(NumRegs);
889 Reg = Reg.id() + NumRegs;
890 }
891}
892
894 FunctionLoweringInfo &FuncInfo,
895 const SDLoc &dl, SDValue &Chain,
896 SDValue *Glue, const Value *V) const {
897 // A Value with type {} or [0 x %t] needs no registers.
898 if (ValueVTs.empty())
899 return SDValue();
900
901 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
902
903 // Assemble the legal parts into the final values.
906 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
907 // Copy the legal parts from the registers.
908 EVT ValueVT = ValueVTs[Value];
909 unsigned NumRegs = RegCount[Value];
910 MVT RegisterVT = isABIMangled()
912 *DAG.getContext(), *CallConv, RegVTs[Value])
913 : RegVTs[Value];
914
915 Parts.resize(NumRegs);
916 for (unsigned i = 0; i != NumRegs; ++i) {
917 SDValue P;
918 if (!Glue) {
919 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
920 } else {
921 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
922 *Glue = P.getValue(2);
923 }
924
925 Chain = P.getValue(1);
926 Parts[i] = P;
927
928 // If the source register was virtual and if we know something about it,
929 // add an assert node.
930 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
931 continue;
932
934 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
935 if (!LOI)
936 continue;
937
938 unsigned RegSize = RegisterVT.getScalarSizeInBits();
939 unsigned NumSignBits = LOI->NumSignBits;
940 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
941
942 if (NumZeroBits == RegSize) {
943 // The current value is a zero.
944 // Explicitly express that as it would be easier for
945 // optimizations to kick in.
946 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
947 continue;
948 }
949
950 // FIXME: We capture more information than the dag can represent. For
951 // now, just use the tightest assertzext/assertsext possible.
952 bool isSExt;
953 EVT FromVT(MVT::Other);
954 if (NumZeroBits) {
955 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
956 isSExt = false;
957 } else if (NumSignBits > 1) {
958 FromVT =
959 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
960 isSExt = true;
961 } else {
962 continue;
963 }
964 // Add an assertion node.
965 assert(FromVT != MVT::Other);
966 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
967 RegisterVT, P, DAG.getValueType(FromVT));
968 }
969
970 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
971 RegisterVT, ValueVT, V, Chain, CallConv);
972 Part += NumRegs;
973 Parts.clear();
974 }
975
976 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
977}
978
980 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
981 const Value *V,
982 ISD::NodeType PreferredExtendType) const {
983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
984 ISD::NodeType ExtendKind = PreferredExtendType;
985
986 // Get the list of the values's legal parts.
987 unsigned NumRegs = Regs.size();
988 SmallVector<SDValue, 8> Parts(NumRegs);
989 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
990 unsigned NumParts = RegCount[Value];
991
992 MVT RegisterVT = isABIMangled()
994 *DAG.getContext(), *CallConv, RegVTs[Value])
995 : RegVTs[Value];
996
997 if (ExtendKind == ISD::ANY_EXTEND)
998 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
999 ExtendKind = ISD::ZERO_EXTEND;
1000
1001 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1002 NumParts, RegisterVT, V, CallConv, ExtendKind);
1003 Part += NumParts;
1004 }
1005
1006 // Copy the parts into the registers.
1007 SmallVector<SDValue, 8> Chains(NumRegs);
1008 for (unsigned i = 0; i != NumRegs; ++i) {
1009 SDValue Part;
1010 if (!Glue) {
1011 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1012 } else {
1013 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1014 *Glue = Part.getValue(1);
1015 }
1016
1017 Chains[i] = Part.getValue(0);
1018 }
1019
1020 if (NumRegs == 1 || Glue)
1021 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1022 // flagged to it. That is the CopyToReg nodes and the user are considered
1023 // a single scheduling unit. If we create a TokenFactor and return it as
1024 // chain, then the TokenFactor is both a predecessor (operand) of the
1025 // user as well as a successor (the TF operands are flagged to the user).
1026 // c1, f1 = CopyToReg
1027 // c2, f2 = CopyToReg
1028 // c3 = TokenFactor c1, c2
1029 // ...
1030 // = op c3, ..., f2
1031 Chain = Chains[NumRegs-1];
1032 else
1033 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1034}
1035
1037 unsigned MatchingIdx, const SDLoc &dl,
1038 SelectionDAG &DAG,
1039 std::vector<SDValue> &Ops) const {
1040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1041
1042 InlineAsm::Flag Flag(Code, Regs.size());
1043 if (HasMatching)
1044 Flag.setMatchingOp(MatchingIdx);
1045 else if (!Regs.empty() && Regs.front().isVirtual()) {
1046 // Put the register class of the virtual registers in the flag word. That
1047 // way, later passes can recompute register class constraints for inline
1048 // assembly as well as normal instructions.
1049 // Don't do this for tied operands that can use the regclass information
1050 // from the def.
1052 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1053 Flag.setRegClass(RC->getID());
1054 }
1055
1056 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1057 Ops.push_back(Res);
1058
1059 if (Code == InlineAsm::Kind::Clobber) {
1060 // Clobbers should always have a 1:1 mapping with registers, and may
1061 // reference registers that have illegal (e.g. vector) types. Hence, we
1062 // shouldn't try to apply any sort of splitting logic to them.
1063 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1064 "No 1:1 mapping from clobbers to regs?");
1066 (void)SP;
1067 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1068 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1069 assert(
1070 (Regs[I] != SP ||
1072 "If we clobbered the stack pointer, MFI should know about it.");
1073 }
1074 return;
1075 }
1076
1077 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1078 MVT RegisterVT = RegVTs[Value];
1079 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1080 RegisterVT);
1081 for (unsigned i = 0; i != NumRegs; ++i) {
1082 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1083 Register TheReg = Regs[Reg++];
1084 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1085 }
1086 }
1087}
1088
1092 unsigned I = 0;
1093 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1094 unsigned RegCount = std::get<0>(CountAndVT);
1095 MVT RegisterVT = std::get<1>(CountAndVT);
1096 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1097 for (unsigned E = I + RegCount; I != E; ++I)
1098 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1099 }
1100 return OutVec;
1101}
1102
1104 AssumptionCache *ac, const TargetLibraryInfo *li,
1105 const TargetTransformInfo &TTI) {
1106 BatchAA = aa;
1107 AC = ac;
1108 GFI = gfi;
1109 LibInfo = li;
1110 Context = DAG.getContext();
1111 LPadToCallSiteMap.clear();
1112 this->TTI = &TTI;
1113 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1114 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1115 *DAG.getMachineFunction().getFunction().getParent());
1116 CanDescribeGlobalAddressInLocationList =
1117 canDescribeGlobalAddressInLocationList(DAG.getMachineFunction());
1118}
1119
1121 NodeMap.clear();
1122 UnusedArgNodeMap.clear();
1123 PendingLoads.clear();
1124 PendingExports.clear();
1125 PendingConstrainedFP.clear();
1126 PendingConstrainedFPStrict.clear();
1127 CurInst = nullptr;
1128 HasTailCall = false;
1129 SDNodeOrder = LowestSDNodeOrder;
1130 StatepointLowering.clear();
1131}
1132
1134 DanglingDebugInfoMap.clear();
1135}
1136
1137// Update DAG root to include dependencies on Pending chains.
1138SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1139 SDValue Root = DAG.getRoot();
1140
1141 if (Pending.empty())
1142 return Root;
1143
1144 // Add current root to PendingChains, unless we already indirectly
1145 // depend on it.
1146 if (Root.getOpcode() != ISD::EntryToken) {
1147 unsigned i = 0, e = Pending.size();
1148 for (; i != e; ++i) {
1149 assert(Pending[i].getNode()->getNumOperands() > 1);
1150 if (Pending[i].getNode()->getOperand(0) == Root)
1151 break; // Don't add the root if we already indirectly depend on it.
1152 }
1153
1154 if (i == e)
1155 Pending.push_back(Root);
1156 }
1157
1158 if (Pending.size() == 1)
1159 Root = Pending[0];
1160 else
1161 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1162
1163 DAG.setRoot(Root);
1164 Pending.clear();
1165 return Root;
1166}
1167
1171
1173 // If the new exception behavior differs from that of the pending
1174 // ones, chain up them and update the root.
1175 switch (EB) {
1178 // Floating-point exceptions produced by such operations are not intended
1179 // to be observed, so the sequence of these operations does not need to be
1180 // preserved.
1181 //
1182 // They however must not be mixed with the instructions that have strict
1183 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1184 // 'ebStrict' operations could distort the observed exception behavior.
1185 if (!PendingConstrainedFPStrict.empty()) {
1186 assert(PendingConstrainedFP.empty());
1187 updateRoot(PendingConstrainedFPStrict);
1188 }
1189 break;
1191 // Floating-point exception produced by these operations may be observed, so
1192 // they must be correctly chained. If trapping on FP exceptions is
1193 // disabled, the exceptions can be observed only by functions that read
1194 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1195 // the order of operations is not significant between barriers.
1196 //
1197 // If trapping is enabled, each operation becomes an implicit observation
1198 // point, so the operations must be sequenced according their original
1199 // source order.
1200 if (!PendingConstrainedFP.empty()) {
1201 assert(PendingConstrainedFPStrict.empty());
1202 updateRoot(PendingConstrainedFP);
1203 }
1204 // TODO: Add support for trapping-enabled scenarios.
1205 }
1206 return DAG.getRoot();
1207}
1208
1210 // Chain up all pending constrained intrinsics together with all
1211 // pending loads, by simply appending them to PendingLoads and
1212 // then calling getMemoryRoot().
1213 PendingLoads.reserve(PendingLoads.size() +
1214 PendingConstrainedFP.size() +
1215 PendingConstrainedFPStrict.size());
1216 PendingLoads.append(PendingConstrainedFP.begin(),
1217 PendingConstrainedFP.end());
1218 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1219 PendingConstrainedFPStrict.end());
1220 PendingConstrainedFP.clear();
1221 PendingConstrainedFPStrict.clear();
1222 return getMemoryRoot();
1223}
1224
1226 // We need to emit pending fpexcept.strict constrained intrinsics,
1227 // so append them to the PendingExports list.
1228 PendingExports.append(PendingConstrainedFPStrict.begin(),
1229 PendingConstrainedFPStrict.end());
1230 PendingConstrainedFPStrict.clear();
1231 return updateRoot(PendingExports);
1232}
1233
1235 DILocalVariable *Variable,
1237 DebugLoc DL) {
1238 assert(Variable && "Missing variable");
1239
1240 // Check if address has undef value.
1241 if (!Address || isa<UndefValue>(Address) ||
1242 (Address->use_empty() && !isa<Argument>(Address))) {
1243 LLVM_DEBUG(
1244 dbgs()
1245 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1246 return;
1247 }
1248
1249 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1250
1251 SDValue &N = NodeMap[Address];
1252 if (!N.getNode() && isa<Argument>(Address))
1253 // Check unused arguments map.
1254 N = UnusedArgNodeMap[Address];
1255 SDDbgValue *SDV;
1256 if (N.getNode()) {
1257 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1258 Address = BCI->getOperand(0);
1259 // Parameters are handled specially.
1260 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1261 if (IsParameter && FINode) {
1262 // Byval parameter. We have a frame index at this point.
1263 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1264 /*IsIndirect*/ true, DL, SDNodeOrder);
1265 } else if (isa<Argument>(Address)) {
1266 // Address is an argument, so try to emit its dbg value using
1267 // virtual register info from the FuncInfo.ValueMap.
1268 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1269 FuncArgumentDbgValueKind::Declare, N);
1270 return;
1271 } else {
1272 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1273 true, DL, SDNodeOrder);
1274 }
1275 DAG.AddDbgValue(SDV, IsParameter);
1276 } else {
1277 // If Address is an argument then try to emit its dbg value using
1278 // virtual register info from the FuncInfo.ValueMap.
1279 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1280 FuncArgumentDbgValueKind::Declare, N)) {
1281 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1282 << " (could not emit func-arg dbg_value)\n");
1283 }
1284 }
1285}
1286
1288 // Add SDDbgValue nodes for any var locs here. Do so before updating
1289 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1290 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1291 // Add SDDbgValue nodes for any var locs here. Do so before updating
1292 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1293 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1294 It != End; ++It) {
1295 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1296 dropDanglingDebugInfo(Var, It->Expr);
1297 if (It->Values.isKillLocation(It->Expr)) {
1298 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1299 continue;
1300 }
1301 SmallVector<Value *> Values(It->Values.location_ops());
1302 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1303 It->Values.hasArgList())) {
1304 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1306 FnVarLocs->getDILocalVariable(It->VariableID),
1307 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1308 }
1309 }
1310 }
1311
1312 // We must skip DbgVariableRecords if they've already been processed above as
1313 // we have just emitted the debug values resulting from assignment tracking
1314 // analysis, making any existing DbgVariableRecords redundant (and probably
1315 // less correct). We still need to process DbgLabelRecords. This does sink
1316 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1317 // be important as it does so deterministcally and ordering between
1318 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1319 // printing).
1320 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1321 // Is there is any debug-info attached to this instruction, in the form of
1322 // DbgRecord non-instruction debug-info records.
1323 for (DbgRecord &DR : I.getDbgRecordRange()) {
1324 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1325 assert(DLR->getLabel() && "Missing label");
1326 SDDbgLabel *SDV =
1327 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1328 DAG.AddDbgLabel(SDV);
1329 continue;
1330 }
1331
1332 if (SkipDbgVariableRecords)
1333 continue;
1335 DILocalVariable *Variable = DVR.getVariable();
1338
1340 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1341 continue;
1342 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1343 << "\n");
1345 DVR.getDebugLoc());
1346 continue;
1347 }
1348
1349 // A DbgVariableRecord with no locations is a kill location.
1351 if (Values.empty()) {
1353 SDNodeOrder);
1354 continue;
1355 }
1356
1357 // A DbgVariableRecord with an undef or absent location is also a kill
1358 // location.
1359 if (llvm::any_of(Values,
1360 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1362 SDNodeOrder);
1363 continue;
1364 }
1365
1366 bool IsVariadic = DVR.hasArgList();
1367 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1368 SDNodeOrder, IsVariadic)) {
1369 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1370 DVR.getDebugLoc(), SDNodeOrder);
1371 }
1372 }
1373}
1374
1376 visitDbgInfo(I);
1377
1378 // Set up outgoing PHI node register values before emitting the terminator.
1379 if (I.isTerminator()) {
1380 HandlePHINodesInSuccessorBlocks(I.getParent());
1381 }
1382
1383 ++SDNodeOrder;
1384 CurInst = &I;
1385
1386 // Set inserted listener only if required.
1387 bool NodeInserted = false;
1388 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1389 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1390 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1391 if (PCSectionsMD || MMRA) {
1392 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1393 DAG, [&](SDNode *) { NodeInserted = true; });
1394 }
1395
1396 visit(I.getOpcode(), I);
1397
1398 if (!I.isTerminator() && !HasTailCall &&
1399 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1401
1402 // Handle metadata.
1403 if (PCSectionsMD || MMRA) {
1404 auto It = NodeMap.find(&I);
1405 if (It != NodeMap.end()) {
1406 if (PCSectionsMD)
1407 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1408 if (MMRA)
1409 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1410 } else if (NodeInserted) {
1411 // This should not happen; if it does, don't let it go unnoticed so we can
1412 // fix it. Relevant visit*() function is probably missing a setValue().
1413 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1414 << I.getModule()->getName() << "]\n";
1415 LLVM_DEBUG(I.dump());
1416 assert(false);
1417 }
1418 }
1419
1420 CurInst = nullptr;
1421}
1422
1423void SelectionDAGBuilder::visitPHI(const PHINode &) {
1424 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1425}
1426
1427void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1428 // Note: this doesn't use InstVisitor, because it has to work with
1429 // ConstantExpr's in addition to instructions.
1430 switch (Opcode) {
1431 default: llvm_unreachable("Unknown instruction type encountered!");
1432 // Build the switch statement using the Instruction.def file.
1433#define HANDLE_INST(NUM, OPCODE, CLASS) \
1434 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1435#include "llvm/IR/Instruction.def"
1436 }
1437}
1438
1440 DILocalVariable *Variable,
1441 DebugLoc DL, unsigned Order,
1444 // For variadic dbg_values we will now insert poison.
1445 // FIXME: We can potentially recover these!
1447 for (const Value *V : Values) {
1448 auto *Poison = PoisonValue::get(V->getType());
1450 }
1451 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1452 /*IsIndirect=*/false, DL, Order,
1453 /*IsVariadic=*/true);
1454 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1455 return true;
1456}
1457
1459 DILocalVariable *Var,
1460 DIExpression *Expr,
1461 bool IsVariadic, DebugLoc DL,
1462 unsigned Order) {
1463 if (IsVariadic) {
1464 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1465 return;
1466 }
1467 // TODO: Dangling debug info will eventually either be resolved or produce
1468 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1469 // between the original dbg.value location and its resolved DBG_VALUE,
1470 // which we should ideally fill with an extra poison DBG_VALUE.
1471 assert(Values.size() == 1);
1472 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1473}
1474
1476 const DIExpression *Expr) {
1477 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1478 DIVariable *DanglingVariable = DDI.getVariable();
1479 DIExpression *DanglingExpr = DDI.getExpression();
1480 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1481 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1482 << printDDI(nullptr, DDI) << "\n");
1483 return true;
1484 }
1485 return false;
1486 };
1487
1488 for (auto &DDIMI : DanglingDebugInfoMap) {
1489 DanglingDebugInfoVector &DDIV = DDIMI.second;
1490
1491 // If debug info is to be dropped, run it through final checks to see
1492 // whether it can be salvaged.
1493 for (auto &DDI : DDIV)
1494 if (isMatchingDbgValue(DDI))
1495 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1496
1497 erase_if(DDIV, isMatchingDbgValue);
1498 }
1499}
1500
1501// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1502// generate the debug data structures now that we've seen its definition.
1504 SDValue Val) {
1505 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1506 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1507 return;
1508
1509 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1510 for (auto &DDI : DDIV) {
1511 DebugLoc DL = DDI.getDebugLoc();
1512 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1513 DILocalVariable *Variable = DDI.getVariable();
1514 DIExpression *Expr = DDI.getExpression();
1515 assert(Variable->isValidLocationForIntrinsic(DL) &&
1516 "Expected inlined-at fields to agree");
1517 SDDbgValue *SDV;
1518 if (Val.getNode()) {
1519 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1520 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1521 // we couldn't resolve it directly when examining the DbgValue intrinsic
1522 // in the first place we should not be more successful here). Unless we
1523 // have some test case that prove this to be correct we should avoid
1524 // calling EmitFuncArgumentDbgValue here.
1525 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1526 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1527 FuncArgumentDbgValueKind::Value, Val)) {
1528 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1529 << printDDI(V, DDI) << "\n");
1530 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1531 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1532 // inserted after the definition of Val when emitting the instructions
1533 // after ISel. An alternative could be to teach
1534 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1535 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1536 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1537 << ValSDNodeOrder << "\n");
1538 SDV = getDbgValue(Val, Variable, Expr, DL,
1539 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1540 DAG.AddDbgValue(SDV, false);
1541 } else
1542 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1543 << printDDI(V, DDI)
1544 << " in EmitFuncArgumentDbgValue\n");
1545 } else {
1546 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1547 << "\n");
1548 auto Poison = PoisonValue::get(V->getType());
1549 auto SDV =
1550 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1551 DAG.AddDbgValue(SDV, false);
1552 }
1553 }
1554 DDIV.clear();
1555}
1556
1557/// If \p V is the address of a describable global, possibly displaced by a
1558/// constant, return the global and fold the displacement into location operand
1559/// \p OpIdx of \p Expr. The displacement rides along in the expression rather
1560/// than in the operand, so that it survives into a DBG_INSTR_REF.
1561static const GlobalValue *
1562getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx,
1563 const MachineFunction &MF) {
1564 const auto *C = dyn_cast<Constant>(V);
1565 if (!C)
1566 return nullptr;
1567 int64_t Offset;
1569 if (GV && Offset) {
1572 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx, /*StackValue=*/false);
1573 }
1574 return GV;
1575}
1576
1578 DanglingDebugInfo &DDI) {
1579 // TODO: For the variadic implementation, instead of only checking the fail
1580 // state of `handleDebugValue`, we need know specifically which values were
1581 // invalid, so that we attempt to salvage only those values when processing
1582 // a DIArgList.
1583 const Value *OrigV = V;
1584 DILocalVariable *Var = DDI.getVariable();
1585 DIExpression *Expr = DDI.getExpression();
1586 DebugLoc DL = DDI.getDebugLoc();
1587 unsigned SDOrder = DDI.getSDNodeOrder();
1588
1589 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1590 // that DW_OP_stack_value is desired.
1591 bool StackValue = true;
1592
1593 // handleDebugValue holds out for a register with the address of a global
1594 // that a location list could not name. With no such register forthcoming,
1595 // naming the global still beats dropping the location.
1596 auto HandleGlobalAddress = [&] {
1597 DIExpression *GVExpr = Expr;
1598 const GlobalValue *GV =
1599 getGlobalAddressDbgOperand(V, GVExpr, 0, DAG.getMachineFunction());
1600 if (!GV)
1601 return false;
1602 SDDbgValue *SDV = DAG.getDbgValueList(
1603 Var, GVExpr, SDDbgOperand::fromGlobalAddr(GV), /*Dependencies=*/{},
1604 /*IsIndirect=*/false, DL, SDOrder, /*IsVariadic=*/false);
1605 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1606 return true;
1607 };
1608
1609 // Can this Value can be encoded without any further work?
1610 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1611 HandleGlobalAddress())
1612 return;
1613
1614 // Attempt to salvage back through as many instructions as possible. Bail if
1615 // a non-instruction is seen, such as a constant expression or global
1616 // variable. FIXME: Further work could recover those too.
1617 while (isa<Instruction>(V)) {
1618 const Instruction &VAsInst = *cast<const Instruction>(V);
1619 // Temporary "0", awaiting real implementation.
1621 SmallVector<Value *, 4> AdditionalValues;
1622 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1623 Expr->getNumLocationOperands(), Ops,
1624 AdditionalValues);
1625 // If we cannot salvage any further, and haven't yet found a suitable debug
1626 // expression, bail out.
1627 if (!V)
1628 break;
1629
1630 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1631 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1632 // here for variadic dbg_values, remove that condition.
1633 if (!AdditionalValues.empty())
1634 break;
1635
1636 // New value and expr now represent this debuginfo.
1638
1639 // Some kind of simplification occurred: check whether the operand of the
1640 // salvaged debug expression can be encoded in this DAG.
1641 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1642 HandleGlobalAddress()) {
1643 LLVM_DEBUG(
1644 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1645 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1646 return;
1647 }
1648 }
1649
1650 // This was the final opportunity to salvage this debug information, and it
1651 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1652 // any earlier variable location.
1653 assert(OrigV && "V shouldn't be null");
1654 auto *Poison = PoisonValue::get(OrigV->getType());
1655 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDNodeOrder);
1656 DAG.AddDbgValue(SDV, false);
1657 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1658 << printDDI(OrigV, DDI) << "\n");
1659}
1660
1662 DIExpression *Expr,
1663 DebugLoc DbgLoc,
1664 unsigned Order) {
1668 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1669 /*IsVariadic*/ false);
1670}
1671
1673 DILocalVariable *Var,
1674 DIExpression *Expr, DebugLoc DbgLoc,
1675 unsigned Order, bool IsVariadic) {
1676 if (Values.empty())
1677 return true;
1678
1679 // Filter EntryValue locations out early.
1680 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1681 return true;
1682
1683 SmallVector<SDDbgOperand> LocationOps;
1684 SmallVector<SDNode *> Dependencies;
1685 for (const auto &[OpIdx, V] : enumerate(Values)) {
1686 // Constant value.
1689 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1690 continue;
1691 }
1692
1693 // Look through IntToPtr constants.
1694 if (auto *CE = dyn_cast<ConstantExpr>(V))
1695 if (CE->getOpcode() == Instruction::IntToPtr) {
1696 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1697 continue;
1698 }
1699
1700 // The address of a global is a link-time constant, and so is a constant
1701 // displacement from one. A global whose address cannot be described this
1702 // way falls through to be described by whatever materializes it instead.
1703 // So does one that a location list could not name, should the variable
1704 // need one; salvageUnresolvedDbgValue names it if nothing materializes it.
1705 if (CanDescribeGlobalAddressInLocationList)
1707 V, Expr, OpIdx, DAG.getMachineFunction())) {
1709 continue;
1710 }
1711
1712 // If the Value is a frame index, we can create a FrameIndex debug value
1713 // without relying on the DAG at all.
1714 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1715 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1716 if (SI != FuncInfo.StaticAllocaMap.end()) {
1717 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1718 continue;
1719 }
1720 }
1721
1722 // Do not use getValue() in here; we don't want to generate code at
1723 // this point if it hasn't been done yet.
1724 SDValue N = NodeMap[V];
1725 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1726 N = UnusedArgNodeMap[V];
1727
1728 if (N.getNode()) {
1729 // Only emit func arg dbg value for non-variadic dbg.values for now.
1730 if (!IsVariadic &&
1731 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1732 FuncArgumentDbgValueKind::Value, N))
1733 return true;
1734 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1735 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1736 // describe stack slot locations.
1737 //
1738 // Consider "int x = 0; int *px = &x;". There are two kinds of
1739 // interesting debug values here after optimization:
1740 //
1741 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1742 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1743 //
1744 // Both describe the direct values of their associated variables.
1745 Dependencies.push_back(N.getNode());
1746 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1747 continue;
1748 }
1749 LocationOps.emplace_back(
1750 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1751 continue;
1752 }
1753
1754 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1755 // Special rules apply for the first dbg.values of parameter variables in a
1756 // function. Identify them by the fact they reference Argument Values, that
1757 // they're parameters, and they are parameters of the current function. We
1758 // need to let them dangle until they get an SDNode.
1759 bool IsParamOfFunc =
1760 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1761 if (IsParamOfFunc)
1762 return false;
1763
1764 // The value is not used in this block yet (or it would have an SDNode).
1765 // We still want the value to appear for the user if possible -- if it has
1766 // an associated VReg, we can refer to that instead.
1767 auto VMI = FuncInfo.ValueMap.find(V);
1768 if (VMI != FuncInfo.ValueMap.end()) {
1769 Register Reg = VMI->second;
1770 // If this is a PHI node, it may be split up into several MI PHI nodes
1771 // (in FunctionLoweringInfo::set).
1772 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1773 V->getType(), std::nullopt);
1774 if (RFV.occupiesMultipleRegs()) {
1775 // FIXME: We could potentially support variadic dbg_values here.
1776 if (IsVariadic)
1777 return false;
1778 unsigned Offset = 0;
1779 unsigned BitsToDescribe = 0;
1780 if (auto VarSize = Var->getSizeInBits())
1781 BitsToDescribe = *VarSize;
1782 if (auto Fragment = Expr->getFragmentInfo())
1783 BitsToDescribe = Fragment->SizeInBits;
1784 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1785 // Bail out if all bits are described already.
1786 if (Offset >= BitsToDescribe)
1787 break;
1788 // TODO: handle scalable vectors.
1789 unsigned RegisterSize = RegAndSize.second;
1790 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1791 ? BitsToDescribe - Offset
1792 : RegisterSize;
1793 auto FragmentExpr = DIExpression::createFragmentExpression(
1794 Expr, Offset, FragmentSize);
1795 if (!FragmentExpr)
1796 continue;
1797 SDDbgValue *SDV = DAG.getVRegDbgValue(
1798 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1799 DAG.AddDbgValue(SDV, false);
1800 Offset += RegisterSize;
1801 }
1802 return true;
1803 }
1804 // We can use simple vreg locations for variadic dbg_values as well.
1805 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1806 continue;
1807 }
1808 // We failed to create a SDDbgOperand for V.
1809 return false;
1810 }
1811
1812 // We have created a SDDbgOperand for each Value in Values.
1813 assert(!LocationOps.empty());
1814 SDDbgValue *SDV =
1815 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1816 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1817 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1818 return true;
1819}
1820
1822 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1823 for (auto &Pair : DanglingDebugInfoMap)
1824 for (auto &DDI : Pair.second)
1825 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1827}
1828
1829/// getCopyFromRegs - If there was virtual register allocated for the value V
1830/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1832 auto It = FuncInfo.ValueMap.find(V);
1833 SDValue Result;
1834
1835 if (It != FuncInfo.ValueMap.end()) {
1836 Register InReg = It->second;
1837
1838 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1839 DAG.getDataLayout(), InReg, Ty,
1840 std::nullopt); // This is not an ABI copy.
1841 SDValue Chain = DAG.getEntryNode();
1842 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1843 V);
1844 resolveDanglingDebugInfo(V, Result);
1845 }
1846
1847 return Result;
1848}
1849
1850/// getValue - Return an SDValue for the given Value.
1852 // If we already have an SDValue for this value, use it. It's important
1853 // to do this first, so that we don't create a CopyFromReg if we already
1854 // have a regular SDValue.
1855 SDValue &N = NodeMap[V];
1856 if (N.getNode()) return N;
1857
1858 // If there's a virtual register allocated and initialized for this
1859 // value, use it.
1860 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1861 return copyFromReg;
1862
1863 // Otherwise create a new SDValue and remember it.
1864 SDValue Val = getValueImpl(V);
1865 NodeMap[V] = Val;
1867 return Val;
1868}
1869
1870void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1871 if (V->getType()->isVoidTy())
1872 return;
1873
1874 SmallVector<EVT, 4> ValueVTs;
1875 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1876 V->getType(), ValueVTs);
1877 if (ValueVTs.empty())
1878 return;
1879 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1880}
1881
1882/// getNonRegisterValue - Return an SDValue for the given Value, but
1883/// don't look in FuncInfo.ValueMap for a virtual register.
1885 // If we already have an SDValue for this value, use it.
1886 SDValue &N = NodeMap[V];
1887 if (N.getNode()) {
1888 if (isIntOrFPConstant(N)) {
1889 // Remove the debug location from the node as the node is about to be used
1890 // in a location which may differ from the original debug location. This
1891 // is relevant to Constant and ConstantFP nodes because they can appear
1892 // as constant expressions inside PHI nodes.
1893 N->setDebugLoc(DebugLoc());
1894 }
1895 return N;
1896 }
1897
1898 // Otherwise create a new SDValue and remember it.
1899 SDValue Val = getValueImpl(V);
1900 NodeMap[V] = Val;
1902 return Val;
1903}
1904
1905/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1906/// Create an SDValue for the given value.
1908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1909
1910 if (const Constant *C = dyn_cast<Constant>(V)) {
1911 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1912
1913 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1914 SDLoc DL = getCurSDLoc();
1915
1916 // DAG.getConstant() may attempt to legalise the vector constant which can
1917 // significantly change the combines applied to the DAG. To reduce the
1918 // divergence when enabling ConstantInt based vectors we try to construct
1919 // the DAG in the same way as shufflevector based splats. TODO: The
1920 // divergence sometimes leads to better optimisations. Ideally we should
1921 // prevent DAG.getConstant() from legalising too early but there are some
1922 // degradations preventing this.
1923 if (VT.isScalableVector())
1924 return DAG.getNode(
1925 ISD::SPLAT_VECTOR, DL, VT,
1926 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1927 if (VT.isFixedLengthVector())
1928 return DAG.getSplatBuildVector(
1929 VT, DL,
1930 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1931 return DAG.getConstant(*CI, DL, VT);
1932 }
1933
1934 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1935 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1936
1937 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1938 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1939
1940 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1941 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1942 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1943 getValue(CPA->getAddrDiscriminator()),
1944 getValue(CPA->getDiscriminator()));
1945 }
1946
1948 return DAG.getConstant(0, getCurSDLoc(), VT);
1949
1950 if (match(C, m_VScale()))
1951 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1952
1953 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1954 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1955
1956 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1957 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1958
1959 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1960 visit(CE->getOpcode(), *CE);
1961 SDValue N1 = NodeMap[V];
1962 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1963 return N1;
1964 }
1965
1967 SmallVector<SDValue, 4> Constants;
1968 for (const Use &U : C->operands()) {
1969 SDNode *Val = getValue(U).getNode();
1970 // If the operand is an empty aggregate, there are no values.
1971 if (!Val) continue;
1972 // Add each leaf value from the operand to the Constants list
1973 // to form a flattened list of all the values.
1974 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1975 Constants.push_back(SDValue(Val, i));
1976 }
1977
1978 return DAG.getMergeValues(Constants, getCurSDLoc());
1979 }
1980
1981 if (const ConstantDataSequential *CDS =
1984 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1985 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1986 // Add each leaf value from the operand to the Constants list
1987 // to form a flattened list of all the values.
1988 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1989 Ops.push_back(SDValue(Val, i));
1990 }
1991
1992 if (isa<ArrayType>(CDS->getType()))
1993 return DAG.getMergeValues(Ops, getCurSDLoc());
1994 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1995 }
1996
1997 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1999 "Unknown struct or array constant!");
2000
2001 SmallVector<EVT, 4> ValueVTs;
2002 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
2003 unsigned NumElts = ValueVTs.size();
2004 if (NumElts == 0)
2005 return SDValue(); // empty struct
2006 SmallVector<SDValue, 4> Constants(NumElts);
2007 for (unsigned i = 0; i != NumElts; ++i) {
2008 EVT EltVT = ValueVTs[i];
2009 if (isa<UndefValue>(C))
2010 Constants[i] = DAG.getUNDEF(EltVT);
2011 else if (EltVT.isFloatingPoint())
2012 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2013 else
2014 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
2015 }
2016
2017 return DAG.getMergeValues(Constants, getCurSDLoc());
2018 }
2019
2020 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
2021 return DAG.getBlockAddress(BA, VT);
2022
2023 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
2024 return getValue(Equiv->getGlobalValue());
2025
2026 if (const auto *NC = dyn_cast<NoCFIValue>(C))
2027 return getValue(NC->getGlobalValue());
2028
2029 if (VT == MVT::aarch64svcount) {
2030 assert(C->isNullValue() && "Can only zero this target type!");
2031 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
2032 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
2033 }
2034
2035 if (VT.isRISCVVectorTuple()) {
2036 assert(C->isNullValue() && "Can only zero this target type!");
2037 return DAG.getNode(
2039 DAG.getNode(
2041 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
2042 VT.getSizeInBits().getKnownMinValue() / 8, true),
2043 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
2044 }
2045
2046 if (VT == MVT::externref || VT == MVT::funcref) {
2047 assert(C->isNullValue() && "Can only zero this target type!");
2048 // The zero value of a WebAssembly reference type is the null reference,
2049 // materialized with ref.null.
2050 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
2051 : Intrinsic::wasm_ref_null_func;
2052 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
2053 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
2054 }
2055
2056 VectorType *VecTy = cast<VectorType>(V->getType());
2057
2058 // Now that we know the number and type of the elements, get that number of
2059 // elements into the Ops array based on what kind of constant it is.
2060 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2062 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2063 for (unsigned i = 0; i != NumElements; ++i)
2064 Ops.push_back(getValue(CV->getOperand(i)));
2065
2066 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2067 }
2068
2070 EVT EltVT =
2071 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2072
2073 SDValue Op;
2074 if (EltVT.isFloatingPoint())
2075 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2076 else
2077 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2078
2079 return DAG.getSplat(VT, getCurSDLoc(), Op);
2080 }
2081
2082 llvm_unreachable("Unknown vector constant");
2083 }
2084
2085 // If this is a static alloca, generate it as the frameindex instead of
2086 // computation.
2087 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2088 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2089 if (SI != FuncInfo.StaticAllocaMap.end())
2090 return DAG.getFrameIndex(
2091 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2092 }
2093
2094 // If this is an instruction which fast-isel has deferred, select it now.
2095 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2096 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2097 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2098 Inst->getType(), std::nullopt);
2099 SDValue Chain = DAG.getEntryNode();
2100 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2101 }
2102
2103 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2104 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2105
2106 if (const auto *BB = dyn_cast<BasicBlock>(V))
2107 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2108
2109 llvm_unreachable("Can't get register for value!");
2110}
2111
2112void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2114 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2115 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2116 bool IsSEH = isAsynchronousEHPersonality(Pers);
2117 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2118 if (IsSEH) {
2119 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2120 CatchPadMBB->setIsEHContTarget(true);
2122 } else
2123 CatchPadMBB->setIsEHScopeEntry();
2124 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2125 if (IsMSVCCXX || IsCoreCLR)
2126 CatchPadMBB->setIsEHFuncletEntry();
2127}
2128
2129void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2130 // Update machine-CFG edge.
2131 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2132 FuncInfo.MBB->addSuccessor(TargetMBB);
2133
2134 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2135 bool IsSEH = isAsynchronousEHPersonality(Pers);
2136 if (IsSEH) {
2137 // If this is not a fall-through branch or optimizations are switched off,
2138 // emit the branch.
2139 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2140 TM.getOptLevel() == CodeGenOptLevel::None)
2141 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2142 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2143 return;
2144 }
2145
2146 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2147 TargetMBB->setIsEHContTarget(true);
2148 DAG.getMachineFunction().setHasEHContTarget(true);
2149
2150 // Figure out the funclet membership for the catchret's successor.
2151 // This will be used by the FuncletLayout pass to determine how to order the
2152 // BB's.
2153 // A 'catchret' returns to the outer scope's color.
2154 Value *ParentPad = I.getCatchSwitchParentPad();
2155 const BasicBlock *SuccessorColor;
2156 if (isa<ConstantTokenNone>(ParentPad))
2157 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2158 else
2159 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2160 assert(SuccessorColor && "No parent funclet for catchret!");
2161 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2162 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2163
2164 // Create the terminator node.
2165 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2166 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2167 DAG.getBasicBlock(SuccessorColorMBB));
2168 DAG.setRoot(Ret);
2169}
2170
2171void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2172 // Don't emit any special code for the cleanuppad instruction. It just marks
2173 // the start of an EH scope/funclet.
2174 FuncInfo.MBB->setIsEHScopeEntry();
2175 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2176 if (Pers != EHPersonality::Wasm_CXX && Pers != EHPersonality::Wasm_D) {
2177 FuncInfo.MBB->setIsEHFuncletEntry();
2178 FuncInfo.MBB->setIsCleanupFuncletEntry();
2179 }
2180}
2181
2182/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2183/// many places it could ultimately go. In the IR, we have a single unwind
2184/// destination, but in the machine CFG, we enumerate all the possible blocks.
2185/// This function skips over imaginary basic blocks that hold catchswitch
2186/// instructions, and finds all the "real" machine
2187/// basic block destinations. As those destinations may not be successors of
2188/// EHPadBB, here we also calculate the edge probability to those destinations.
2189/// The passed-in Prob is the edge probability to EHPadBB.
2191 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2192 BranchProbability Prob,
2193 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2194 &UnwindDests) {
2195 EHPersonality Personality =
2197 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2198 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2199 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2200 bool IsWasmD = Personality == EHPersonality::Wasm_D;
2201 bool IsSEH = isAsynchronousEHPersonality(Personality);
2202
2203 while (EHPadBB) {
2205 BasicBlock *NewEHPadBB = nullptr;
2206 if (isa<LandingPadInst>(Pad)) {
2207 // Stop on landingpads. They are not funclets.
2208 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2209 break;
2210 } else if (isa<CleanupPadInst>(Pad)) {
2211 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2212 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2213 // which always catches an exception.
2214 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2215 UnwindDests.back().first->setIsEHScopeEntry();
2216 // In Wasm, EH scopes are not funclets
2217 if (!IsWasmCXX && !IsWasmD)
2218 UnwindDests.back().first->setIsEHFuncletEntry();
2219 break;
2220 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2221 // Add the catchpad handlers to the possible destinations.
2222 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2223 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2224 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2225 if (IsMSVCCXX || IsCoreCLR)
2226 UnwindDests.back().first->setIsEHFuncletEntry();
2227 if (!IsSEH)
2228 UnwindDests.back().first->setIsEHScopeEntry();
2229 }
2230 NewEHPadBB = CatchSwitch->getUnwindDest();
2231 } else {
2232 continue;
2233 }
2234
2235 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2236 if (BPI && NewEHPadBB)
2237 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2238 EHPadBB = NewEHPadBB;
2239 }
2240}
2241
2242void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2243 // Update successor info.
2245 auto UnwindDest = I.getUnwindDest();
2246 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2247 BranchProbability UnwindDestProb =
2248 (BPI && UnwindDest)
2249 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2251 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2252 for (auto &UnwindDest : UnwindDests) {
2253 UnwindDest.first->setIsEHPad();
2254 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2255 }
2256 FuncInfo.MBB->normalizeSuccProbs();
2257
2258 // Create the terminator node.
2259 MachineBasicBlock *CleanupPadMBB =
2260 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2261 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2262 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2263 DAG.setRoot(Ret);
2264}
2265
2266void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2267 report_fatal_error("visitCatchSwitch not yet implemented!");
2268}
2269
2270void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2271 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2272 auto &DL = DAG.getDataLayout();
2273 SDValue Chain = getControlRoot();
2276
2277 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2278 // lower
2279 //
2280 // %val = call <ty> @llvm.experimental.deoptimize()
2281 // ret <ty> %val
2282 //
2283 // differently.
2284 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2286 return;
2287 }
2288
2289 if (!FuncInfo.CanLowerReturn) {
2290 Register DemoteReg = FuncInfo.DemoteRegister;
2291
2292 // Emit a store of the return value through the virtual register.
2293 // Leave Outs empty so that LowerReturn won't try to load return
2294 // registers the usual way.
2295 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2296 SDValue RetPtr =
2297 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2298 Type *RetTy = I.getOperand(0)->getType();
2299 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2300 RetPtr =
2301 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2302 SDValue RetOp = getValue(I.getOperand(0));
2303
2304 SmallVector<EVT, 4> ValueVTs, MemVTs;
2305 SmallVector<uint64_t, 4> Offsets;
2306 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2307 unsigned NumValues = ValueVTs.size();
2308
2309 SmallVector<SDValue, 4> Chains(NumValues);
2310 for (unsigned i = 0; i != NumValues; ++i) {
2311 // An aggregate return value cannot wrap around the address space, so
2312 // offsets to its parts don't wrap either.
2313 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2314 TypeSize::getFixed(Offsets[i]));
2315
2316 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2317 if (MemVTs[i] != ValueVTs[i])
2318 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2319 Chains[i] = DAG.getStore(
2320 Chain, getCurSDLoc(), Val,
2321 // FIXME: better loc info would be nice.
2322 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2323 commonAlignment(BaseAlign, Offsets[i]));
2324 }
2325
2326 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2327 MVT::Other, Chains);
2328 } else if (I.getNumOperands() != 0) {
2330 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2331 unsigned NumValues = Types.size();
2332 if (NumValues) {
2333 SDValue RetOp = getValue(I.getOperand(0));
2334
2335 const Function *F = I.getParent()->getParent();
2336
2337 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2338 I.getOperand(0)->getType(), F->getCallingConv(),
2339 /*IsVarArg*/ false, DL);
2340
2341 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2342 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2343 ExtendKind = ISD::SIGN_EXTEND;
2344 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2345 ExtendKind = ISD::ZERO_EXTEND;
2346
2347 LLVMContext &Context = F->getContext();
2348 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2349
2350 for (unsigned j = 0; j != NumValues; ++j) {
2351 EVT VT = TLI.getValueType(DL, Types[j]);
2352
2353 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2354 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2355
2356 CallingConv::ID CC = F->getCallingConv();
2357
2358 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2359 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2360 SmallVector<SDValue, 4> Parts(NumParts);
2362 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2363 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2364
2365 // 'inreg' on function refers to return value
2366 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2367 if (RetInReg)
2368 Flags.setInReg();
2369
2370 if (I.getOperand(0)->getType()->isPointerTy()) {
2371 Flags.setPointer();
2372 Flags.setPointerAddrSpace(
2373 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2374 }
2375
2376 if (NeedsRegBlock) {
2377 Flags.setInConsecutiveRegs();
2378 if (j == NumValues - 1)
2379 Flags.setInConsecutiveRegsLast();
2380 }
2381
2382 // Propagate extension type if any
2383 if (ExtendKind == ISD::SIGN_EXTEND)
2384 Flags.setSExt();
2385 else if (ExtendKind == ISD::ZERO_EXTEND)
2386 Flags.setZExt();
2387 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2388 Flags.setNoExt();
2389
2390 for (unsigned i = 0; i < NumParts; ++i) {
2391 Outs.push_back(ISD::OutputArg(Flags,
2392 Parts[i].getValueType().getSimpleVT(),
2393 VT, Types[j], 0, 0));
2394 OutVals.push_back(Parts[i]);
2395 }
2396 }
2397 }
2398 }
2399
2400 // Push in swifterror virtual register as the last element of Outs. This makes
2401 // sure swifterror virtual register will be returned in the swifterror
2402 // physical register.
2403 const Function *F = I.getParent()->getParent();
2404 if (TLI.supportSwiftError() &&
2405 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2406 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2407 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2408 Flags.setSwiftError();
2409 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2410 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2411 PointerType::getUnqual(*DAG.getContext()),
2412 /*origidx=*/1, /*partOffs=*/0));
2413 // Create SDNode for the swifterror virtual register.
2414 OutVals.push_back(
2415 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2416 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2417 EVT(TLI.getPointerTy(DL))));
2418 }
2419
2420 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2421 CallingConv::ID CallConv =
2422 DAG.getMachineFunction().getFunction().getCallingConv();
2423 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2424 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2425
2426 // Verify that the target's LowerReturn behaved as expected.
2427 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2428 "LowerReturn didn't return a valid chain!");
2429
2430 // Update the DAG with the new chain value resulting from return lowering.
2431 DAG.setRoot(Chain);
2432}
2433
2434/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2435/// created for it, emit nodes to copy the value into the virtual
2436/// registers.
2438 // Skip empty types
2439 if (V->getType()->isEmptyTy())
2440 return;
2441
2442 auto VMI = FuncInfo.ValueMap.find(V);
2443 if (VMI != FuncInfo.ValueMap.end()) {
2444 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2445 "Unused value assigned virtual registers!");
2446 CopyValueToVirtualRegister(V, VMI->second);
2447 }
2448}
2449
2450/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2451/// the current basic block, add it to ValueMap now so that we'll get a
2452/// CopyTo/FromReg.
2454 // No need to export constants.
2455 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2456
2457 // Already exported?
2458 if (FuncInfo.isExportedInst(V)) return;
2459
2460 Register Reg = FuncInfo.InitializeRegForValue(V);
2462}
2463
2465 const BasicBlock *FromBB) {
2466 // The operands of the setcc have to be in this block. We don't know
2467 // how to export them from some other block.
2468 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2469 // Can export from current BB.
2470 if (VI->getParent() == FromBB)
2471 return true;
2472
2473 // Is already exported, noop.
2474 return FuncInfo.isExportedInst(V);
2475 }
2476
2477 // If this is an argument, we can export it if the BB is the entry block or
2478 // if it is already exported.
2479 if (isa<Argument>(V)) {
2480 if (FromBB->isEntryBlock())
2481 return true;
2482
2483 // Otherwise, can only export this if it is already exported.
2484 return FuncInfo.isExportedInst(V);
2485 }
2486
2487 // Otherwise, constants can always be exported.
2488 return true;
2489}
2490
2491/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2493SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2494 const MachineBasicBlock *Dst) const {
2496 const BasicBlock *SrcBB = Src->getBasicBlock();
2497 const BasicBlock *DstBB = Dst->getBasicBlock();
2498 if (!BPI) {
2499 // If BPI is not available, set the default probability as 1 / N, where N is
2500 // the number of successors.
2501 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2502 return BranchProbability(1, SuccSize);
2503 }
2504 return BPI->getEdgeProbability(SrcBB, DstBB);
2505}
2506
2507void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2508 MachineBasicBlock *Dst,
2509 BranchProbability Prob) {
2510 if (!FuncInfo.BPI)
2511 Src->addSuccessorWithoutProb(Dst);
2512 else {
2513 if (Prob.isUnknown())
2514 Prob = getEdgeProbability(Src, Dst);
2515 Src->addSuccessor(Dst, Prob);
2516 }
2517}
2518
2519static bool InBlock(const Value *V, const BasicBlock *BB) {
2520 if (const Instruction *I = dyn_cast<Instruction>(V))
2521 return I->getParent() == BB;
2522 return true;
2523}
2524
2525/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2526/// This function emits a branch and is used at the leaves of an OR or an
2527/// AND operator tree.
2528void
2531 MachineBasicBlock *FBB,
2532 MachineBasicBlock *CurBB,
2533 MachineBasicBlock *SwitchBB,
2534 BranchProbability TProb,
2535 BranchProbability FProb,
2536 bool InvertCond) {
2537 const BasicBlock *BB = CurBB->getBasicBlock();
2538
2539 // If the leaf of the tree is a comparison, merge the condition into
2540 // the caseblock.
2541 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2542 // The operands of the cmp have to be in this block. We don't know
2543 // how to export them from some other block. If this is the first block
2544 // of the sequence, no exporting is needed.
2545 if (CurBB == SwitchBB ||
2546 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2547 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2548 ISD::CondCode Condition;
2549 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2550 ICmpInst::Predicate Pred =
2551 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2552 Condition = getICmpCondCode(Pred);
2553 } else {
2554 const FCmpInst *FC = cast<FCmpInst>(Cond);
2555 FCmpInst::Predicate Pred =
2556 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2557 Condition = getFCmpCondCode(Pred);
2558 if (FC->hasNoNaNs() ||
2559 (isKnownNeverNaN(FC->getOperand(0),
2560 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2561 isKnownNeverNaN(FC->getOperand(1),
2562 SimplifyQuery(DAG.getDataLayout(), FC))))
2563 Condition = getFCmpCodeWithoutNaN(Condition);
2564 }
2565
2566 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2567 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2568 SL->SwitchCases.push_back(CB);
2569 return;
2570 }
2571 }
2572
2573 // Create a CaseBlock record representing this branch.
2574 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2575 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2576 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2577 SL->SwitchCases.push_back(CB);
2578}
2579
2580// Collect dependencies on V recursively. This is used for the cost analysis in
2581// `shouldKeepJumpConditionsTogether`.
2585 unsigned Depth = 0) {
2586 // Return false if we have an incomplete count.
2588 return false;
2589
2590 auto *I = dyn_cast<Instruction>(V);
2591 if (I == nullptr)
2592 return true;
2593
2594 if (Necessary != nullptr) {
2595 // This instruction is necessary for the other side of the condition so
2596 // don't count it.
2597 if (Necessary->contains(I))
2598 return true;
2599 }
2600
2601 // Already added this dep.
2602 if (!Deps->try_emplace(I, false).second)
2603 return true;
2604
2605 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2606 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2607 Depth + 1))
2608 return false;
2609 return true;
2610}
2611
2614 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2616 if (Params.BaseCost < 0)
2617 return false;
2618
2619 // Baseline cost.
2620 InstructionCost CostThresh = Params.BaseCost;
2621
2622 BranchProbabilityInfo *BPI = nullptr;
2623 if (Params.LikelyBias || Params.UnlikelyBias)
2624 BPI = FuncInfo.BPI;
2625 if (BPI != nullptr) {
2626 // See if we are either likely to get an early out or compute both lhs/rhs
2627 // of the condition.
2628 BasicBlock *IfFalse = I.getSuccessor(0);
2629 BasicBlock *IfTrue = I.getSuccessor(1);
2630
2631 std::optional<bool> Likely;
2632 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2633 Likely = true;
2634 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2635 Likely = false;
2636
2637 if (Likely) {
2638 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2639 // Its likely we will have to compute both lhs and rhs of condition
2640 CostThresh += Params.LikelyBias;
2641 else {
2642 if (Params.UnlikelyBias < 0)
2643 return false;
2644 // Its likely we will get an early out.
2645 CostThresh -= Params.UnlikelyBias;
2646 }
2647 }
2648 }
2649
2650 if (CostThresh <= 0)
2651 return false;
2652
2653 // Collect "all" instructions that lhs condition is dependent on.
2654 // Use map for stable iteration (to avoid non-determanism of iteration of
2655 // SmallPtrSet). The `bool` value is just a dummy.
2657 collectInstructionDeps(&LhsDeps, Lhs);
2658 // Collect "all" instructions that rhs condition is dependent on AND are
2659 // dependencies of lhs. This gives us an estimate on which instructions we
2660 // stand to save by splitting the condition.
2661 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2662 return false;
2663 // Add the compare instruction itself unless its a dependency on the LHS.
2664 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2665 if (!LhsDeps.contains(RhsI))
2666 RhsDeps.try_emplace(RhsI, false);
2667
2668 InstructionCost CostOfIncluding = 0;
2669 // See if this instruction will need to computed independently of whether RHS
2670 // is.
2671 Value *BrCond = I.getCondition();
2672 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2673 for (const auto *U : Ins->users()) {
2674 // If user is independent of RHS calculation we don't need to count it.
2675 if (auto *UIns = dyn_cast<Instruction>(U))
2676 if (UIns != BrCond && !RhsDeps.contains(UIns))
2677 return false;
2678 }
2679 return true;
2680 };
2681
2682 // Prune instructions from RHS Deps that are dependencies of unrelated
2683 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2684 // arbitrary and just meant to cap the how much time we spend in the pruning
2685 // loop. Its highly unlikely to come into affect.
2686 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2687 // Stop after a certain point. No incorrectness from including too many
2688 // instructions.
2689 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2690 const Instruction *ToDrop = nullptr;
2691 for (const auto &InsPair : RhsDeps) {
2692 if (!ShouldCountInsn(InsPair.first)) {
2693 ToDrop = InsPair.first;
2694 break;
2695 }
2696 }
2697 if (ToDrop == nullptr)
2698 break;
2699 RhsDeps.erase(ToDrop);
2700 }
2701
2702 for (const auto &InsPair : RhsDeps) {
2703 // Finally accumulate latency that we can only attribute to computing the
2704 // RHS condition. Use latency because we are essentially trying to calculate
2705 // the cost of the dependency chain.
2706 // Possible TODO: We could try to estimate ILP and make this more precise.
2707 CostOfIncluding += TTI->getInstructionCost(
2708 InsPair.first, TargetTransformInfo::TCK_Latency);
2709
2710 if (CostOfIncluding > CostThresh)
2711 return false;
2712 }
2713 return true;
2714}
2715
2718 MachineBasicBlock *FBB,
2719 MachineBasicBlock *CurBB,
2720 MachineBasicBlock *SwitchBB,
2722 BranchProbability TProb,
2723 BranchProbability FProb,
2724 bool InvertCond) {
2725 // Skip over not part of the tree and remember to invert op and operands at
2726 // next level.
2727 Value *NotCond;
2728 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2729 InBlock(NotCond, CurBB->getBasicBlock())) {
2730 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2731 !InvertCond);
2732 return;
2733 }
2734
2736 const Value *BOpOp0, *BOpOp1;
2737 // Compute the effective opcode for Cond, taking into account whether it needs
2738 // to be inverted, e.g.
2739 // and (not (or A, B)), C
2740 // gets lowered as
2741 // and (and (not A, not B), C)
2743 if (BOp) {
2744 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2745 ? Instruction::And
2746 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2747 ? Instruction::Or
2749 if (InvertCond) {
2750 if (BOpc == Instruction::And)
2751 BOpc = Instruction::Or;
2752 else if (BOpc == Instruction::Or)
2753 BOpc = Instruction::And;
2754 }
2755 }
2756
2757 // If this node is not part of the or/and tree, emit it as a branch.
2758 // Note that all nodes in the tree should have same opcode.
2759 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2760 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2761 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2762 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2763 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2764 TProb, FProb, InvertCond);
2765 return;
2766 }
2767
2768 // Create TmpBB after CurBB.
2769 MachineFunction::iterator BBI(CurBB);
2770 MachineFunction &MF = DAG.getMachineFunction();
2772 CurBB->getParent()->insert(++BBI, TmpBB);
2773
2774 if (Opc == Instruction::Or) {
2775 // Codegen X | Y as:
2776 // BB1:
2777 // jmp_if_X TBB
2778 // jmp TmpBB
2779 // TmpBB:
2780 // jmp_if_Y TBB
2781 // jmp FBB
2782 //
2783
2784 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2785 // The requirement is that
2786 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2787 // = TrueProb for original BB.
2788 // Assuming the original probabilities are A and B, one choice is to set
2789 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2790 // A/(1+B) and 2B/(1+B). This choice assumes that
2791 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2792 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2793 // TmpBB, but the math is more complicated.
2794
2795 auto NewTrueProb = TProb / 2;
2796 auto NewFalseProb = TProb / 2 + FProb;
2797 // Emit the LHS condition.
2798 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2799 NewFalseProb, InvertCond);
2800
2801 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2802 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2804 // Emit the RHS condition into TmpBB.
2805 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2806 Probs[1], InvertCond);
2807 } else {
2808 assert(Opc == Instruction::And && "Unknown merge op!");
2809 // Codegen X & Y as:
2810 // BB1:
2811 // jmp_if_X TmpBB
2812 // jmp FBB
2813 // TmpBB:
2814 // jmp_if_Y TBB
2815 // jmp FBB
2816 //
2817 // This requires creation of TmpBB after CurBB.
2818
2819 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2820 // The requirement is that
2821 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2822 // = FalseProb for original BB.
2823 // Assuming the original probabilities are A and B, one choice is to set
2824 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2825 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2826 // TrueProb for BB1 * FalseProb for TmpBB.
2827
2828 auto NewTrueProb = TProb + FProb / 2;
2829 auto NewFalseProb = FProb / 2;
2830 // Emit the LHS condition.
2831 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2832 NewFalseProb, InvertCond);
2833
2834 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2835 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2837 // Emit the RHS condition into TmpBB.
2838 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2839 Probs[1], InvertCond);
2840 }
2841}
2842
2843/// If the set of cases should be emitted as a series of branches, return true.
2844/// If we should emit this as a bunch of and/or'd together conditions, return
2845/// false.
2846bool
2847SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2848 if (Cases.size() != 2) return true;
2849
2850 // If this is two comparisons of the same values or'd or and'd together, they
2851 // will get folded into a single comparison, so don't emit two blocks.
2852 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2853 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2854 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2855 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2856 return false;
2857 }
2858
2859 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2860 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2861 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2862 Cases[0].CC == Cases[1].CC &&
2863 isa<Constant>(Cases[0].CmpRHS) &&
2864 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2865 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2866 return false;
2867 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2868 return false;
2869 }
2870
2871 return true;
2872}
2873
2874void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2876
2877 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2878
2879 // Update machine-CFG edges.
2880 BrMBB->addSuccessor(Succ0MBB);
2881
2882 // If this is not a fall-through branch or optimizations are switched off,
2883 // emit the branch.
2884 if (Succ0MBB != NextBlock(BrMBB) ||
2886 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2887 DAG.getBasicBlock(Succ0MBB));
2888 setValue(&I, Br);
2889 DAG.setRoot(Br);
2890 }
2891}
2892
2893void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2894 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2895
2896 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2897
2898 // If this condition is one of the special cases we handle, do special stuff
2899 // now.
2900 const Value *CondVal = I.getCondition();
2901 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2902
2903 // If this is a series of conditions that are or'd or and'd together, emit
2904 // this as a sequence of branches instead of setcc's with and/or operations.
2905 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2906 // unpredictable branches, and vector extracts because those jumps are likely
2907 // expensive for any target), this should improve performance.
2908 // For example, instead of something like:
2909 // cmp A, B
2910 // C = seteq
2911 // cmp D, E
2912 // F = setle
2913 // or C, F
2914 // jnz foo
2915 // Emit:
2916 // cmp A, B
2917 // je foo
2918 // cmp D, E
2919 // jle foo
2920 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2921 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2922 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2923 BOp->hasOneUse() && !IsUnpredictable) {
2924 Value *Vec;
2925 const Value *BOp0, *BOp1;
2927 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2928 Opcode = Instruction::And;
2929 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2930 Opcode = Instruction::Or;
2931
2932 if (Opcode &&
2933 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2934 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2936 FuncInfo, I, Opcode, BOp0, BOp1,
2937 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2938 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2939 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2940 getEdgeProbability(BrMBB, Succ0MBB),
2941 getEdgeProbability(BrMBB, Succ1MBB),
2942 /*InvertCond=*/false);
2943 // If the compares in later blocks need to use values not currently
2944 // exported from this block, export them now. This block should always
2945 // be the first entry.
2946 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2947
2948 // Allow some cases to be rejected.
2949 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2950 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2951 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2952 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2953 }
2954
2955 // Emit the branch for this block.
2956 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2957 SL->SwitchCases.erase(SL->SwitchCases.begin());
2958 return;
2959 }
2960
2961 // Okay, we decided not to do this, remove any inserted MBB's and clear
2962 // SwitchCases.
2963 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2964 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2965
2966 SL->SwitchCases.clear();
2967 }
2968 }
2969
2970 // Create a CaseBlock record representing this branch.
2971 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2972 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2974 IsUnpredictable);
2975
2976 // Use visitSwitchCase to actually insert the fast branch sequence for this
2977 // cond branch.
2978 visitSwitchCase(CB, BrMBB);
2979}
2980
2981/// visitSwitchCase - Emits the necessary code to represent a single node in
2982/// the binary search tree resulting from lowering a switch instruction.
2984 MachineBasicBlock *SwitchBB) {
2985 SDValue Cond;
2986 SDValue CondLHS = getValue(CB.CmpLHS);
2987 SDLoc dl = CB.DL;
2988
2989 if (CB.CC == ISD::SETTRUE) {
2990 // Branch or fall through to TrueBB.
2991 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2992 SwitchBB->normalizeSuccProbs();
2993 if (CB.TrueBB != NextBlock(SwitchBB)) {
2994 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2995 DAG.getBasicBlock(CB.TrueBB)));
2996 }
2997 return;
2998 }
2999
3000 auto &TLI = DAG.getTargetLoweringInfo();
3001 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
3002
3003 // Build the setcc now.
3004 if (!CB.CmpMHS) {
3005 // Fold "(X == true)" to X and "(X == false)" to !X to
3006 // handle common cases produced by branch lowering.
3007 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
3008 CB.CC == ISD::SETEQ)
3009 Cond = CondLHS;
3010 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
3011 CB.CC == ISD::SETEQ) {
3012 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
3013 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
3014 } else {
3015 SDValue CondRHS = getValue(CB.CmpRHS);
3016
3017 // If a pointer's DAG type is larger than its memory type then the DAG
3018 // values are zero-extended. This breaks signed comparisons so truncate
3019 // back to the underlying type before doing the compare.
3020 if (CondLHS.getValueType() != MemVT) {
3021 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
3022 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
3023 }
3024 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
3025 }
3026 } else {
3027 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
3028
3029 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
3030 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
3031
3032 SDValue CmpOp = getValue(CB.CmpMHS);
3033 EVT VT = CmpOp.getValueType();
3034
3035 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
3036 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
3037 ISD::SETLE);
3038 } else {
3039 SDValue SUB = DAG.getNode(ISD::SUB, dl,
3040 VT, CmpOp, DAG.getConstant(Low, dl, VT));
3041 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
3042 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
3043 }
3044 }
3045
3046 // Update successor info
3047 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3048 // TrueBB and FalseBB are always different unless the incoming IR is
3049 // degenerate. This only happens when running llc on weird IR.
3050 if (CB.TrueBB != CB.FalseBB)
3051 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
3052 SwitchBB->normalizeSuccProbs();
3053
3054 // If the lhs block is the next block, invert the condition so that we can
3055 // fall through to the lhs instead of the rhs block.
3056 if (CB.TrueBB == NextBlock(SwitchBB)) {
3057 std::swap(CB.TrueBB, CB.FalseBB);
3058 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3059 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3060 }
3061
3062 SDNodeFlags Flags;
3064 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3065 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3066
3067 setValue(CurInst, BrCond);
3068
3069 // Insert the false branch. Do this even if it's a fall through branch,
3070 // this makes it easier to do DAG optimizations which require inverting
3071 // the branch condition.
3072 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3073 DAG.getBasicBlock(CB.FalseBB));
3074
3075 DAG.setRoot(BrCond);
3076}
3077
3078/// visitJumpTable - Emit JumpTable node in the current MBB
3080 // Emit the code for the jump table
3081 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3082 assert(JT.Reg && "Should lower JT Header first!");
3083 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3084 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3085 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3086 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3087 Index.getValue(1), Table, Index);
3088 DAG.setRoot(BrJumpTable);
3089}
3090
3091/// visitJumpTableHeader - This function emits necessary code to produce index
3092/// in the JumpTable from switch case.
3094 JumpTableHeader &JTH,
3095 MachineBasicBlock *SwitchBB) {
3096 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3097 const SDLoc &dl = *JT.SL;
3098
3099 // Subtract the lowest switch case value from the value being switched on.
3100 SDValue SwitchOp = getValue(JTH.SValue);
3101 EVT VT = SwitchOp.getValueType();
3102 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3103 DAG.getConstant(JTH.First, dl, VT));
3104
3105 // The SDNode we just created, which holds the value being switched on minus
3106 // the smallest case value, needs to be copied to a virtual register so it
3107 // can be used as an index into the jump table in a subsequent basic block.
3108 // This value may be smaller or larger than the target's pointer type, and
3109 // therefore require extension or truncating.
3110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3111 SwitchOp =
3112 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3113
3114 Register JumpTableReg =
3115 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3116 SDValue CopyTo =
3117 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3118 JT.Reg = JumpTableReg;
3119
3120 if (!JTH.FallthroughUnreachable) {
3121 // Emit the range check for the jump table, and branch to the default block
3122 // for the switch statement if the value being switched on exceeds the
3123 // largest case in the switch.
3124 SDValue CMP = DAG.getSetCC(
3125 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3126 Sub.getValueType()),
3127 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3128
3129 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3130 MVT::Other, CopyTo, CMP,
3131 DAG.getBasicBlock(JT.Default));
3132
3133 // Avoid emitting unnecessary branches to the next block.
3134 if (JT.MBB != NextBlock(SwitchBB))
3135 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3136 DAG.getBasicBlock(JT.MBB));
3137
3138 DAG.setRoot(BrCond);
3139 } else {
3140 // Avoid emitting unnecessary branches to the next block.
3141 if (JT.MBB != NextBlock(SwitchBB))
3142 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3143 DAG.getBasicBlock(JT.MBB)));
3144 else
3145 DAG.setRoot(CopyTo);
3146 }
3147}
3148
3149/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3150/// variable if there exists one.
3152 SDValue &Chain) {
3153 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3154 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3155 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3157 Value *Global =
3160 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3161 if (Global) {
3162 MachinePointerInfo MPInfo(Global);
3166 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3167 DAG.setNodeMemRefs(Node, {MemRef});
3168 }
3169 if (PtrTy != PtrMemTy)
3170 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3171 return SDValue(Node, 0);
3172}
3173
3174/// Codegen a new tail for a stack protector check ParentMBB which has had its
3175/// tail spliced into a stack protector check success bb.
3176///
3177/// For a high level explanation of how this fits into the stack protector
3178/// generation see the comment on the declaration of class
3179/// StackProtectorDescriptor.
3181 MachineBasicBlock *ParentBB) {
3182
3183 // First create the loads to the guard/stack slot for the comparison.
3184 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3185 auto &DL = DAG.getDataLayout();
3186 EVT PtrTy = TLI.getFrameIndexTy(DL);
3187 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3188
3189 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3190 int FI = MFI.getStackProtectorIndex();
3191
3192 SDValue Guard;
3193 SDLoc dl = getCurSDLoc();
3194 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3195 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3196 Align Align = DL.getPrefTypeAlign(
3197 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3198
3199 // Generate code to load the content of the guard slot.
3200 SDValue GuardVal = DAG.getLoad(
3201 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3202 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3204
3205 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3206 // original cookie for comparison. The prologue stored (FP - Cookie) or
3207 // (FP XOR Cookie), so we apply the same operation again to unmix:
3208 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3209 if (TLI.useStackGuardMixFP())
3210 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3211
3212 // If we're using function-based instrumentation, call the guard check
3213 // function
3215 // Get the guard check function from the target and verify it exists since
3216 // we're using function-based instrumentation
3217 const Function *GuardCheckFn =
3218 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3219 assert(GuardCheckFn && "Guard check function is null");
3220
3221 // The target provides a guard check function to validate the guard value.
3222 // Generate a call to that function with the content of the guard slot as
3223 // argument.
3224 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3225 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3226
3228 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3229 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3230 Entry.IsInReg = true;
3231 Args.push_back(Entry);
3232
3235 .setChain(DAG.getEntryNode())
3236 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3237 getValue(GuardCheckFn), std::move(Args));
3238
3239 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3240 DAG.setRoot(Result.second);
3241 return;
3242 }
3243
3244 // Load the fresh guard value for comparison.
3245 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3246 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3247 SDValue Chain = DAG.getEntryNode();
3248 if (TLI.useStackGuardMixFP()) {
3249 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3250 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3251 SDValue GuardPtr = getValue(IRGuard);
3252 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3253 MachinePointerInfo(IRGuard, 0), Align,
3255 } else {
3256 LLVMContext &Ctx = *DAG.getContext();
3257 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3258 Guard = DAG.getPOISON(PtrMemTy);
3259 }
3260 } else {
3261 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3262 if (TLI.useLoadStackGuardNode(M)) {
3263 Guard = getLoadStackGuard(DAG, dl, Chain);
3264 } else {
3265 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3266 SDValue GuardPtr = getValue(IRGuard);
3267 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3268 MachinePointerInfo(IRGuard, 0), Align,
3270 } else {
3271 LLVMContext &Ctx = *DAG.getContext();
3272 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3273 Guard = DAG.getPOISON(PtrMemTy);
3274 }
3275 }
3276 }
3277
3278 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3279 // contain unmixed cookie values that can be compared directly.
3280
3281 // Perform the comparison via a getsetcc.
3282 SDValue Cmp = DAG.getSetCC(
3283 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3284 Guard, GuardVal, ISD::SETNE);
3285
3286 // If the guard/stackslot do not equal, branch to failure MBB.
3287 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3288 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3289 // Otherwise branch to success MBB.
3290 SDValue Br = DAG.getNode(ISD::BR, dl,
3291 MVT::Other, BrCond,
3292 DAG.getBasicBlock(SPD.getSuccessMBB()));
3293
3294 DAG.setRoot(Br);
3295}
3296
3297/// Codegen the failure basic block for a stack protector check.
3298///
3299/// A failure stack protector machine basic block consists simply of a call to
3300/// __stack_chk_fail().
3301///
3302/// For a high level explanation of how this fits into the stack protector
3303/// generation see the comment on the declaration of class
3304/// StackProtectorDescriptor.
3307
3308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3309 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3310 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3311 SDValue Chain;
3312
3313 // For -Oz builds with a guard check function, we use function-based
3314 // instrumentation. Otherwise, if we have a guard check function, we call it
3315 // in the failure block.
3316 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3317 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3318 // First create the loads to the guard/stack slot for the comparison.
3319 auto &DL = DAG.getDataLayout();
3320 EVT PtrTy = TLI.getFrameIndexTy(DL);
3321 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3322
3323 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3324 int FI = MFI.getStackProtectorIndex();
3325
3326 SDLoc dl = getCurSDLoc();
3327 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3328 Align Align = DL.getPrefTypeAlign(
3329 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3330
3331 // Generate code to load the content of the guard slot.
3332 SDValue GuardVal = DAG.getLoad(
3333 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3334 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3336
3337 if (TLI.useStackGuardMixFP())
3338 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3339
3340 // The target provides a guard check function to validate the guard value.
3341 // Generate a call to that function with the content of the guard slot as
3342 // argument.
3343 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3344 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3345
3347 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3348 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3349 Entry.IsInReg = true;
3350 Args.push_back(Entry);
3351
3354 .setChain(DAG.getEntryNode())
3355 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3356 getValue(GuardCheckFn), std::move(Args));
3357
3358 Chain = TLI.LowerCallTo(CLI).second;
3359 } else {
3361 CallOptions.setDiscardResult(true);
3362 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3363 {}, CallOptions, getCurSDLoc())
3364 .second;
3365 }
3366
3367 // Emit a trap instruction if we are required to do so.
3368 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3369 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3370 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3371
3372 DAG.setRoot(Chain);
3373}
3374
3375/// visitBitTestHeader - This function emits necessary code to produce value
3376/// suitable for "bit tests"
3378 MachineBasicBlock *SwitchBB) {
3379 SDLoc dl = getCurSDLoc();
3380
3381 // Subtract the minimum value.
3382 SDValue SwitchOp = getValue(B.SValue);
3383 EVT VT = SwitchOp.getValueType();
3384 SDValue RangeSub =
3385 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3386
3387 // Determine the type of the test operands.
3388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3389 bool UsePtrType = false;
3390 if (!TLI.isTypeLegal(VT)) {
3391 UsePtrType = true;
3392 } else {
3393 for (const BitTestCase &Case : B.Cases)
3394 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3395 // Switch table case range are encoded into series of masks.
3396 // Just use pointer type, it's guaranteed to fit.
3397 UsePtrType = true;
3398 break;
3399 }
3400 }
3401 SDValue Sub = RangeSub;
3402 if (UsePtrType) {
3403 VT = TLI.getPointerTy(DAG.getDataLayout());
3404 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3405 }
3406
3407 B.RegVT = VT.getSimpleVT();
3408 B.Reg = FuncInfo.CreateReg(B.RegVT);
3409 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3410
3411 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3412
3413 if (!B.FallthroughUnreachable)
3414 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3415 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3416 SwitchBB->normalizeSuccProbs();
3417
3418 SDValue Root = CopyTo;
3419 if (!B.FallthroughUnreachable) {
3420 // Conditional branch to the default block.
3421 SDValue RangeCmp = DAG.getSetCC(dl,
3422 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3423 RangeSub.getValueType()),
3424 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3425 ISD::SETUGT);
3426
3427 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3428 DAG.getBasicBlock(B.Default));
3429 }
3430
3431 // Avoid emitting unnecessary branches to the next block.
3432 if (MBB != NextBlock(SwitchBB))
3433 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3434
3435 DAG.setRoot(Root);
3436}
3437
3438/// visitBitTestCase - this function produces one "bit test"
3440 MachineBasicBlock *NextMBB,
3441 BranchProbability BranchProbToNext,
3442 Register Reg, BitTestCase &B,
3443 MachineBasicBlock *SwitchBB) {
3444 SDLoc dl = getCurSDLoc();
3445 MVT VT = BB.RegVT;
3446 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3447 SDValue Cmp;
3448 unsigned PopCount = llvm::popcount(B.Mask);
3449 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3450 if (PopCount == 1) {
3451 // Testing for a single bit; just compare the shift count with what it
3452 // would need to be to shift a 1 bit in that position.
3453 Cmp = DAG.getSetCC(
3454 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3455 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3456 ISD::SETEQ);
3457 } else if (PopCount == BB.Range) {
3458 // There is only one zero bit in the range, test for it directly.
3459 Cmp = DAG.getSetCC(
3460 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3461 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3462 } else {
3463 // Make desired shift
3464 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3465 DAG.getConstant(1, dl, VT), ShiftOp);
3466
3467 // Emit bit tests and jumps
3468 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3469 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3470 Cmp = DAG.getSetCC(
3471 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3472 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3473 }
3474
3475 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3476 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3477 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3478 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3479 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3480 // one as they are relative probabilities (and thus work more like weights),
3481 // and hence we need to normalize them to let the sum of them become one.
3482 SwitchBB->normalizeSuccProbs();
3483
3484 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3485 MVT::Other, getControlRoot(),
3486 Cmp, DAG.getBasicBlock(B.TargetBB));
3487
3488 // Avoid emitting unnecessary branches to the next block.
3489 if (NextMBB != NextBlock(SwitchBB))
3490 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3491 DAG.getBasicBlock(NextMBB));
3492
3493 DAG.setRoot(BrAnd);
3494}
3495
3496void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3497 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3498
3499 // Retrieve successors. Look through artificial IR level blocks like
3500 // catchswitch for successors.
3501 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3502 const BasicBlock *EHPadBB = I.getSuccessor(1);
3503 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3504
3505 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3506 // have to do anything here to lower funclet bundles.
3507 failForInvalidBundles(I, "invokes",
3513
3514 const Value *Callee(I.getCalledOperand());
3515 const Function *Fn = dyn_cast<Function>(Callee);
3516 if (isa<InlineAsm>(Callee))
3517 visitInlineAsm(I, EHPadBB);
3518 else if (Fn && Fn->isIntrinsic()) {
3519 switch (Fn->getIntrinsicID()) {
3520 default:
3521 llvm_unreachable("Cannot invoke this intrinsic");
3522 case Intrinsic::donothing:
3523 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3524 case Intrinsic::seh_try_begin:
3525 case Intrinsic::seh_scope_begin:
3526 case Intrinsic::seh_try_end:
3527 case Intrinsic::seh_scope_end:
3528 if (EHPadMBB)
3529 // a block referenced by EH table
3530 // so dtor-funclet not removed by opts
3531 EHPadMBB->setMachineBlockAddressTaken();
3532 break;
3533 case Intrinsic::experimental_patchpoint_void:
3534 case Intrinsic::experimental_patchpoint:
3535 visitPatchpoint(I, EHPadBB);
3536 break;
3537 case Intrinsic::experimental_gc_statepoint:
3539 break;
3540 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3541 // but these intrinsics are special because they can be invoked, so we
3542 // manually lower it to a DAG node here.
3543 case Intrinsic::wasm_throw: {
3545 std::array<SDValue, 4> Ops = {
3546 getControlRoot(), // inchain for the terminator node
3547 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3549 getValue(I.getArgOperand(0)), // tag
3550 getValue(I.getArgOperand(1)) // thrown value
3551 };
3552 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3553 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3554 break;
3555 }
3556 case Intrinsic::wasm_rethrow: {
3557 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558 std::array<SDValue, 2> Ops = {
3559 getControlRoot(), // inchain for the terminator node
3560 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3561 TLI.getPointerTy(DAG.getDataLayout()))};
3562 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3563 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3564 break;
3565 }
3566 }
3567 } else if (I.hasDeoptState()) {
3568 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3569 // Eventually we will support lowering the @llvm.experimental.deoptimize
3570 // intrinsic, and right now there are no plans to support other intrinsics
3571 // with deopt state.
3572 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3573 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3575 } else {
3576 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3577 }
3578
3579 // If the value of the invoke is used outside of its defining block, make it
3580 // available as a virtual register.
3581 // We already took care of the exported value for the statepoint instruction
3582 // during call to the LowerStatepoint.
3583 if (!isa<GCStatepointInst>(I)) {
3585 }
3586
3588 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3589 BranchProbability EHPadBBProb =
3590 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3592 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3593
3594 // Update successor info.
3595 addSuccessorWithProb(InvokeMBB, Return);
3596 for (auto &UnwindDest : UnwindDests) {
3597 UnwindDest.first->setIsEHPad();
3598 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3599 }
3600 InvokeMBB->normalizeSuccProbs();
3601
3602 // Drop into normal successor.
3603 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3604 DAG.getBasicBlock(Return)));
3605}
3606
3607/// The intrinsics currently supported by callbr are implicit control flow
3608/// intrinsics such as amdgcn.kill.
3609/// - they should be called (no "dontcall-" attributes)
3610/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3611/// - they do not need custom argument handling (no
3612/// TLI.CollectTargetIntrinsicOperands())
3613void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3614#ifndef NDEBUG
3616 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3617 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3618 assert(Infos.empty() && "Intrinsic touches memory");
3619#endif
3620
3621 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3622
3624 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3625 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3626
3627 // Create the node.
3628 SDValue Result =
3629 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3630 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3631
3632 setValue(&I, Result);
3633}
3634
3635void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3636 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3637
3638 if (I.isInlineAsm()) {
3639 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3640 // have to do anything here to lower funclet bundles.
3641 failForInvalidBundles(I, "callbrs",
3643 visitInlineAsm(I);
3644 } else {
3645 assert(!I.hasOperandBundles() &&
3646 "Can't have operand bundles for intrinsics");
3647 visitCallBrIntrinsic(I);
3648 }
3650
3651 // Retrieve successors.
3652 SmallPtrSet<BasicBlock *, 8> Dests;
3653 Dests.insert(I.getDefaultDest());
3654 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3655
3656 // Update successor info.
3657 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3658 // TODO: For most of the cases where there is an intrinsic callbr, we're
3659 // having exactly one indirect target, which will be unreachable. As soon as
3660 // this changes, we might need to enhance
3661 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3662 // intrinsic indirect branches.
3663 if (I.isInlineAsm()) {
3664 for (BasicBlock *Dest : I.getIndirectDests()) {
3665 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3666 Target->setIsInlineAsmBrIndirectTarget();
3667 // If we introduce a type of asm goto statement that is permitted to use
3668 // an indirect call instruction to jump to its labels, then we should add
3669 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3670 // target block as requiring a BTI.
3671
3672 Target->setLabelMustBeEmitted();
3673 // Don't add duplicate machine successors.
3674 if (Dests.insert(Dest).second)
3675 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3676 }
3677 }
3678 CallBrMBB->normalizeSuccProbs();
3679
3680 // Drop into default successor.
3681 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3682 MVT::Other, getControlRoot(),
3683 DAG.getBasicBlock(Return)));
3684}
3685
3686void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3687 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3688}
3689
3690void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3691 assert(FuncInfo.MBB->isEHPad() &&
3692 "Call to landingpad not in landing pad!");
3693
3694 // If there aren't registers to copy the values into (e.g., during SjLj
3695 // exceptions), then don't bother to create these DAG nodes.
3696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3697 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3698 if (TLI.getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn) ==
3699 0 &&
3700 TLI.getExceptionSelectorRegister(FuncInfo.ExceptionModel,
3701 PersonalityFn) == 0)
3702 return;
3703
3704 // If landingpad's return type is token type, we don't create DAG nodes
3705 // for its exception pointer and selector value. The extraction of exception
3706 // pointer or selector value from token type landingpads is not currently
3707 // supported.
3708 if (LP.getType()->isTokenTy())
3709 return;
3710
3711 // LangRef leaves the result type target-specific, so diagnose types this
3712 // lowering cannot represent instead of asserting.
3713 SDLoc dl = getCurSDLoc();
3715 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3716 *LP.getFunction(),
3717 "landingpad result type must be a struct of an exception pointer and "
3718 "an integer selector",
3719 dl.getDebugLoc()));
3720 setValueToPoison(&LP, dl);
3721 return;
3722 }
3723
3724 SmallVector<EVT, 2> ValueVTs;
3725 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3726 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3727
3728 // Get the two live-in registers as SDValues. The physregs have already been
3729 // copied into virtual registers.
3730 SDValue Ops[2];
3731 if (FuncInfo.ExceptionPointerVirtReg) {
3732 Ops[0] = DAG.getZExtOrTrunc(
3733 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3734 FuncInfo.ExceptionPointerVirtReg,
3735 TLI.getPointerTy(DAG.getDataLayout())),
3736 dl, ValueVTs[0]);
3737 } else {
3738 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3739 }
3740 Ops[1] = DAG.getZExtOrTrunc(
3741 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3742 FuncInfo.ExceptionSelectorVirtReg,
3743 TLI.getPointerTy(DAG.getDataLayout())),
3744 dl, ValueVTs[1]);
3745
3746 // Merge into one.
3747 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3748 DAG.getVTList(ValueVTs), Ops);
3749 setValue(&LP, Res);
3750}
3751
3754 // Update JTCases.
3755 for (JumpTableBlock &JTB : SL->JTCases)
3756 if (JTB.first.HeaderBB == First)
3757 JTB.first.HeaderBB = Last;
3758
3759 // Update BitTestCases.
3760 for (BitTestBlock &BTB : SL->BitTestCases)
3761 if (BTB.Parent == First)
3762 BTB.Parent = Last;
3763}
3764
3765void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3766 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3767
3768 // Update machine-CFG edges with unique successors.
3770 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3771 BasicBlock *BB = I.getSuccessor(i);
3772 bool Inserted = Done.insert(BB).second;
3773 if (!Inserted)
3774 continue;
3775
3776 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3777 addSuccessorWithProb(IndirectBrMBB, Succ);
3778 }
3779 IndirectBrMBB->normalizeSuccProbs();
3780
3782 MVT::Other, getControlRoot(),
3783 getValue(I.getAddress())));
3784}
3785
3786void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3787 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3788 DAG.getTarget().Options.NoTrapAfterNoreturn))
3789 return;
3790
3791 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3792}
3793
3794void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3795 SDNodeFlags Flags;
3796 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3797 Flags.copyFMF(*FPOp);
3798
3799 SDValue Op = getValue(I.getOperand(0));
3800 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3801 Op, Flags);
3802 setValue(&I, UnNodeValue);
3803}
3804
3805void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3806 SDNodeFlags Flags;
3807 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3808 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3809 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3810 }
3811 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3812 Flags.setExact(ExactOp->isExact());
3813 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3814 Flags.setDisjoint(DisjointOp->isDisjoint());
3815 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3816 Flags.copyFMF(*FPOp);
3817
3818 SDValue Op1 = getValue(I.getOperand(0));
3819 SDValue Op2 = getValue(I.getOperand(1));
3820 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3821 Op1, Op2, Flags);
3822 setValue(&I, BinNodeValue);
3823}
3824
3825void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3826 SDValue Op1 = getValue(I.getOperand(0));
3827 SDValue Op2 = getValue(I.getOperand(1));
3828
3829 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3830 Op1.getValueType(), DAG.getDataLayout());
3831
3832 // Coerce the shift amount to the right type if we can. This exposes the
3833 // truncate or zext to optimization early.
3834 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3836 "Unexpected shift type");
3837 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3838 }
3839
3840 bool nuw = false;
3841 bool nsw = false;
3842 bool exact = false;
3843
3844 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3845
3846 if (const OverflowingBinaryOperator *OFBinOp =
3848 nuw = OFBinOp->hasNoUnsignedWrap();
3849 nsw = OFBinOp->hasNoSignedWrap();
3850 }
3851 if (const PossiblyExactOperator *ExactOp =
3853 exact = ExactOp->isExact();
3854 }
3855 SDNodeFlags Flags;
3856 Flags.setExact(exact);
3857 Flags.setNoSignedWrap(nsw);
3858 Flags.setNoUnsignedWrap(nuw);
3859 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3860 Flags);
3861 setValue(&I, Res);
3862}
3863
3864void SelectionDAGBuilder::visitSDiv(const User &I) {
3865 SDValue Op1 = getValue(I.getOperand(0));
3866 SDValue Op2 = getValue(I.getOperand(1));
3867
3868 SDNodeFlags Flags;
3869 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3870 cast<PossiblyExactOperator>(&I)->isExact());
3871 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3872 Op2, Flags));
3873}
3874
3875void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3876 ICmpInst::Predicate predicate = I.getPredicate();
3877 SDValue Op1 = getValue(I.getOperand(0));
3878 SDValue Op2 = getValue(I.getOperand(1));
3879 ISD::CondCode Opcode = getICmpCondCode(predicate);
3880
3881 auto &TLI = DAG.getTargetLoweringInfo();
3882 EVT MemVT =
3883 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3884
3885 // If a pointer's DAG type is larger than its memory type then the DAG values
3886 // are zero-extended. This breaks signed comparisons so truncate back to the
3887 // underlying type before doing the compare.
3888 if (Op1.getValueType() != MemVT) {
3889 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3890 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3891 }
3892
3893 SDNodeFlags Flags;
3894 Flags.setSameSign(I.hasSameSign());
3895
3896 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3897 I.getType());
3898 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3899 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3900}
3901
3902void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3903 FCmpInst::Predicate predicate = I.getPredicate();
3904 SDValue Op1 = getValue(I.getOperand(0));
3905 SDValue Op2 = getValue(I.getOperand(1));
3906
3907 ISD::CondCode Condition = getFCmpCondCode(predicate);
3908 auto *FPMO = cast<FPMathOperator>(&I);
3909 if (FPMO->hasNoNaNs() ||
3910 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3911 Condition = getFCmpCodeWithoutNaN(Condition);
3912
3913 SDNodeFlags Flags;
3914 Flags.copyFMF(*FPMO);
3915
3916 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3917 I.getType());
3918 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3919 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3920}
3921
3922// Check if the condition of the select has one use or two users that are both
3923// selects with the same condition.
3924static bool hasOnlySelectUsers(const Value *Cond) {
3925 return llvm::all_of(Cond->users(), [](const Value *V) {
3926 return isa<SelectInst>(V);
3927 });
3928}
3929
3930void SelectionDAGBuilder::visitSelect(const User &I) {
3931 SmallVector<EVT, 4> ValueVTs;
3932 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3933 ValueVTs);
3934 unsigned NumValues = ValueVTs.size();
3935 if (NumValues == 0) return;
3936
3938 SDValue Cond = getValue(I.getOperand(0));
3939 SDValue LHSVal = getValue(I.getOperand(1));
3940 SDValue RHSVal = getValue(I.getOperand(2));
3941 SmallVector<SDValue, 1> BaseOps(1, Cond);
3943 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3944
3945 bool IsUnaryAbs = false;
3946 bool Negate = false;
3947
3948 SDNodeFlags Flags;
3949 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3950 Flags.copyFMF(*FPOp);
3951
3952 Flags.setUnpredictable(
3953 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3954
3955 // Min/max matching is only viable if all output VTs are the same.
3956 if (all_equal(ValueVTs)) {
3957 EVT VT = ValueVTs[0];
3958 LLVMContext &Ctx = *DAG.getContext();
3959 auto &TLI = DAG.getTargetLoweringInfo();
3960
3961 // We care about the legality of the operation after it has been type
3962 // legalized.
3963 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3964 VT = TLI.getTypeToTransformTo(Ctx, VT);
3965
3966 // If the vselect is legal, assume we want to leave this as a vector setcc +
3967 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3968 // min/max is legal on the scalar type.
3969 bool UseScalarMinMax = VT.isVector() &&
3971
3972 // ValueTracking's select pattern matching does not account for -0.0,
3973 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3974 // -0.0 is less than +0.0.
3975 const Value *LHS, *RHS;
3976 auto SPR = matchSelectPattern(&I, LHS, RHS);
3978 switch (SPR.Flavor) {
3979 case SPF_UMAX: Opc = ISD::UMAX; break;
3980 case SPF_UMIN: Opc = ISD::UMIN; break;
3981 case SPF_SMAX: Opc = ISD::SMAX; break;
3982 case SPF_SMIN: Opc = ISD::SMIN; break;
3983 case SPF_FMINNUM:
3985 break;
3986
3987 switch (SPR.NaNBehavior) {
3988 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3989 case SPNB_RETURNS_ANY:
3990 case SPNB_RETURNS_NAN:
3991 break;
3992 case SPNB_RETURNS_OTHER:
3994 Flags.setNoSignedZeros(true);
3995 break;
3996 }
3997 break;
3998 case SPF_FMAXNUM:
4000 break;
4001
4002 switch (SPR.NaNBehavior) {
4003 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4004 case SPNB_RETURNS_NAN:
4005 case SPNB_RETURNS_ANY:
4006 break;
4007 case SPNB_RETURNS_OTHER:
4009 Flags.setNoSignedZeros(true);
4010 break;
4011 }
4012 break;
4013 case SPF_NABS:
4014 Negate = true;
4015 [[fallthrough]];
4016 case SPF_ABS:
4017 IsUnaryAbs = true;
4018 Opc = ISD::ABS;
4019 break;
4020 default: break;
4021 }
4022
4023 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
4024 (TLI.isOperationLegalOrCustom(Opc, VT) ||
4025 (UseScalarMinMax &&
4027 // If the underlying comparison instruction is used by any other
4028 // instruction, the consumed instructions won't be destroyed, so it is
4029 // not profitable to convert to a min/max.
4031 OpCode = Opc;
4032 LHSVal = getValue(LHS);
4033 RHSVal = getValue(RHS);
4034 BaseOps.clear();
4035 }
4036
4037 if (IsUnaryAbs) {
4038 OpCode = Opc;
4039 LHSVal = getValue(LHS);
4040 BaseOps.clear();
4041 }
4042 }
4043
4044 if (IsUnaryAbs) {
4045 for (unsigned i = 0; i != NumValues; ++i) {
4046 SDLoc dl = getCurSDLoc();
4047 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
4048 Values[i] =
4049 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
4050 if (Negate)
4051 Values[i] = DAG.getNegative(Values[i], dl, VT);
4052 }
4053 } else {
4054 for (unsigned i = 0; i != NumValues; ++i) {
4055 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
4056 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
4057 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
4058 Values[i] = DAG.getNode(
4059 OpCode, getCurSDLoc(),
4060 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
4061 }
4062 }
4063
4065 DAG.getVTList(ValueVTs), Values));
4066}
4067
4068void SelectionDAGBuilder::visitTrunc(const User &I) {
4069 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4070 SDValue N = getValue(I.getOperand(0));
4071 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4072 I.getType());
4073 SDNodeFlags Flags;
4074 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4075 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4076 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4077 }
4078
4079 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4080}
4081
4082void SelectionDAGBuilder::visitZExt(const User &I) {
4083 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4084 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4085 SDValue N = getValue(I.getOperand(0));
4086 auto &TLI = DAG.getTargetLoweringInfo();
4087 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4088
4089 SDNodeFlags Flags;
4090 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4091 Flags.setNonNeg(PNI->hasNonNeg());
4092
4093 // Eagerly use nonneg information to canonicalize towards sign_extend if
4094 // that is the target's preference.
4095 // TODO: Let the target do this later.
4096 if (Flags.hasNonNeg() &&
4097 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4098 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4099 return;
4100 }
4101
4102 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4103}
4104
4105void SelectionDAGBuilder::visitSExt(const User &I) {
4106 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4107 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4108 SDValue N = getValue(I.getOperand(0));
4109 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4110 I.getType());
4111 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4112}
4113
4114void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4115 // FPTrunc is never a no-op cast, no need to check
4116 SDValue N = getValue(I.getOperand(0));
4117 SDLoc dl = getCurSDLoc();
4118 SDNodeFlags Flags;
4119 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4120 Flags.copyFMF(*FPOp);
4121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4122 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4123 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4124 DAG.getTargetConstant(
4125 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4126 Flags));
4127}
4128
4129void SelectionDAGBuilder::visitFPExt(const User &I) {
4130 // FPExt is never a no-op cast, no need to check
4131 SDValue N = getValue(I.getOperand(0));
4132 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4133 I.getType());
4134 SDNodeFlags Flags;
4135 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4136 Flags.copyFMF(*FPOp);
4137 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4138}
4139
4140void SelectionDAGBuilder::visitFPToUI(const User &I) {
4141 // FPToUI is never a no-op cast, no need to check
4142 SDValue N = getValue(I.getOperand(0));
4143 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4144 I.getType());
4145 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4146}
4147
4148void SelectionDAGBuilder::visitFPToSI(const User &I) {
4149 // FPToSI is never a no-op cast, no need to check
4150 SDValue N = getValue(I.getOperand(0));
4151 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4152 I.getType());
4153 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4154}
4155
4156void SelectionDAGBuilder::visitUIToFP(const User &I) {
4157 // UIToFP is never a no-op cast, no need to check
4158 SDValue N = getValue(I.getOperand(0));
4159 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4160 I.getType());
4161 SDNodeFlags Flags;
4162 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4163 Flags.copyFMF(*cast<FPMathOperator>(&I));
4164
4165 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4166}
4167
4168void SelectionDAGBuilder::visitSIToFP(const User &I) {
4169 // SIToFP is never a no-op cast, no need to check
4170 SDValue N = getValue(I.getOperand(0));
4171 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4172 I.getType());
4173 SDNodeFlags Flags;
4174 Flags.copyFMF(*cast<FPMathOperator>(&I));
4175
4176 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4177}
4178
4179void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4180 SDValue N = getValue(I.getOperand(0));
4181 // By definition the type of the ptrtoaddr must be equal to the address type.
4182 const auto &TLI = DAG.getTargetLoweringInfo();
4183 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4184 // The address width must be smaller or equal to the pointer representation
4185 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4186 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4187 setValue(&I, N);
4188}
4189
4190void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4191 // What to do depends on the size of the integer and the size of the pointer.
4192 // We can either truncate, zero extend, or no-op, accordingly.
4193 SDValue N = getValue(I.getOperand(0));
4194 auto &TLI = DAG.getTargetLoweringInfo();
4195 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4196 I.getType());
4197 EVT PtrMemVT =
4198 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4199 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4200 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4201 setValue(&I, N);
4202}
4203
4204void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4205 // What to do depends on the size of the integer and the size of the pointer.
4206 // We can either truncate, zero extend, or no-op, accordingly.
4207 SDValue N = getValue(I.getOperand(0));
4208 auto &TLI = DAG.getTargetLoweringInfo();
4209 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4210 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4211 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4212 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4213 setValue(&I, N);
4214}
4215
4216void SelectionDAGBuilder::visitBitCast(const User &I) {
4217 SDValue N = getValue(I.getOperand(0));
4218 SDLoc dl = getCurSDLoc();
4219 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4220 I.getType());
4221
4222 // BitCast assures us that source and destination are the same size so this is
4223 // either a BITCAST or a no-op.
4224 if (DestVT != N.getValueType())
4225 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4226 DestVT, N)); // convert types.
4227 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4228 // might fold any kind of constant expression to an integer constant and that
4229 // is not what we are looking for. Only recognize a bitcast of a genuine
4230 // constant integer as an opaque constant.
4231 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4232 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4233 /*isOpaque*/true));
4234 else
4235 setValue(&I, N); // noop cast.
4236}
4237
4238void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4239 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4240 const Value *SV = I.getOperand(0);
4241 SDValue N = getValue(SV);
4242 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4243
4244 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4245 unsigned DestAS = I.getType()->getPointerAddressSpace();
4246
4247 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(), SrcAS, DestAS)) {
4248 SDNodeFlags Flags;
4249 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4250 Flags.setNonNull(ASC->hasNonNull());
4251 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4252 }
4253
4254 setValue(&I, N);
4255}
4256
4257void SelectionDAGBuilder::visitInsertElement(const User &I) {
4258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4259 SDValue InVec = getValue(I.getOperand(0));
4260 SDValue InVal = getValue(I.getOperand(1));
4261 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4262 TLI.getVectorIdxTy(DAG.getDataLayout()));
4264 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4265 InVec, InVal, InIdx));
4266}
4267
4268void SelectionDAGBuilder::visitBitInsert(const User &I) {
4269 SDValue Base = getValue(I.getOperand(0));
4270 SDValue Val = getValue(I.getOperand(1));
4271 SDValue Offset = getValue(I.getOperand(2));
4272 EVT BaseVT = Base.getValueType();
4273 EVT ValVT = Val.getValueType();
4274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4275 SDLoc dl = getCurSDLoc();
4276
4277 assert(BaseVT.getSizeInBits() >= ValVT.getSizeInBits() &&
4278 "bitinsert val wider than base should be rejected by verifier");
4279
4280 // If Val is a float, cast it to an integer of the same bitwidth
4281 // so DAG.getZExtOrTrunc can process it safely.
4282 if (!ValVT.isInteger()) {
4283 ValVT = ValVT.changeTypeToInteger();
4284 Val = DAG.getBitcast(ValVT, Val);
4285 }
4286
4287 // Legalize shift amount to the target's shift amount type.
4288 EVT ShiftAmtTy = TLI.getShiftAmountTy(BaseVT, DAG.getDataLayout());
4289 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4290
4291 unsigned BaseBitWidth = BaseVT.getScalarSizeInBits();
4292 unsigned ValBitWidth = ValVT.getScalarSizeInBits();
4293 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4294 SDValue ShiftedMask =
4295 DAG.getNode(ISD::SHL, dl, BaseVT, DAG.getConstant(InsertMask, dl, BaseVT),
4296 LegalShiftAmount);
4297 SDValue ClearMask = DAG.getNOT(dl, ShiftedMask, BaseVT);
4298 SDValue ClearedBase = DAG.getNode(ISD::AND, dl, BaseVT, Base, ClearMask);
4299
4300 SDValue ExtVal = DAG.getZExtOrTrunc(Val, dl, BaseVT);
4301 SDValue ShiftedVal =
4302 DAG.getNode(ISD::SHL, dl, BaseVT, ExtVal, LegalShiftAmount);
4303 SDValue Result = DAG.getNode(ISD::OR, dl, BaseVT, ClearedBase, ShiftedVal);
4304 setValue(&I, Result);
4305}
4306
4307void SelectionDAGBuilder::visitBitExtract(const User &I) {
4308 SDValue Src = getValue(I.getOperand(0));
4309 SDValue Offset = getValue(I.getOperand(1));
4310 EVT SrcVT = Src.getValueType();
4311 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4312 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4313 SDLoc dl = getCurSDLoc();
4314
4315 assert(ResultVT.getSizeInBits() <= SrcVT.getSizeInBits() &&
4316 "bitextract result wider than source should be rejected by verifier");
4317
4318 // Legalize shift amount to the target's shift amount type.
4319 EVT ShiftAmtTy = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
4320 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4321
4322 // Shift right by Offset - brings target field to bit 0
4323 SDValue Shifted = DAG.getNode(ISD::SRL, dl, SrcVT, Src, LegalShiftAmount);
4324
4325 SDValue Result;
4326 if (!ResultVT.isInteger()) {
4327 // Drop into the integer domain to safely truncate the shifted bits
4328 EVT IntResultVT = ResultVT.changeTypeToInteger();
4329 Result = DAG.getNode(ISD::TRUNCATE, dl, IntResultVT, Shifted);
4330 Result = DAG.getBitcast(ResultVT, Result);
4331 } else {
4332 // Normal integer path
4333 Result = DAG.getNode(ISD::TRUNCATE, dl, ResultVT, Shifted);
4334 }
4335
4336 setValue(&I, Result);
4337}
4338
4339void SelectionDAGBuilder::visitExtractElement(const User &I) {
4340 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4341 SDValue InVec = getValue(I.getOperand(0));
4342 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4343 TLI.getVectorIdxTy(DAG.getDataLayout()));
4345 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4346 InVec, InIdx));
4347}
4348
4349void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4350 SDValue Src1 = getValue(I.getOperand(0));
4351 SDValue Src2 = getValue(I.getOperand(1));
4352 ArrayRef<int> Mask;
4353 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4354 Mask = SVI->getShuffleMask();
4355 else
4356 Mask = cast<ConstantExpr>(I).getShuffleMask();
4357 SDLoc DL = getCurSDLoc();
4358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4359 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4360 EVT SrcVT = Src1.getValueType();
4361
4362 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4363 // Canonical splat form of first element of first input vector.
4364 SDValue FirstElt =
4365 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4366 DAG.getVectorIdxConstant(0, DL));
4367 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4368 return;
4369 }
4370
4371 // For now, we only handle splats for scalable vectors.
4372 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4373 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4374 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4375
4376 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4377 unsigned MaskNumElts = Mask.size();
4378
4379 if (SrcNumElts == MaskNumElts) {
4380 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4381 return;
4382 }
4383
4384 // Normalize the shuffle vector since mask and vector length don't match.
4385 if (SrcNumElts < MaskNumElts) {
4386 // Mask is longer than the source vectors. We can use concatenate vector to
4387 // make the mask and vectors lengths match.
4388
4389 if (MaskNumElts % SrcNumElts == 0) {
4390 // Mask length is a multiple of the source vector length.
4391 // Check if the shuffle is some kind of concatenation of the input
4392 // vectors.
4393 unsigned NumConcat = MaskNumElts / SrcNumElts;
4394 bool IsConcat = true;
4395 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4396 for (unsigned i = 0; i != MaskNumElts; ++i) {
4397 int Idx = Mask[i];
4398 if (Idx < 0)
4399 continue;
4400 // Ensure the indices in each SrcVT sized piece are sequential and that
4401 // the same source is used for the whole piece.
4402 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4403 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4404 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4405 IsConcat = false;
4406 break;
4407 }
4408 // Remember which source this index came from.
4409 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4410 }
4411
4412 // The shuffle is concatenating multiple vectors together. Just emit
4413 // a CONCAT_VECTORS operation.
4414 if (IsConcat) {
4415 SmallVector<SDValue, 8> ConcatOps;
4416 for (auto Src : ConcatSrcs) {
4417 if (Src < 0)
4418 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4419 else if (Src == 0)
4420 ConcatOps.push_back(Src1);
4421 else
4422 ConcatOps.push_back(Src2);
4423 }
4424 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4425 return;
4426 }
4427 }
4428
4429 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4430 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4431 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4432 PaddedMaskNumElts);
4433
4434 // Pad both vectors with undefs to make them the same length as the mask.
4435 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4436
4437 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4438 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4439 MOps1[0] = Src1;
4440 MOps2[0] = Src2;
4441
4442 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4443 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4444
4445 // Readjust mask for new input vector length.
4446 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4447 for (unsigned i = 0; i != MaskNumElts; ++i) {
4448 int Idx = Mask[i];
4449 if (Idx >= (int)SrcNumElts)
4450 Idx -= SrcNumElts - PaddedMaskNumElts;
4451 MappedOps[i] = Idx;
4452 }
4453
4454 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4455
4456 // If the concatenated vector was padded, extract a subvector with the
4457 // correct number of elements.
4458 if (MaskNumElts != PaddedMaskNumElts)
4459 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4460 DAG.getVectorIdxConstant(0, DL));
4461
4462 setValue(&I, Result);
4463 return;
4464 }
4465
4466 assert(SrcNumElts > MaskNumElts);
4467
4468 // Analyze the access pattern of the vector to see if we can extract
4469 // two subvectors and do the shuffle.
4470 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4471 bool CanExtract = true;
4472 for (int Idx : Mask) {
4473 unsigned Input = 0;
4474 if (Idx < 0)
4475 continue;
4476
4477 if (Idx >= (int)SrcNumElts) {
4478 Input = 1;
4479 Idx -= SrcNumElts;
4480 }
4481
4482 // If all the indices come from the same MaskNumElts sized portion of
4483 // the sources we can use extract. Also make sure the extract wouldn't
4484 // extract past the end of the source.
4485 int NewStartIdx = alignDown(Idx, MaskNumElts);
4486 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4487 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4488 CanExtract = false;
4489 // Make sure we always update StartIdx as we use it to track if all
4490 // elements are undef.
4491 StartIdx[Input] = NewStartIdx;
4492 }
4493
4494 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4495 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4496 return;
4497 }
4498 if (CanExtract) {
4499 // Extract appropriate subvector and generate a vector shuffle
4500 for (unsigned Input = 0; Input < 2; ++Input) {
4501 SDValue &Src = Input == 0 ? Src1 : Src2;
4502 if (StartIdx[Input] < 0)
4503 Src = DAG.getUNDEF(VT);
4504 else {
4505 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4506 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4507 }
4508 }
4509
4510 // Calculate new mask.
4511 SmallVector<int, 8> MappedOps(Mask);
4512 for (int &Idx : MappedOps) {
4513 if (Idx >= (int)SrcNumElts)
4514 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4515 else if (Idx >= 0)
4516 Idx -= StartIdx[0];
4517 }
4518
4519 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4520 return;
4521 }
4522
4523 // We can't use either concat vectors or extract subvectors so fall back to
4524 // replacing the shuffle with extract and build vector.
4525 // to insert and build vector.
4526 EVT EltVT = VT.getVectorElementType();
4528 for (int Idx : Mask) {
4529 SDValue Res;
4530
4531 if (Idx < 0) {
4532 Res = DAG.getUNDEF(EltVT);
4533 } else {
4534 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4535 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4536
4537 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4538 DAG.getVectorIdxConstant(Idx, DL));
4539 }
4540
4541 Ops.push_back(Res);
4542 }
4543
4544 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4545}
4546
4547void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4548 ArrayRef<unsigned> Indices = I.getIndices();
4549 const Value *Op0 = I.getOperand(0);
4550 const Value *Op1 = I.getOperand(1);
4551 Type *AggTy = I.getType();
4552 Type *ValTy = Op1->getType();
4553 bool IntoUndef = isa<UndefValue>(Op0);
4554 bool FromUndef = isa<UndefValue>(Op1);
4555
4556 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4557
4558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4559 SmallVector<EVT, 4> AggValueVTs;
4560 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4561 SmallVector<EVT, 4> ValValueVTs;
4562 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4563
4564 unsigned NumAggValues = AggValueVTs.size();
4565 unsigned NumValValues = ValValueVTs.size();
4566 SmallVector<SDValue, 4> Values(NumAggValues);
4567
4568 // Ignore an insertvalue that produces an empty object
4569 if (!NumAggValues) {
4570 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4571 return;
4572 }
4573
4574 SDValue Agg = getValue(Op0);
4575 unsigned i = 0;
4576 // Copy the beginning value(s) from the original aggregate.
4577 for (; i != LinearIndex; ++i)
4578 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4579 SDValue(Agg.getNode(), Agg.getResNo() + i);
4580 // Copy values from the inserted value(s).
4581 if (NumValValues) {
4582 SDValue Val = getValue(Op1);
4583 for (; i != LinearIndex + NumValValues; ++i)
4584 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4585 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4586 }
4587 // Copy remaining value(s) from the original aggregate.
4588 for (; i != NumAggValues; ++i)
4589 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4590 SDValue(Agg.getNode(), Agg.getResNo() + i);
4591
4593 DAG.getVTList(AggValueVTs), Values));
4594}
4595
4596void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4597 ArrayRef<unsigned> Indices = I.getIndices();
4598 const Value *Op0 = I.getOperand(0);
4599 Type *AggTy = Op0->getType();
4600 Type *ValTy = I.getType();
4601 bool OutOfUndef = isa<UndefValue>(Op0);
4602
4603 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4604
4605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4606 SmallVector<EVT, 4> ValValueVTs;
4607 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4608
4609 unsigned NumValValues = ValValueVTs.size();
4610
4611 // Ignore a extractvalue that produces an empty object
4612 if (!NumValValues) {
4613 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4614 return;
4615 }
4616
4617 SmallVector<SDValue, 4> Values(NumValValues);
4618
4619 SDValue Agg = getValue(Op0);
4620 // Copy out the selected value(s).
4621 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4622 Values[i - LinearIndex] =
4623 OutOfUndef ?
4624 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4625 SDValue(Agg.getNode(), Agg.getResNo() + i);
4626
4628 DAG.getVTList(ValValueVTs), Values));
4629}
4630
4631void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4632 Value *Op0 = I.getOperand(0);
4633 // Note that the pointer operand may be a vector of pointers. Take the scalar
4634 // element which holds a pointer.
4635 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4636 SDValue N = getValue(Op0);
4637 SDLoc dl = getCurSDLoc();
4638 auto &TLI = DAG.getTargetLoweringInfo();
4639 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4640
4641 // For a vector GEP, keep the prefix scalar as long as possible, then
4642 // convert any scalars encountered after the first vector operand to vectors.
4643 bool IsVectorGEP = I.getType()->isVectorTy();
4644 ElementCount VectorElementCount =
4645 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4647
4649 GTI != E; ++GTI) {
4650 const Value *Idx = GTI.getOperand();
4651 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4652 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4653 if (Field) {
4654 // N = N + Offset
4656 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4657
4658 // In an inbounds GEP with an offset that is nonnegative even when
4659 // interpreted as signed, assume there is no unsigned overflow.
4660 SDNodeFlags Flags;
4661 if (NW.hasNoUnsignedWrap() ||
4662 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4664 Flags.setInBounds(NW.isInBounds());
4665
4666 N = DAG.getMemBasePlusOffset(
4667 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4668 }
4669 } else {
4670 // IdxSize is the width of the arithmetic according to IR semantics.
4671 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4672 // (and fix up the result later).
4673 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4674 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4675 TypeSize ElementSize =
4676 GTI.getSequentialElementStride(DAG.getDataLayout());
4677 // We intentionally mask away the high bits here; ElementSize may not
4678 // fit in IdxTy.
4679 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4680 /*isSigned=*/false, /*implicitTrunc=*/true);
4681 bool ElementScalable = ElementSize.isScalable();
4682
4683 // If this is a scalar constant or a splat vector of constants,
4684 // handle it quickly.
4685 const auto *C = dyn_cast<Constant>(Idx);
4686 if (C && isa<VectorType>(C->getType()))
4687 C = C->getSplatValue();
4688
4689 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4690 if (CI && CI->isZero())
4691 continue;
4692 if (CI && !ElementScalable) {
4693 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4694 LLVMContext &Context = *DAG.getContext();
4695 SDValue OffsVal;
4696 if (N.getValueType().isVector())
4697 OffsVal = DAG.getConstant(
4698 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4699 else
4700 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4701
4702 // In an inbounds GEP with an offset that is nonnegative even when
4703 // interpreted as signed, assume there is no unsigned overflow.
4704 SDNodeFlags Flags;
4705 if (NW.hasNoUnsignedWrap() ||
4706 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4707 Flags.setNoUnsignedWrap(true);
4708 Flags.setInBounds(NW.isInBounds());
4709
4710 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4711
4712 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4713 continue;
4714 }
4715
4716 // N = N + Idx * ElementMul;
4717 SDValue IdxN = getValue(Idx);
4718
4719 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4720 if (N.getValueType().isVector()) {
4721 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4722 VectorElementCount);
4723 IdxN = DAG.getSplat(VT, dl, IdxN);
4724 } else {
4725 EVT VT =
4726 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4727 N = DAG.getSplat(VT, dl, N);
4728 }
4729 }
4730
4731 // If the index is smaller or larger than intptr_t, truncate or extend
4732 // it.
4733 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4734
4735 SDNodeFlags ScaleFlags;
4736 // The multiplication of an index by the type size does not wrap the
4737 // pointer index type in a signed sense (mul nsw).
4739
4740 // The multiplication of an index by the type size does not wrap the
4741 // pointer index type in an unsigned sense (mul nuw).
4742 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4743
4744 if (ElementScalable) {
4745 EVT VScaleTy = N.getValueType().getScalarType();
4746 SDValue VScale = DAG.getNode(
4747 ISD::VSCALE, dl, VScaleTy,
4748 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4749 if (N.getValueType().isVector())
4750 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4751 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4752 ScaleFlags);
4753 } else {
4754 // If this is a multiply by a power of two, turn it into a shl
4755 // immediately. This is a very common case.
4756 if (ElementMul != 1) {
4757 if (ElementMul.isPowerOf2()) {
4758 unsigned Amt = ElementMul.logBase2();
4759 IdxN = DAG.getNode(
4760 ISD::SHL, dl, N.getValueType(), IdxN,
4761 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4762 ScaleFlags);
4763 } else {
4764 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4765 IdxN.getValueType());
4766 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4767 ScaleFlags);
4768 }
4769 }
4770 }
4771
4772 // The successive addition of the current address, truncated to the
4773 // pointer index type and interpreted as an unsigned number, and each
4774 // offset, also interpreted as an unsigned number, does not wrap the
4775 // pointer index type (add nuw).
4776 SDNodeFlags AddFlags;
4777 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4778 AddFlags.setInBounds(NW.isInBounds());
4779
4780 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4781 }
4782 }
4783
4784 if (IsVectorGEP && !N.getValueType().isVector()) {
4785 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4786 N = DAG.getSplat(VT, dl, N);
4787 }
4788
4789 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4790 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4791 if (IsVectorGEP) {
4792 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4793 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4794 }
4795
4796 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4797 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4798
4799 setValue(&I, N);
4800}
4801
4802void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4803 // If this is a fixed sized alloca in the entry block of the function,
4804 // allocate it statically on the stack.
4805 if (FuncInfo.StaticAllocaMap.count(&I))
4806 return; // getValue will auto-populate this.
4807
4808 SDLoc dl = getCurSDLoc();
4809 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4810 auto &DL = DAG.getDataLayout();
4811 TypeSize TySize = I.getAllocationBaseSize(DL);
4812 MaybeAlign Alignment = I.getAlign();
4813
4814 SDValue AllocSize = getValue(I.getArraySize());
4815
4816 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4817 if (AllocSize.getValueType() != IntPtr)
4818 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4819
4820 AllocSize = DAG.getNode(
4821 ISD::MUL, dl, IntPtr, AllocSize,
4822 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4823
4824 // Handle alignment. If the requested alignment is less than or equal to
4825 // the stack alignment, ignore it. If the size is greater than or equal to
4826 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4827 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4828 if (*Alignment <= StackAlign)
4829 Alignment = std::nullopt;
4830
4831 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4832 // Round the size of the allocation up to the stack alignment size
4833 // by add SA-1 to the size. This doesn't overflow because we're computing
4834 // an address inside an alloca.
4835 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4836 DAG.getConstant(StackAlignMask, dl, IntPtr),
4838
4839 // Mask out the low bits for alignment purposes.
4840 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4841 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4842
4843 SDValue Ops[] = {
4844 getRoot(), AllocSize,
4845 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4846 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4847 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4848 setValue(&I, DSA);
4849 DAG.setRoot(DSA.getValue(1));
4850
4851 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4852}
4853
4854static const MDNode *getRangeMetadata(const Instruction &I) {
4855 return I.getMetadata(LLVMContext::MD_range);
4856}
4857
4858static std::optional<ConstantRange> getRange(const Instruction &I) {
4859 if (const auto *CB = dyn_cast<CallBase>(&I))
4860 if (std::optional<ConstantRange> CR = CB->getRange())
4861 return CR;
4862 if (const MDNode *Range = getRangeMetadata(I))
4864 return std::nullopt;
4865}
4866
4868 if (const auto *CB = dyn_cast<CallBase>(&I))
4869 return CB->getRetNoFPClass();
4870 return fcNone;
4871}
4872
4873void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4874 if (I.isAtomic())
4875 return visitAtomicLoad(I);
4876
4877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4878 const Value *SV = I.getOperand(0);
4879 if (TLI.supportSwiftError()) {
4880 // Swifterror values can come from either a function parameter with
4881 // swifterror attribute or an alloca with swifterror attribute.
4882 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4883 if (Arg->hasSwiftErrorAttr())
4884 return visitLoadFromSwiftError(I);
4885 }
4886
4887 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4888 if (Alloca->isSwiftError())
4889 return visitLoadFromSwiftError(I);
4890 }
4891 }
4892
4893 SDValue Ptr = getValue(SV);
4894
4895 Type *Ty = I.getType();
4896 SmallVector<EVT, 4> ValueVTs, MemVTs;
4898 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4899 unsigned NumValues = ValueVTs.size();
4900 if (NumValues == 0)
4901 return;
4902
4903 Align Alignment = I.getAlign();
4904 AAMDNodes AAInfo = I.getAAMetadata();
4905 const MDNode *Ranges = getRangeMetadata(I);
4906 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4907 bool isVolatile = I.isVolatile();
4908 MachineMemOperand::Flags MMOFlags =
4909 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4910
4911 SDValue Root;
4912 bool ConstantMemory = false;
4913 if (isVolatile)
4914 // Serialize volatile loads with other side effects.
4915 Root = getRoot();
4916 else if (NumValues > MaxParallelChains)
4917 Root = getMemoryRoot();
4918 else if (BatchAA &&
4919 BatchAA->pointsToConstantMemory(MemoryLocation(
4920 SV,
4921 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4922 AAInfo))) {
4923 // Do not serialize (non-volatile) loads of constant memory with anything.
4924 Root = DAG.getEntryNode();
4925 ConstantMemory = true;
4927 } else {
4928 // Do not serialize non-volatile loads against each other.
4929 Root = DAG.getRoot();
4930 }
4931
4932 SDLoc dl = getCurSDLoc();
4933
4934 if (isVolatile)
4935 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4936
4938 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4939
4940 unsigned ChainI = 0;
4941 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4942 // Serializing loads here may result in excessive register pressure, and
4943 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4944 // could recover a bit by hoisting nodes upward in the chain by recognizing
4945 // they are side-effect free or do not alias. The optimizer should really
4946 // avoid this case by converting large object/array copies to llvm.memcpy
4947 // (MaxParallelChains should always remain as failsafe).
4948 if (ChainI == MaxParallelChains) {
4949 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4950 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4951 ArrayRef(Chains.data(), ChainI));
4952 Root = Chain;
4953 ChainI = 0;
4954 }
4955
4956 // TODO: MachinePointerInfo only supports a fixed length offset.
4957 MachinePointerInfo PtrInfo =
4958 !Offsets[i].isScalable() || Offsets[i].isZero()
4959 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4960 : MachinePointerInfo();
4961
4962 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4963 SDValue L =
4964 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4965 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4966 Chains[ChainI] = L.getValue(1);
4967
4968 if (MemVTs[i] != ValueVTs[i])
4969 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4970
4971 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4972 uint64_t FPTestInt =
4973 cast<ConstantInt>(
4974 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
4975 ->getZExtValue();
4976 if (FPTestInt != fcNone) {
4977 SDValue FPTestConst =
4978 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
4979 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
4980 FPTestConst);
4981 }
4982 }
4983 Values[i] = L;
4984 }
4985
4986 if (!ConstantMemory) {
4987 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4988 ArrayRef(Chains.data(), ChainI));
4989 if (isVolatile)
4990 DAG.setRoot(Chain);
4991 else
4992 PendingLoads.push_back(Chain);
4993 }
4994
4995 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4996 DAG.getVTList(ValueVTs), Values));
4997}
4998
4999void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
5000 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5001 "call visitStoreToSwiftError when backend supports swifterror");
5002
5003 SmallVector<EVT, 4> ValueVTs;
5004 SmallVector<uint64_t, 4> Offsets;
5005 const Value *SrcV = I.getOperand(0);
5006 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5007 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5008 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5009 "expect a single EVT for swifterror");
5010
5011 SDValue Src = getValue(SrcV);
5012 // Create a virtual register, then update the virtual register.
5013 Register VReg =
5014 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
5015 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
5016 // Chain can be getRoot or getControlRoot.
5017 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
5018 SDValue(Src.getNode(), Src.getResNo()));
5019 DAG.setRoot(CopyNode);
5020}
5021
5022void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
5023 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5024 "call visitLoadFromSwiftError when backend supports swifterror");
5025
5026 assert(!I.isVolatile() &&
5027 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
5028 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
5029 "Support volatile, non temporal, invariant for load_from_swift_error");
5030
5031 const Value *SV = I.getOperand(0);
5032 Type *Ty = I.getType();
5033 assert(
5034 (!BatchAA ||
5035 !BatchAA->pointsToConstantMemory(MemoryLocation(
5036 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
5037 I.getAAMetadata()))) &&
5038 "load_from_swift_error should not be constant memory");
5039
5040 SmallVector<EVT, 4> ValueVTs;
5041 SmallVector<uint64_t, 4> Offsets;
5042 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
5043 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5044 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5045 "expect a single EVT for swifterror");
5046
5047 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
5048 SDValue L = DAG.getCopyFromReg(
5049 getRoot(), getCurSDLoc(),
5050 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
5051
5052 setValue(&I, L);
5053}
5054
5055void SelectionDAGBuilder::visitStore(const StoreInst &I) {
5056 if (I.isAtomic())
5057 return visitAtomicStore(I);
5058
5059 const Value *SrcV = I.getOperand(0);
5060 const Value *PtrV = I.getOperand(1);
5061
5062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5063 if (TLI.supportSwiftError()) {
5064 // Swifterror values can come from either a function parameter with
5065 // swifterror attribute or an alloca with swifterror attribute.
5066 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
5067 if (Arg->hasSwiftErrorAttr())
5068 return visitStoreToSwiftError(I);
5069 }
5070
5071 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
5072 if (Alloca->isSwiftError())
5073 return visitStoreToSwiftError(I);
5074 }
5075 }
5076
5077 SmallVector<EVT, 4> ValueVTs, MemVTs;
5079 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5080 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
5081 unsigned NumValues = ValueVTs.size();
5082 if (NumValues == 0)
5083 return;
5084
5085 // Get the lowered operands. Note that we do this after
5086 // checking if NumResults is zero, because with zero results
5087 // the operands won't have values in the map.
5088 SDValue Src = getValue(SrcV);
5089 SDValue Ptr = getValue(PtrV);
5090
5091 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
5092 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5093 SDLoc dl = getCurSDLoc();
5094 Align Alignment = I.getAlign();
5095 AAMDNodes AAInfo = I.getAAMetadata();
5096 const MDNode *MemCacheHint =
5097 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5098
5099 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5100
5101 unsigned ChainI = 0;
5102 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5103 // See visitLoad comments.
5104 if (ChainI == MaxParallelChains) {
5105 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5106 ArrayRef(Chains.data(), ChainI));
5107 Root = Chain;
5108 ChainI = 0;
5109 }
5110
5111 // TODO: MachinePointerInfo only supports a fixed length offset.
5112 MachinePointerInfo PtrInfo =
5113 !Offsets[i].isScalable() || Offsets[i].isZero()
5114 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
5115 : MachinePointerInfo();
5116
5117 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5118 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
5119 if (MemVTs[i] != ValueVTs[i])
5120 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
5121 SDValue St =
5122 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
5123 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
5124 Chains[ChainI] = St;
5125 }
5126
5127 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5128 ArrayRef(Chains.data(), ChainI));
5129 setValue(&I, StoreNode);
5130 DAG.setRoot(StoreNode);
5131}
5132
5133void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
5134 bool IsCompressing) {
5135 SDLoc sdl = getCurSDLoc();
5136
5137 Value *Src0Operand = I.getArgOperand(0);
5138 Value *PtrOperand = I.getArgOperand(1);
5139 Value *MaskOperand = I.getArgOperand(2);
5140 Align Alignment = I.getParamAlign(1).valueOrOne();
5141
5142 SDValue Ptr = getValue(PtrOperand);
5143 SDValue Src0 = getValue(Src0Operand);
5144 SDValue Mask = getValue(MaskOperand);
5145 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5146
5147 EVT VT = Src0.getValueType();
5148
5149 const auto &TLI = DAG.getTargetLoweringInfo();
5150
5151 auto MMOFlags = MachineMemOperand::MOStore;
5152 MMOFlags |= TLI.getTargetMMOFlags(I);
5153 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5155
5156 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5157
5158 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5159 MachinePointerInfo(PtrOperand), MMOFlags,
5160 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5161 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5162
5163 SDValue StoreNode =
5164 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5165 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5166 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5167 Mask)
5168 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5169 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5170 IsCompressing);
5171 DAG.setRoot(StoreNode);
5172 setValue(&I, StoreNode);
5173}
5174
5175// Get a uniform base for the Gather/Scatter intrinsic.
5176// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5177// We try to represent it as a base pointer + vector of indices.
5178// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5179// The first operand of the GEP may be a single pointer or a vector of pointers
5180// Example:
5181// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5182// or
5183// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5184// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5185//
5186// When the first GEP operand is a single pointer - it is the uniform base we
5187// are looking for. If first operand of the GEP is a splat vector - we
5188// extract the splat value and use it as a uniform base.
5189// In all other cases the function returns 'false'.
5190static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5191 SDValue &Scale, SelectionDAGBuilder *SDB,
5192 const BasicBlock *CurBB, uint64_t ElemSize) {
5193 SelectionDAG& DAG = SDB->DAG;
5194 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5195 const DataLayout &DL = DAG.getDataLayout();
5196
5197 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5198
5199 // Handle splat constant pointer.
5200 if (auto *C = dyn_cast<Constant>(Ptr)) {
5201 C = C->getSplatValue();
5202 if (!C)
5203 return false;
5204
5205 Base = SDB->getValue(C);
5206
5207 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5208 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5209 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5210 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5211 return true;
5212 }
5213
5215 if (!GEP || GEP->getParent() != CurBB)
5216 return false;
5217
5218 if (GEP->getNumOperands() != 2)
5219 return false;
5220
5221 const Value *BasePtr = GEP->getPointerOperand();
5222 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5223
5224 // Make sure the base is scalar and the index is a vector.
5225 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5226 return false;
5227
5228 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5229 if (ScaleVal.isScalable())
5230 return false;
5231
5232 // Target may not support the required addressing mode.
5233 if (ScaleVal != 1 &&
5234 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5235 return false;
5236
5237 Base = SDB->getValue(BasePtr);
5238 Index = SDB->getValue(IndexVal);
5239
5240 Scale =
5241 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5242 return true;
5243}
5244
5245void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5246 SDLoc sdl = getCurSDLoc();
5247
5248 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5249 const Value *Ptr = I.getArgOperand(1);
5250 SDValue Src0 = getValue(I.getArgOperand(0));
5251 SDValue Mask = getValue(I.getArgOperand(2));
5252 EVT VT = Src0.getValueType();
5253 Align Alignment = I.getParamAlign(1).valueOrOne();
5254 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5255
5256 SDValue Base;
5257 SDValue Index;
5258 SDValue Scale;
5259 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5260 I.getParent(), VT.getScalarStoreSize());
5261
5262 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5263 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5264 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5265 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5266 if (!UniformBase) {
5267 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5268 Index = getValue(Ptr);
5269 Scale =
5270 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5271 }
5272
5273 EVT IdxVT = Index.getValueType();
5274 EVT EltTy = IdxVT.getVectorElementType();
5275 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5276 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5277 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5278 }
5279
5280 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5281 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5282 Ops, MMO, ISD::SIGNED_SCALED, false);
5283 DAG.setRoot(Scatter);
5284 setValue(&I, Scatter);
5285}
5286
5287void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5288 SDLoc sdl = getCurSDLoc();
5289
5290 Value *PtrOperand = I.getArgOperand(0);
5291 Value *MaskOperand = I.getArgOperand(1);
5292 Value *Src0Operand = I.getArgOperand(2);
5293 Align Alignment = I.getParamAlign(0).valueOrOne();
5294
5295 SDValue Ptr = getValue(PtrOperand);
5296 SDValue Src0 = getValue(Src0Operand);
5297 SDValue Mask = getValue(MaskOperand);
5298 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5299
5300 EVT VT = Src0.getValueType();
5301 AAMDNodes AAInfo = I.getAAMetadata();
5302 const MDNode *Ranges = getRangeMetadata(I);
5303 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5304
5305 // Do not serialize masked loads of constant memory with anything.
5306 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5307 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5308
5309 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5310
5311 const auto &TLI = DAG.getTargetLoweringInfo();
5312
5313 auto MMOFlags = MachineMemOperand::MOLoad;
5314 MMOFlags |= TLI.getTargetMMOFlags(I);
5315 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5317 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5319
5320 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5321 MachinePointerInfo(PtrOperand), MMOFlags,
5322 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5323 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5324
5325 // The Load/Res may point to different values and both of them are output
5326 // variables.
5327 SDValue Load;
5328 SDValue Res;
5329 if (!IsExpanding &&
5330 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5331 /*IsStore=*/false))
5332 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5333 else
5334 Res = Load =
5335 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5336 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5337 if (AddToChain)
5338 PendingLoads.push_back(Load.getValue(1));
5339 setValue(&I, Res);
5340}
5341
5342void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5343 SDLoc sdl = getCurSDLoc();
5344 Value *PtrOperand = I.getArgOperand(0);
5345 // The remaining arguments (num_accessible_bytes or oracle function + args)
5346 // are IR-level semantics only; they are not needed at codegen.
5347 SDValue Ptr = getValue(PtrOperand);
5348
5349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5350 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5351 Align Alignment = I.getParamAlign(0).valueOrOne();
5352 AAMDNodes AAInfo = I.getAAMetadata();
5353
5354 SDValue InChain = DAG.getRoot();
5355
5356 // Use MOLoad but NOT MODereferenceable - the memory may not be
5357 // fully dereferenceable.
5358 auto MMOFlags = MachineMemOperand::MOLoad;
5359 MMOFlags |= TLI.getTargetMMOFlags(I);
5360 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5362 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5364
5365 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5366 MachinePointerInfo(PtrOperand), MMOFlags,
5367 LocationSize::precise(VT.getStoreSize()), Alignment, AAInfo);
5368
5369 SDValue Load = DAG.getLoad(VT, sdl, InChain, Ptr, MMO);
5370 PendingLoads.push_back(Load.getValue(1));
5371 setValue(&I, Load);
5372}
5373
5374void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5375 SDLoc sdl = getCurSDLoc();
5376
5377 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5378 const Value *Ptr = I.getArgOperand(0);
5379 SDValue Src0 = getValue(I.getArgOperand(2));
5380 SDValue Mask = getValue(I.getArgOperand(1));
5381
5382 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5383 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5384 Align Alignment = I.getParamAlign(0).valueOrOne();
5385
5386 const MDNode *Ranges = getRangeMetadata(I);
5387
5388 SDValue Root = DAG.getRoot();
5389 SDValue Base;
5390 SDValue Index;
5391 SDValue Scale;
5392 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5393 I.getParent(), VT.getScalarStoreSize());
5394 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5395 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5396 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5398 MMOMetadata(I.getAAMetadata(), Ranges));
5399
5400 if (!UniformBase) {
5401 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5402 Index = getValue(Ptr);
5403 Scale =
5404 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5405 }
5406
5407 EVT IdxVT = Index.getValueType();
5408 EVT EltTy = IdxVT.getVectorElementType();
5409 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5410 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5411 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5412 }
5413
5414 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5415 SDValue Gather =
5416 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5418
5419 PendingLoads.push_back(Gather.getValue(1));
5420 setValue(&I, Gather);
5421}
5422
5423void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5424 SDLoc dl = getCurSDLoc();
5425 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5426 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5427 SyncScope::ID SSID = I.getSyncScopeID();
5428
5429 SDValue InChain = getRoot();
5430
5431 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5432 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5433
5434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5435 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5436
5437 MachineFunction &MF = DAG.getMachineFunction();
5438 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5439 MachineMemOperand *MMO = MF.getMachineMemOperand(
5440 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5441 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5442 SSID, SuccessOrdering, FailureOrdering);
5443
5444 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5445 dl, MemVT, VTs, InChain,
5446 getValue(I.getPointerOperand()),
5447 getValue(I.getCompareOperand()),
5448 getValue(I.getNewValOperand()), MMO);
5449
5450 SDValue OutChain = L.getValue(2);
5451
5452 setValue(&I, L);
5453 DAG.setRoot(OutChain);
5454}
5455
5456void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5457 SDLoc dl = getCurSDLoc();
5459 switch (I.getOperation()) {
5460 default: llvm_unreachable("Unknown atomicrmw operation");
5478 break;
5481 break;
5484 break;
5487 break;
5490 break;
5493 break;
5496 break;
5499 break;
5500 }
5501 AtomicOrdering Ordering = I.getOrdering();
5502 SyncScope::ID SSID = I.getSyncScopeID();
5503
5504 SDValue InChain = getRoot();
5505
5506 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5508 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5509
5510 MachineFunction &MF = DAG.getMachineFunction();
5511 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5512 MachineMemOperand *MMO = MF.getMachineMemOperand(
5513 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5514 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5515 SSID, Ordering);
5516
5517 SDValue L =
5518 DAG.getAtomic(NT, dl, MemVT, InChain,
5519 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5520 MMO);
5521
5522 SDValue OutChain = L.getValue(1);
5523
5524 setValue(&I, L);
5525 DAG.setRoot(OutChain);
5526}
5527
5528void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5529 SDLoc dl = getCurSDLoc();
5530 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5531 SDValue Ops[3];
5532 Ops[0] = getRoot();
5533 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5534 TLI.getFenceOperandTy(DAG.getDataLayout()));
5535 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5536 TLI.getFenceOperandTy(DAG.getDataLayout()));
5537 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5538 setValue(&I, N);
5539 DAG.setRoot(N);
5540}
5541
5542void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5543 SDLoc dl = getCurSDLoc();
5544 AtomicOrdering Order = I.getOrdering();
5545 SyncScope::ID SSID = I.getSyncScopeID();
5546
5547 SDValue InChain = getRoot();
5548
5549 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5550 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5551 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5552
5553 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5554 report_fatal_error("Cannot generate unaligned atomic load");
5555
5556 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5557
5558 const MDNode *Ranges = getRangeMetadata(I);
5559 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5560 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5561 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5562 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5563 Order);
5564
5565 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5566
5567 SDValue Ptr = getValue(I.getPointerOperand());
5568 SDValue L =
5569 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5570
5571 SDValue OutChain = L.getValue(1);
5572 if (MemVT != VT)
5573 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5574
5575 setValue(&I, L);
5576 DAG.setRoot(OutChain);
5577}
5578
5579void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5580 SDLoc dl = getCurSDLoc();
5581
5582 AtomicOrdering Ordering = I.getOrdering();
5583 SyncScope::ID SSID = I.getSyncScopeID();
5584
5585 SDValue InChain = getRoot();
5586
5587 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5588 EVT MemVT =
5589 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5590
5591 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5592 report_fatal_error("Cannot generate unaligned atomic store");
5593
5594 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5595
5596 MachineFunction &MF = DAG.getMachineFunction();
5597 const MDNode *MemCacheHint =
5598 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5599 MachineMemOperand *MMO = MF.getMachineMemOperand(
5600 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5601 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5602 SSID, Ordering);
5603
5604 SDValue Val = getValue(I.getValueOperand());
5605 if (Val.getValueType() != MemVT)
5606 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5607 SDValue Ptr = getValue(I.getPointerOperand());
5608
5609 SDValue OutChain =
5610 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5611
5612 setValue(&I, OutChain);
5613 DAG.setRoot(OutChain);
5614}
5615
5616/// Check if this intrinsic call depends on the chain (1st return value)
5617/// and if it only *loads* memory.
5618/// Ignore the callsite's attributes. A specific call site may be marked with
5619/// readnone, but the lowering code will expect the chain based on the
5620/// definition.
5621std::pair<bool, bool>
5622SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5623 const Function *F = I.getCalledFunction();
5624 bool HasChain = !F->doesNotAccessMemory();
5625 bool OnlyLoad =
5626 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5627
5628 return {HasChain, OnlyLoad};
5629}
5630
5631SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5632 const CallBase &I, bool HasChain, bool OnlyLoad,
5633 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5634 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5635
5636 // Build the operand list.
5638 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5639 if (OnlyLoad) {
5640 // We don't need to serialize loads against other loads.
5641 Ops.push_back(DAG.getRoot());
5642 } else {
5643 Ops.push_back(getRoot());
5644 }
5645 }
5646
5647 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5648 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5649 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5650 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5651 TLI.getPointerTy(DAG.getDataLayout())));
5652
5653 // Add all operands of the call to the operand list.
5654 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5655 const Value *Arg = I.getArgOperand(i);
5656 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5657 Ops.push_back(getValue(Arg));
5658 continue;
5659 }
5660
5661 // Use TargetConstant instead of a regular constant for immarg.
5662 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5663 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5664 assert(CI->getBitWidth() <= 64 &&
5665 "large intrinsic immediates not handled");
5666 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5667 } else {
5668 Ops.push_back(
5669 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5670 }
5671 }
5672
5673 if (std::optional<OperandBundleUse> Bundle =
5674 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5675 auto *Sym = Bundle->Inputs[0].get();
5676 SDValue SDSym = getValue(Sym);
5677 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5678 Ops.push_back(SDSym);
5679 }
5680
5681 if (std::optional<OperandBundleUse> Bundle =
5682 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5683 Value *Token = Bundle->Inputs[0].get();
5684 SDValue ConvControlToken = getValue(Token);
5685 assert(Ops.back().getValueType() != MVT::Glue &&
5686 "Did not expect another glue node here.");
5687 ConvControlToken =
5688 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5689 Ops.push_back(ConvControlToken);
5690 }
5691
5692 return Ops;
5693}
5694
5695SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5696 bool HasChain) {
5697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5698
5699 SmallVector<EVT, 4> ValueVTs;
5700 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5701
5702 if (HasChain)
5703 ValueVTs.push_back(MVT::Other);
5704
5705 return DAG.getVTList(ValueVTs);
5706}
5707
5708/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5709SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5710 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5711 const SDVTList &VTs) {
5712 if (!HasChain)
5713 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5714 if (!IntrinsicVT.isVoidTy())
5715 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5716 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5717}
5718
5719/// Set root, convert return type if necessary and check alignment.
5720SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5721 bool HasChain,
5722 bool OnlyLoad,
5723 SDValue Result) {
5724 if (HasChain) {
5725 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5726 if (OnlyLoad)
5727 PendingLoads.push_back(Chain);
5728 else
5729 DAG.setRoot(Chain);
5730 }
5731
5732 if (I.getType()->isVoidTy())
5733 return Result;
5734
5735 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5736 // Insert `assertalign` node if there's an alignment.
5737 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5738 } else if (!isa<VectorType>(I.getType())) {
5739 Result = lowerRangeToAssertZExt(DAG, I, Result);
5740 }
5741
5742 return Result;
5743}
5744
5745/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5746/// node.
5747void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5748 unsigned Intrinsic) {
5749 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5750 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5751
5752 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5753 Intrinsic)) {
5754 SDLoc DL = getCurSDLoc();
5755 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5756 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5757
5758 // The intrinsic is not available on this subtarget. Preserve the chain for
5759 // side-effecting intrinsics and lower any result to poison so that
5760 // compilation can continue and collect further diagnostics.
5761 if (HasChain && !OnlyLoad)
5762 DAG.setRoot(getRoot());
5763
5765 return;
5766 }
5767
5768 // Infos is set by getTgtMemIntrinsic.
5770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5771 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5772 // Use the first (primary) info determines the node opcode.
5773 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5774
5776 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5777 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5778
5779 // Propagate fast-math-flags from IR to node(s).
5780 SDNodeFlags Flags;
5781 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5782 Flags.copyFMF(*FPMO);
5783 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5784
5785 // Create the node.
5786 SDValue Result;
5787
5788 // In some cases, custom collection of operands from CallInst I may be needed.
5790 if (!Infos.empty()) {
5791 // This is target intrinsic that touches memory
5792 // Create MachineMemOperands for each memory access described by the target.
5793 MachineFunction &MF = DAG.getMachineFunction();
5795 for (const auto &Info : Infos) {
5796 // TODO: We currently just fallback to address space 0 if
5797 // getTgtMemIntrinsic didn't yield anything useful.
5798 MachinePointerInfo MPI;
5799 if (Info.ptrVal)
5800 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5801 else if (Info.fallbackAddressSpace)
5802 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5803 EVT MemVT = Info.memVT;
5804 LocationSize Size = LocationSize::precise(Info.size);
5805 if (Size.hasValue() && !Size.getValue())
5807 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5808 MachineMemOperand *MMO = MF.getMachineMemOperand(
5809 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5810 Info.order, Info.failureOrder);
5811 MMOs.push_back(MMO);
5812 }
5813
5814 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5815 Info->memVT, MMOs);
5816 } else {
5817 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5818 }
5819
5820 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5821
5822 setValue(&I, Result);
5823}
5824
5825/// GetSignificand - Get the significand and build it into a floating-point
5826/// number with exponent of 1:
5827///
5828/// Op = (Op & 0x007fffff) | 0x3f800000;
5829///
5830/// where Op is the hexadecimal representation of floating point value.
5832 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5833 DAG.getConstant(0x007fffff, dl, MVT::i32));
5834 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5835 DAG.getConstant(0x3f800000, dl, MVT::i32));
5836 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5837}
5838
5839/// GetExponent - Get the exponent:
5840///
5841/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5842///
5843/// where Op is the hexadecimal representation of floating point value.
5845 const TargetLowering &TLI, const SDLoc &dl) {
5846 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5847 DAG.getConstant(0x7f800000, dl, MVT::i32));
5848 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5849 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5850 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5851 DAG.getConstant(127, dl, MVT::i32));
5852 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5853}
5854
5855/// getF32Constant - Get 32-bit floating point constant.
5856static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5857 const SDLoc &dl) {
5858 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5859 MVT::f32);
5860}
5861
5863 SelectionDAG &DAG) {
5864 // TODO: What fast-math-flags should be set on the floating-point nodes?
5865
5866 // IntegerPartOfX = ((int32_t)(t0);
5867 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5868
5869 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5870 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5871 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5872
5873 // IntegerPartOfX <<= 23;
5874 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5875 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5876
5877 SDValue TwoToFractionalPartOfX;
5878 if (LimitFloatPrecision <= 6) {
5879 // For floating-point precision of 6:
5880 //
5881 // TwoToFractionalPartOfX =
5882 // 0.997535578f +
5883 // (0.735607626f + 0.252464424f * x) * x;
5884 //
5885 // error 0.0144103317, which is 6 bits
5886 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5887 getF32Constant(DAG, 0x3e814304, dl));
5888 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5889 getF32Constant(DAG, 0x3f3c50c8, dl));
5890 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5891 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5892 getF32Constant(DAG, 0x3f7f5e7e, dl));
5893 } else if (LimitFloatPrecision <= 12) {
5894 // For floating-point precision of 12:
5895 //
5896 // TwoToFractionalPartOfX =
5897 // 0.999892986f +
5898 // (0.696457318f +
5899 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5900 //
5901 // error 0.000107046256, which is 13 to 14 bits
5902 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5903 getF32Constant(DAG, 0x3da235e3, dl));
5904 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5905 getF32Constant(DAG, 0x3e65b8f3, dl));
5906 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5907 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5908 getF32Constant(DAG, 0x3f324b07, dl));
5909 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5910 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5911 getF32Constant(DAG, 0x3f7ff8fd, dl));
5912 } else { // LimitFloatPrecision <= 18
5913 // For floating-point precision of 18:
5914 //
5915 // TwoToFractionalPartOfX =
5916 // 0.999999982f +
5917 // (0.693148872f +
5918 // (0.240227044f +
5919 // (0.554906021e-1f +
5920 // (0.961591928e-2f +
5921 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5922 // error 2.47208000*10^(-7), which is better than 18 bits
5923 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5924 getF32Constant(DAG, 0x3924b03e, dl));
5925 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5926 getF32Constant(DAG, 0x3ab24b87, dl));
5927 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5928 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5929 getF32Constant(DAG, 0x3c1d8c17, dl));
5930 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5931 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5932 getF32Constant(DAG, 0x3d634a1d, dl));
5933 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5934 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5935 getF32Constant(DAG, 0x3e75fe14, dl));
5936 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5937 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5938 getF32Constant(DAG, 0x3f317234, dl));
5939 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5940 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5941 getF32Constant(DAG, 0x3f800000, dl));
5942 }
5943
5944 // Add the exponent into the result in integer domain.
5945 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5946 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5947 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5948}
5949
5950/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5951/// limited-precision mode.
5953 const TargetLowering &TLI, SDNodeFlags Flags) {
5954 if (Op.getValueType() == MVT::f32 &&
5956
5957 // Put the exponent in the right bit position for later addition to the
5958 // final result:
5959 //
5960 // t0 = Op * log2(e)
5961
5962 // TODO: What fast-math-flags should be set here?
5963 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5964 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5965 return getLimitedPrecisionExp2(t0, dl, DAG);
5966 }
5967
5968 // No special expansion.
5969 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5970}
5971
5972/// expandLog - Lower a log intrinsic. Handles the special sequences for
5973/// limited-precision mode.
5975 const TargetLowering &TLI, SDNodeFlags Flags) {
5976 // TODO: What fast-math-flags should be set on the floating-point nodes?
5977
5978 if (Op.getValueType() == MVT::f32 &&
5980 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5981
5982 // Scale the exponent by log(2).
5983 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5984 SDValue LogOfExponent =
5985 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5986 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5987
5988 // Get the significand and build it into a floating-point number with
5989 // exponent of 1.
5990 SDValue X = GetSignificand(DAG, Op1, dl);
5991
5992 SDValue LogOfMantissa;
5993 if (LimitFloatPrecision <= 6) {
5994 // For floating-point precision of 6:
5995 //
5996 // LogofMantissa =
5997 // -1.1609546f +
5998 // (1.4034025f - 0.23903021f * x) * x;
5999 //
6000 // error 0.0034276066, which is better than 8 bits
6001 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6002 getF32Constant(DAG, 0xbe74c456, dl));
6003 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6004 getF32Constant(DAG, 0x3fb3a2b1, dl));
6005 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6006 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6007 getF32Constant(DAG, 0x3f949a29, dl));
6008 } else if (LimitFloatPrecision <= 12) {
6009 // For floating-point precision of 12:
6010 //
6011 // LogOfMantissa =
6012 // -1.7417939f +
6013 // (2.8212026f +
6014 // (-1.4699568f +
6015 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
6016 //
6017 // error 0.000061011436, which is 14 bits
6018 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6019 getF32Constant(DAG, 0xbd67b6d6, dl));
6020 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6021 getF32Constant(DAG, 0x3ee4f4b8, dl));
6022 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6023 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6024 getF32Constant(DAG, 0x3fbc278b, dl));
6025 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6026 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6027 getF32Constant(DAG, 0x40348e95, dl));
6028 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6029 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6030 getF32Constant(DAG, 0x3fdef31a, dl));
6031 } else { // LimitFloatPrecision <= 18
6032 // For floating-point precision of 18:
6033 //
6034 // LogOfMantissa =
6035 // -2.1072184f +
6036 // (4.2372794f +
6037 // (-3.7029485f +
6038 // (2.2781945f +
6039 // (-0.87823314f +
6040 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
6041 //
6042 // error 0.0000023660568, which is better than 18 bits
6043 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6044 getF32Constant(DAG, 0xbc91e5ac, dl));
6045 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6046 getF32Constant(DAG, 0x3e4350aa, 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, 0x3f60d3e3, 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, 0x4011cdf0, dl));
6053 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6054 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6055 getF32Constant(DAG, 0x406cfd1c, dl));
6056 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6057 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6058 getF32Constant(DAG, 0x408797cb, dl));
6059 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6060 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6061 getF32Constant(DAG, 0x4006dcab, dl));
6062 }
6063
6064 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
6065 }
6066
6067 // No special expansion.
6068 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
6069}
6070
6071/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
6072/// limited-precision mode.
6074 const TargetLowering &TLI, SDNodeFlags Flags) {
6075 // TODO: What fast-math-flags should be set on the floating-point nodes?
6076
6077 if (Op.getValueType() == MVT::f32 &&
6079 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6080
6081 // Get the exponent.
6082 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
6083
6084 // Get the significand and build it into a floating-point number with
6085 // exponent of 1.
6086 SDValue X = GetSignificand(DAG, Op1, dl);
6087
6088 // Different possible minimax approximations of significand in
6089 // floating-point for various degrees of accuracy over [1,2].
6090 SDValue Log2ofMantissa;
6091 if (LimitFloatPrecision <= 6) {
6092 // For floating-point precision of 6:
6093 //
6094 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
6095 //
6096 // error 0.0049451742, which is more than 7 bits
6097 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6098 getF32Constant(DAG, 0xbeb08fe0, dl));
6099 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6100 getF32Constant(DAG, 0x40019463, dl));
6101 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6102 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6103 getF32Constant(DAG, 0x3fd6633d, dl));
6104 } else if (LimitFloatPrecision <= 12) {
6105 // For floating-point precision of 12:
6106 //
6107 // Log2ofMantissa =
6108 // -2.51285454f +
6109 // (4.07009056f +
6110 // (-2.12067489f +
6111 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
6112 //
6113 // error 0.0000876136000, which is better than 13 bits
6114 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6115 getF32Constant(DAG, 0xbda7262e, dl));
6116 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6117 getF32Constant(DAG, 0x3f25280b, dl));
6118 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6119 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6120 getF32Constant(DAG, 0x4007b923, dl));
6121 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6122 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6123 getF32Constant(DAG, 0x40823e2f, dl));
6124 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6125 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6126 getF32Constant(DAG, 0x4020d29c, dl));
6127 } else { // LimitFloatPrecision <= 18
6128 // For floating-point precision of 18:
6129 //
6130 // Log2ofMantissa =
6131 // -3.0400495f +
6132 // (6.1129976f +
6133 // (-5.3420409f +
6134 // (3.2865683f +
6135 // (-1.2669343f +
6136 // (0.27515199f -
6137 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
6138 //
6139 // error 0.0000018516, which is better than 18 bits
6140 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6141 getF32Constant(DAG, 0xbcd2769e, dl));
6142 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6143 getF32Constant(DAG, 0x3e8ce0b9, dl));
6144 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6145 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6146 getF32Constant(DAG, 0x3fa22ae7, dl));
6147 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6148 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6149 getF32Constant(DAG, 0x40525723, dl));
6150 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6151 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6152 getF32Constant(DAG, 0x40aaf200, dl));
6153 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6154 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6155 getF32Constant(DAG, 0x40c39dad, dl));
6156 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6157 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6158 getF32Constant(DAG, 0x4042902c, dl));
6159 }
6160
6161 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
6162 }
6163
6164 // No special expansion.
6165 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
6166}
6167
6168/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6169/// limited-precision mode.
6171 const TargetLowering &TLI, SDNodeFlags Flags) {
6172 // TODO: What fast-math-flags should be set on the floating-point nodes?
6173
6174 if (Op.getValueType() == MVT::f32 &&
6176 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6177
6178 // Scale the exponent by log10(2) [0.30102999f].
6179 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6180 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6181 getF32Constant(DAG, 0x3e9a209a, dl));
6182
6183 // Get the significand and build it into a floating-point number with
6184 // exponent of 1.
6185 SDValue X = GetSignificand(DAG, Op1, dl);
6186
6187 SDValue Log10ofMantissa;
6188 if (LimitFloatPrecision <= 6) {
6189 // For floating-point precision of 6:
6190 //
6191 // Log10ofMantissa =
6192 // -0.50419619f +
6193 // (0.60948995f - 0.10380950f * x) * x;
6194 //
6195 // error 0.0014886165, which is 6 bits
6196 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6197 getF32Constant(DAG, 0xbdd49a13, dl));
6198 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6199 getF32Constant(DAG, 0x3f1c0789, dl));
6200 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6201 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6202 getF32Constant(DAG, 0x3f011300, dl));
6203 } else if (LimitFloatPrecision <= 12) {
6204 // For floating-point precision of 12:
6205 //
6206 // Log10ofMantissa =
6207 // -0.64831180f +
6208 // (0.91751397f +
6209 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6210 //
6211 // error 0.00019228036, which is better than 12 bits
6212 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6213 getF32Constant(DAG, 0x3d431f31, dl));
6214 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6215 getF32Constant(DAG, 0x3ea21fb2, dl));
6216 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6217 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6218 getF32Constant(DAG, 0x3f6ae232, dl));
6219 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6220 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6221 getF32Constant(DAG, 0x3f25f7c3, dl));
6222 } else { // LimitFloatPrecision <= 18
6223 // For floating-point precision of 18:
6224 //
6225 // Log10ofMantissa =
6226 // -0.84299375f +
6227 // (1.5327582f +
6228 // (-1.0688956f +
6229 // (0.49102474f +
6230 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6231 //
6232 // error 0.0000037995730, which is better than 18 bits
6233 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6234 getF32Constant(DAG, 0x3c5d51ce, dl));
6235 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6236 getF32Constant(DAG, 0x3e00685a, dl));
6237 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6238 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6239 getF32Constant(DAG, 0x3efb6798, dl));
6240 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6241 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6242 getF32Constant(DAG, 0x3f88d192, dl));
6243 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6244 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6245 getF32Constant(DAG, 0x3fc4316c, dl));
6246 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6247 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6248 getF32Constant(DAG, 0x3f57ce70, dl));
6249 }
6250
6251 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6252 }
6253
6254 // No special expansion.
6255 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6256}
6257
6258/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6259/// limited-precision mode.
6261 const TargetLowering &TLI, SDNodeFlags Flags) {
6262 if (Op.getValueType() == MVT::f32 &&
6264 return getLimitedPrecisionExp2(Op, dl, DAG);
6265
6266 // No special expansion.
6267 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6268}
6269
6270/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6271/// limited-precision mode with x == 10.0f.
6273 SelectionDAG &DAG, const TargetLowering &TLI,
6274 SDNodeFlags Flags) {
6275 bool IsExp10 = false;
6276 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6279 APFloat Ten(10.0f);
6280 IsExp10 = LHSC->isExactlyValue(Ten);
6281 }
6282 }
6283
6284 // TODO: What fast-math-flags should be set on the FMUL node?
6285 if (IsExp10) {
6286 // Put the exponent in the right bit position for later addition to the
6287 // final result:
6288 //
6289 // #define LOG2OF10 3.3219281f
6290 // t0 = Op * LOG2OF10;
6291 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6292 getF32Constant(DAG, 0x40549a78, dl));
6293 return getLimitedPrecisionExp2(t0, dl, DAG);
6294 }
6295
6296 // No special expansion.
6297 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6298}
6299
6300/// ExpandPowI - Expand a llvm.powi intrinsic.
6302 SelectionDAG &DAG) {
6303 // If RHS is a constant, we can expand this out to a multiplication tree if
6304 // it's beneficial on the target, otherwise we end up lowering to a call to
6305 // __powidf2 (for example).
6307 unsigned Val = RHSC->getSExtValue();
6308
6309 // powi(x, 0) -> 1.0
6310 if (Val == 0)
6311 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6312
6314 Val, DAG.shouldOptForSize())) {
6315 // Get the exponent as a positive value.
6316 if ((int)Val < 0)
6317 Val = -Val;
6318 // We use the simple binary decomposition method to generate the multiply
6319 // sequence. There are more optimal ways to do this (for example,
6320 // powi(x,15) generates one more multiply than it should), but this has
6321 // the benefit of being both really simple and much better than a libcall.
6322 SDValue Res; // Logically starts equal to 1.0
6323 SDValue CurSquare = LHS;
6324 // TODO: Intrinsics should have fast-math-flags that propagate to these
6325 // nodes.
6326 while (Val) {
6327 if (Val & 1) {
6328 if (Res.getNode())
6329 Res =
6330 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6331 else
6332 Res = CurSquare; // 1.0*CurSquare.
6333 }
6334
6335 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6336 CurSquare, CurSquare);
6337 Val >>= 1;
6338 }
6339
6340 // If the original was negative, invert the result, producing 1/(x*x*x).
6341 if (RHSC->getSExtValue() < 0)
6342 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6343 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6344 return Res;
6345 }
6346 }
6347
6348 // Otherwise, expand to a libcall.
6349 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6350}
6351
6352static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6353 SDValue LHS, SDValue RHS, SDValue Scale,
6354 SelectionDAG &DAG, const TargetLowering &TLI) {
6355 EVT VT = LHS.getValueType();
6356 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6357 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6358 LLVMContext &Ctx = *DAG.getContext();
6359
6360 // If the type is legal but the operation isn't, this node might survive all
6361 // the way to operation legalization. If we end up there and we do not have
6362 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6363 // node.
6364
6365 // Coax the legalizer into expanding the node during type legalization instead
6366 // by bumping the size by one bit. This will force it to Promote, enabling the
6367 // early expansion and avoiding the need to expand later.
6368
6369 // We don't have to do this if Scale is 0; that can always be expanded, unless
6370 // it's a saturating signed operation. Those can experience true integer
6371 // division overflow, a case which we must avoid.
6372
6373 // FIXME: We wouldn't have to do this (or any of the early
6374 // expansion/promotion) if it was possible to expand a libcall of an
6375 // illegal type during operation legalization. But it's not, so things
6376 // get a bit hacky.
6377 unsigned ScaleInt = Scale->getAsZExtVal();
6378 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6379 (TLI.isTypeLegal(VT) ||
6380 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6382 Opcode, VT, ScaleInt);
6383 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6384 EVT PromVT;
6385 if (VT.isScalarInteger())
6386 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6387 else if (VT.isVector()) {
6388 PromVT = VT.getVectorElementType();
6389 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6390 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6391 } else
6392 llvm_unreachable("Wrong VT for DIVFIX?");
6393 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6394 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6395 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6396 // For saturating operations, we need to shift up the LHS to get the
6397 // proper saturation width, and then shift down again afterwards.
6398 if (Saturating)
6399 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6400 DAG.getConstant(1, DL, ShiftTy));
6401 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6402 if (Saturating)
6403 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6404 DAG.getConstant(1, DL, ShiftTy));
6405 return DAG.getZExtOrTrunc(Res, DL, VT);
6406 }
6407 }
6408
6409 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6410}
6411
6412// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6413// bitcasted, or split argument. Returns a list of <Register, size in bits>
6414static void
6415getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6416 const SDValue &N) {
6417 switch (N.getOpcode()) {
6418 case ISD::CopyFromReg: {
6419 SDValue Op = N.getOperand(1);
6420 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6421 Op.getValueType().getSizeInBits());
6422 return;
6423 }
6424 case ISD::BITCAST:
6425 case ISD::AssertZext:
6426 case ISD::AssertSext:
6427 case ISD::TRUNCATE:
6428 getUnderlyingArgRegs(Regs, N.getOperand(0));
6429 return;
6430 case ISD::BUILD_PAIR:
6431 case ISD::BUILD_VECTOR:
6433 for (SDValue Op : N->op_values())
6434 getUnderlyingArgRegs(Regs, Op);
6435 return;
6436 default:
6437 return;
6438 }
6439}
6440
6441/// If the DbgValueInst is a dbg_value of a function argument, create the
6442/// corresponding DBG_VALUE machine instruction for it now. At the end of
6443/// instruction selection, they will be inserted to the entry BB.
6444/// We don't currently support this for variadic dbg_values, as they shouldn't
6445/// appear for function arguments or in the prologue.
6446bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6447 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6448 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6449 const Argument *Arg = dyn_cast<Argument>(V);
6450 if (!Arg)
6451 return false;
6452
6453 MachineFunction &MF = DAG.getMachineFunction();
6454 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6455
6456 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6457 // we've been asked to pursue.
6458 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6459 bool Indirect) {
6460 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6461 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6462 // pointing at the VReg, which will be patched up later.
6463 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6465 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6466 /* isKill */ false, /* isDead */ false,
6467 /* isUndef */ false, /* isEarlyClobber */ false,
6468 /* SubReg */ 0, /* isDebug */ true)});
6469
6470 auto *NewDIExpr = FragExpr;
6471 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6472 // the DIExpression.
6473 if (Indirect)
6474 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6476 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6477 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6478 } else {
6479 // Create a completely standard DBG_VALUE.
6480 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6481 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6482 }
6483 };
6484
6485 if (Kind == FuncArgumentDbgValueKind::Value) {
6486 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6487 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6488 // the entry block.
6489 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6490 if (!IsInEntryBlock)
6491 return false;
6492
6493 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6494 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6495 // variable that also is a param.
6496 //
6497 // Although, if we are at the top of the entry block already, we can still
6498 // emit using ArgDbgValue. This might catch some situations when the
6499 // dbg.value refers to an argument that isn't used in the entry block, so
6500 // any CopyToReg node would be optimized out and the only way to express
6501 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6502 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6503 // we should only emit as ArgDbgValue if the Variable is an argument to the
6504 // current function, and the dbg.value intrinsic is found in the entry
6505 // block.
6506 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6507 !DL->getInlinedAt();
6508 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6509 if (!IsInPrologue && !VariableIsFunctionInputArg)
6510 return false;
6511
6512 // Here we assume that a function argument on IR level only can be used to
6513 // describe one input parameter on source level. If we for example have
6514 // source code like this
6515 //
6516 // struct A { long x, y; };
6517 // void foo(struct A a, long b) {
6518 // ...
6519 // b = a.x;
6520 // ...
6521 // }
6522 //
6523 // and IR like this
6524 //
6525 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6526 // entry:
6527 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6528 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6529 // call void @llvm.dbg.value(metadata i32 %b, "b",
6530 // ...
6531 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6532 // ...
6533 //
6534 // then the last dbg.value is describing a parameter "b" using a value that
6535 // is an argument. But since we already has used %a1 to describe a parameter
6536 // we should not handle that last dbg.value here (that would result in an
6537 // incorrect hoisting of the DBG_VALUE to the function entry).
6538 // Notice that we allow one dbg.value per IR level argument, to accommodate
6539 // for the situation with fragments above.
6540 // If there is no node for the value being handled, we return true to skip
6541 // the normal generation of debug info, as it would kill existing debug
6542 // info for the parameter in case of duplicates.
6543 if (VariableIsFunctionInputArg) {
6544 unsigned ArgNo = Arg->getArgNo();
6545 if (ArgNo >= FuncInfo.DescribedArgs.size())
6546 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6547 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6548 return !NodeMap[V].getNode();
6549 FuncInfo.DescribedArgs.set(ArgNo);
6550 }
6551 }
6552
6553 bool IsIndirect = false;
6554 std::optional<MachineOperand> Op;
6555 // Some arguments' frame index is recorded during argument lowering.
6556 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6557 if (FI != std::numeric_limits<int>::max())
6559
6561 if (!Op && N.getNode()) {
6562 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6563 Register Reg;
6564 if (ArgRegsAndSizes.size() == 1)
6565 Reg = ArgRegsAndSizes.front().first;
6566
6567 if (Reg && Reg.isVirtual()) {
6568 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6569 Register PR = RegInfo.getLiveInPhysReg(Reg);
6570 if (PR)
6571 Reg = PR;
6572 }
6573 if (Reg) {
6575 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6576 }
6577 }
6578
6579 if (!Op && N.getNode()) {
6580 // Check if frame index is available.
6581 SDValue LCandidate = peekThroughBitcasts(N);
6582 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6583 if (FrameIndexSDNode *FINode =
6584 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6585 Op = MachineOperand::CreateFI(FINode->getIndex());
6586 }
6587
6588 if (!Op) {
6589 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6590 auto splitMultiRegDbgValue =
6591 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6592 unsigned Offset = 0;
6593 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6594 // FIXME: Scalable sizes are not supported in fragment expressions.
6595 if (RegSizeInBits.isScalable())
6596 return false;
6597
6598 // If the expression is already a fragment, the current register
6599 // offset+size might extend beyond the fragment. In this case, only
6600 // the register bits that are inside the fragment are relevant.
6601 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6602 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6603 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6604 // The register is entirely outside the expression fragment,
6605 // so is irrelevant for debug info.
6606 if (Offset >= ExprFragmentSizeInBits)
6607 break;
6608 // The register is partially outside the expression fragment, only
6609 // the low bits within the fragment are relevant for debug info.
6610 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6611 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6612 }
6613 }
6614
6615 auto FragmentExpr = DIExpression::createFragmentExpression(
6616 Expr, Offset, RegFragmentSizeInBits);
6617 Offset += RegSizeInBits.getFixedValue();
6618 // If a valid fragment expression cannot be created, the variable's
6619 // correct value cannot be determined and so it is set as poison.
6620 if (!FragmentExpr) {
6621 SDDbgValue *SDV = DAG.getConstantDbgValue(
6622 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6623 DAG.AddDbgValue(SDV, false);
6624 continue;
6625 }
6626 MachineInstr *NewMI = MakeVRegDbgValue(
6627 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6628 FuncInfo.ArgDbgValues.push_back(NewMI);
6629 }
6630
6631 return true;
6632 };
6633
6634 // Check if ValueMap has reg number.
6636 VMI = FuncInfo.ValueMap.find(V);
6637 if (VMI != FuncInfo.ValueMap.end()) {
6638 const auto &TLI = DAG.getTargetLoweringInfo();
6639 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6640 V->getType(), std::nullopt);
6641 if (RFV.occupiesMultipleRegs())
6642 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6643
6644 Op = MachineOperand::CreateReg(VMI->second, false);
6645 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6646 } else if (ArgRegsAndSizes.size() > 1) {
6647 // This was split due to the calling convention, and no virtual register
6648 // mapping exists for the value.
6649 return splitMultiRegDbgValue(ArgRegsAndSizes);
6650 }
6651 }
6652
6653 if (!Op)
6654 return false;
6655
6656 assert(Variable->isValidLocationForIntrinsic(DL) &&
6657 "Expected inlined-at fields to agree");
6658 MachineInstr *NewMI = nullptr;
6659
6660 if (Op->isReg())
6661 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6662 else
6663 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6664 Variable, Expr);
6665
6666 // Otherwise, use ArgDbgValues.
6667 FuncInfo.ArgDbgValues.push_back(NewMI);
6668 return true;
6669}
6670
6671/// Return the appropriate SDDbgValue based on N.
6672SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6673 DILocalVariable *Variable,
6674 DIExpression *Expr,
6675 const DebugLoc &dl,
6676 unsigned DbgSDNodeOrder) {
6677 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6678 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6679 // stack slot locations.
6680 //
6681 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6682 // debug values here after optimization:
6683 //
6684 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6685 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6686 //
6687 // Both describe the direct values of their associated variables.
6688 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6689 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6690 }
6691 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6692 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6693}
6694
6695static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6696 switch (Intrinsic) {
6697 case Intrinsic::smul_fix:
6698 return ISD::SMULFIX;
6699 case Intrinsic::umul_fix:
6700 return ISD::UMULFIX;
6701 case Intrinsic::smul_fix_sat:
6702 return ISD::SMULFIXSAT;
6703 case Intrinsic::umul_fix_sat:
6704 return ISD::UMULFIXSAT;
6705 case Intrinsic::sdiv_fix:
6706 return ISD::SDIVFIX;
6707 case Intrinsic::udiv_fix:
6708 return ISD::UDIVFIX;
6709 case Intrinsic::sdiv_fix_sat:
6710 return ISD::SDIVFIXSAT;
6711 case Intrinsic::udiv_fix_sat:
6712 return ISD::UDIVFIXSAT;
6713 default:
6714 llvm_unreachable("Unhandled fixed point intrinsic");
6715 }
6716}
6717
6718/// Given a @llvm.call.preallocated.setup, return the corresponding
6719/// preallocated call.
6720static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6721 assert(cast<CallBase>(PreallocatedSetup)
6723 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6724 "expected call_preallocated_setup Value");
6725 for (const auto *U : PreallocatedSetup->users()) {
6726 auto *UseCall = cast<CallBase>(U);
6727 const Function *Fn = UseCall->getCalledFunction();
6728 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6729 return UseCall;
6730 }
6731 }
6732 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6733}
6734
6735/// If DI is a debug value with an EntryValue expression, lower it using the
6736/// corresponding physical register of the associated Argument value
6737/// (guaranteed to exist by the verifier).
6738bool SelectionDAGBuilder::visitEntryValueDbgValue(
6740 DIExpression *Expr, DebugLoc DbgLoc) {
6741 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6742 return false;
6743
6744 // These properties are guaranteed by the verifier.
6745 const Argument *Arg = cast<Argument>(Values[0]);
6746 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6747
6748 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6749 if (ArgIt == FuncInfo.ValueMap.end()) {
6750 LLVM_DEBUG(
6751 dbgs() << "Dropping dbg.value: expression is entry_value but "
6752 "couldn't find an associated register for the Argument\n");
6753 return true;
6754 }
6755 Register ArgVReg = ArgIt->getSecond();
6756
6757 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6758 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6759 SDDbgValue *SDV = DAG.getVRegDbgValue(
6760 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6761 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6762 return true;
6763 }
6764 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6765 "couldn't find a physical register\n");
6766 return true;
6767}
6768
6769/// Lower the call to the specified intrinsic function.
6770void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6771 unsigned Intrinsic) {
6772 SDLoc sdl = getCurSDLoc();
6773 switch (Intrinsic) {
6774 case Intrinsic::experimental_convergence_anchor:
6775 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6776 break;
6777 case Intrinsic::experimental_convergence_entry:
6778 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6779 break;
6780 case Intrinsic::experimental_convergence_loop: {
6781 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6782 auto *Token = Bundle->Inputs[0].get();
6783 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6784 getValue(Token)));
6785 break;
6786 }
6787 }
6788}
6789
6790void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6791 unsigned IntrinsicID) {
6792 // For now, we're only lowering an 'add' histogram.
6793 // We can add others later, e.g. saturating adds, min/max.
6794 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6795 "Tried to lower unsupported histogram type");
6796 SDLoc sdl = getCurSDLoc();
6797 Value *Ptr = I.getOperand(0);
6798 SDValue Inc = getValue(I.getOperand(1));
6799 SDValue Mask = getValue(I.getOperand(2));
6800
6801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6802 DataLayout TargetDL = DAG.getDataLayout();
6803 EVT VT = Inc.getValueType();
6804 Align Alignment = DAG.getEVTAlign(VT);
6805
6806 const MDNode *Ranges = getRangeMetadata(I);
6807
6808 SDValue Root = DAG.getRoot();
6809 SDValue Base;
6810 SDValue Index;
6811 SDValue Scale;
6812 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6813 I.getParent(), VT.getScalarStoreSize());
6814
6815 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6816
6817 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6818 MachinePointerInfo(AS),
6820 MemoryLocation::UnknownSize, Alignment,
6821 MMOMetadata(I.getAAMetadata(), Ranges));
6822
6823 if (!UniformBase) {
6824 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6825 Index = getValue(Ptr);
6826 Scale =
6827 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6828 }
6829
6830 EVT IdxVT = Index.getValueType();
6831
6832 // Avoid using e.g. i32 as index type when the increment must be performed
6833 // on i64's.
6834 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6835 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6836 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6837 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6838 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6839 }
6840
6841 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6842
6843 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6844 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6845 Ops, MMO, ISD::SIGNED_SCALED);
6846
6847 setValue(&I, Histogram);
6848 DAG.setRoot(Histogram);
6849}
6850
6851void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6852 unsigned Intrinsic) {
6853 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6854 "Tried lowering invalid vector extract last");
6855 SDLoc sdl = getCurSDLoc();
6856 const DataLayout &Layout = DAG.getDataLayout();
6857 SDValue Data = getValue(I.getOperand(0));
6858 SDValue Mask = getValue(I.getOperand(1));
6859
6860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6861 EVT ResVT = TLI.getValueType(Layout, I.getType());
6862
6863 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6864 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6865 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6866
6867 Value *Default = I.getOperand(2);
6869 SDValue PassThru = getValue(Default);
6870 EVT BoolVT = Mask.getValueType().getScalarType();
6871 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6872 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6873 }
6874
6875 setValue(&I, Result);
6876}
6877
6878/// Lower the call to the specified intrinsic function.
6879void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6880 unsigned Intrinsic) {
6881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6882 SDLoc sdl = getCurSDLoc();
6883 DebugLoc dl = getCurDebugLoc();
6884 SDValue Res;
6885
6886 SDNodeFlags Flags;
6887 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6888 Flags.copyFMF(*FPOp);
6889
6890 switch (Intrinsic) {
6891 default:
6892 // By default, turn this into a target intrinsic node.
6893 visitTargetIntrinsic(I, Intrinsic);
6894 return;
6895 case Intrinsic::vscale: {
6896 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6897 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6898 return;
6899 }
6900 case Intrinsic::vastart: visitVAStart(I); return;
6901 case Intrinsic::vaend: visitVAEnd(I); return;
6902 case Intrinsic::vacopy: visitVACopy(I); return;
6903 case Intrinsic::returnaddress:
6904 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6905 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6906 getValue(I.getArgOperand(0))));
6907 return;
6908 case Intrinsic::addressofreturnaddress:
6909 setValue(&I,
6910 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6911 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6912 return;
6913 case Intrinsic::sponentry:
6914 setValue(&I,
6915 DAG.getNode(ISD::SPONENTRY, sdl,
6916 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6917 return;
6918 case Intrinsic::frameaddress:
6919 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6920 TLI.getFrameIndexTy(DAG.getDataLayout()),
6921 getValue(I.getArgOperand(0))));
6922 return;
6923 case Intrinsic::read_volatile_register:
6924 case Intrinsic::read_register: {
6925 Value *Reg = I.getArgOperand(0);
6926 SDValue Chain = getRoot();
6927 SDValue RegName =
6928 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6929 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6930 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6931 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6932 setValue(&I, Res);
6933 DAG.setRoot(Res.getValue(1));
6934 return;
6935 }
6936 case Intrinsic::write_register: {
6937 Value *Reg = I.getArgOperand(0);
6938 Value *RegValue = I.getArgOperand(1);
6939 SDValue Chain = getRoot();
6940 SDValue RegName =
6941 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6942 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6943 RegName, getValue(RegValue)));
6944 return;
6945 }
6946 case Intrinsic::write_volatile_register: {
6947 Value *Reg = I.getArgOperand(0);
6948 Value *RegValue = I.getArgOperand(1);
6949 SDValue Chain = getRoot();
6950 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6951 SDValue RegName = DAG.getMDNode(MD);
6952 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6953 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6954 Chain, RegName, getValue(RegValue));
6955 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6956 // preventing the backend from dead-eliminating the write. This is
6957 // preferred over READ_REGISTER, which would emit extra register copies
6958 // (e.g. fmov xN, dN for FP/SIMD registers).
6959 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6960 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6961 const MachineFunction &MF = DAG.getMachineFunction();
6962 Register PhysReg =
6963 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6964 if (PhysReg.isValid()) {
6965 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6966 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6967 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6968 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6969 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6970 } else {
6971 DAG.setRoot(WriteChain);
6972 }
6973 return;
6974 }
6975 case Intrinsic::memcpy:
6976 case Intrinsic::memcpy_inline: {
6977 const auto &MCI = cast<MemCpyInst>(I);
6978 SDValue Dst = getValue(I.getArgOperand(0));
6979 SDValue Src = getValue(I.getArgOperand(1));
6980 SDValue Size = getValue(I.getArgOperand(2));
6981 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6982 "memcpy_inline needs constant size");
6983 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6984 Align DstAlign = MCI.getDestAlign().valueOrOne();
6985 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6986 bool isVol = MCI.isVolatile();
6987 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6988 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
6989 isVol, MCI.isForceInlined(), &I, std::nullopt,
6990 MachinePointerInfo(I.getArgOperand(0)),
6991 MachinePointerInfo(I.getArgOperand(1)),
6992 I.getAAMetadata(), BatchAA);
6993 updateDAGForMaybeTailCall(MC);
6994 return;
6995 }
6996 case Intrinsic::memset:
6997 case Intrinsic::memset_inline: {
6998 const auto &MSII = cast<MemSetInst>(I);
6999 SDValue Dst = getValue(I.getArgOperand(0));
7000 SDValue Value = getValue(I.getArgOperand(1));
7001 SDValue Size = getValue(I.getArgOperand(2));
7002 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7003 "memset_inline needs constant size");
7004 // @llvm.memset defines 0 and 1 to both mean no alignment.
7005 Align DstAlign = MSII.getDestAlign().valueOrOne();
7006 bool isVol = MSII.isVolatile();
7007 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7008 SDValue MC = DAG.getMemset(
7009 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
7010 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
7011 updateDAGForMaybeTailCall(MC);
7012 return;
7013 }
7014 case Intrinsic::memmove: {
7015 const auto &MMI = cast<MemMoveInst>(I);
7016 SDValue Op1 = getValue(I.getArgOperand(0));
7017 SDValue Op2 = getValue(I.getArgOperand(1));
7018 SDValue Op3 = getValue(I.getArgOperand(2));
7019 // @llvm.memmove defines 0 and 1 to both mean no alignment.
7020 Align DstAlign = MMI.getDestAlign().valueOrOne();
7021 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
7022 bool isVol = MMI.isVolatile();
7023 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7024 SDValue MM = DAG.getMemmove(
7025 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
7026 /* OverrideTailCall */ std::nullopt,
7027 MachinePointerInfo(I.getArgOperand(0)),
7028 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
7029 updateDAGForMaybeTailCall(MM);
7030 return;
7031 }
7032 case Intrinsic::memcpy_element_unordered_atomic: {
7033 auto &MI = cast<AnyMemCpyInst>(I);
7034 SDValue Dst = getValue(MI.getRawDest());
7035 SDValue Src = getValue(MI.getRawSource());
7036 SDValue Length = getValue(MI.getLength());
7037
7038 Type *LengthTy = MI.getLength()->getType();
7039 unsigned ElemSz = MI.getElementSizeInBytes();
7040 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7041 SDValue MC =
7042 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7043 isTC, MachinePointerInfo(MI.getRawDest()),
7044 MachinePointerInfo(MI.getRawSource()));
7045 updateDAGForMaybeTailCall(MC);
7046 return;
7047 }
7048 case Intrinsic::memmove_element_unordered_atomic: {
7049 auto &MI = cast<AnyMemMoveInst>(I);
7050 SDValue Dst = getValue(MI.getRawDest());
7051 SDValue Src = getValue(MI.getRawSource());
7052 SDValue Length = getValue(MI.getLength());
7053
7054 Type *LengthTy = MI.getLength()->getType();
7055 unsigned ElemSz = MI.getElementSizeInBytes();
7056 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7057 SDValue MC =
7058 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7059 isTC, MachinePointerInfo(MI.getRawDest()),
7060 MachinePointerInfo(MI.getRawSource()));
7061 updateDAGForMaybeTailCall(MC);
7062 return;
7063 }
7064 case Intrinsic::memset_element_unordered_atomic: {
7065 auto &MI = cast<AnyMemSetInst>(I);
7066 SDValue Dst = getValue(MI.getRawDest());
7067 SDValue Val = getValue(MI.getValue());
7068 SDValue Length = getValue(MI.getLength());
7069
7070 Type *LengthTy = MI.getLength()->getType();
7071 unsigned ElemSz = MI.getElementSizeInBytes();
7072 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7073 SDValue MC =
7074 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
7075 isTC, MachinePointerInfo(MI.getRawDest()));
7076 updateDAGForMaybeTailCall(MC);
7077 return;
7078 }
7079 case Intrinsic::call_preallocated_setup: {
7080 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
7081 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7082 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
7083 getRoot(), SrcValue);
7084 setValue(&I, Res);
7085 DAG.setRoot(Res);
7086 return;
7087 }
7088 case Intrinsic::call_preallocated_arg: {
7089 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
7090 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7091 SDValue Ops[3];
7092 Ops[0] = getRoot();
7093 Ops[1] = SrcValue;
7094 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7095 MVT::i32); // arg index
7096 SDValue Res = DAG.getNode(
7098 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
7099 setValue(&I, Res);
7100 DAG.setRoot(Res.getValue(1));
7101 return;
7102 }
7103
7104 case Intrinsic::eh_typeid_for: {
7105 // Find the type id for the given typeinfo.
7106 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
7107 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
7108 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
7109 setValue(&I, Res);
7110 return;
7111 }
7112
7113 case Intrinsic::eh_return_i32:
7114 case Intrinsic::eh_return_i64:
7115 DAG.getMachineFunction().setCallsEHReturn(true);
7116 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
7117 MVT::Other,
7119 getValue(I.getArgOperand(0)),
7120 getValue(I.getArgOperand(1))));
7121 return;
7122 case Intrinsic::eh_unwind_init:
7123 DAG.getMachineFunction().setCallsUnwindInit(true);
7124 return;
7125 case Intrinsic::eh_dwarf_cfa:
7126 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
7127 TLI.getPointerTy(DAG.getDataLayout()),
7128 getValue(I.getArgOperand(0))));
7129 return;
7130 case Intrinsic::eh_sjlj_callsite: {
7131 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
7132 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
7133
7134 FuncInfo.setCurrentCallSite(CI->getZExtValue());
7135 return;
7136 }
7137 case Intrinsic::eh_sjlj_functioncontext: {
7138 // Get and store the index of the function context.
7139 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7140 AllocaInst *FnCtx =
7141 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
7142 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7144 return;
7145 }
7146 case Intrinsic::eh_sjlj_setjmp: {
7147 SDValue Ops[2];
7148 Ops[0] = getRoot();
7149 Ops[1] = getValue(I.getArgOperand(0));
7150 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
7151 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7152 setValue(&I, Op.getValue(0));
7153 DAG.setRoot(Op.getValue(1));
7154 return;
7155 }
7156 case Intrinsic::eh_sjlj_longjmp:
7157 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
7158 getRoot(), getValue(I.getArgOperand(0))));
7159 return;
7160 case Intrinsic::eh_sjlj_setup_dispatch:
7161 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
7162 getRoot()));
7163 return;
7164 case Intrinsic::masked_gather:
7165 visitMaskedGather(I);
7166 return;
7167 case Intrinsic::masked_load:
7168 visitMaskedLoad(I);
7169 return;
7170 case Intrinsic::masked_scatter:
7171 visitMaskedScatter(I);
7172 return;
7173 case Intrinsic::masked_store:
7174 visitMaskedStore(I);
7175 return;
7176 case Intrinsic::masked_expandload:
7177 visitMaskedLoad(I, true /* IsExpanding */);
7178 return;
7179 case Intrinsic::masked_compressstore:
7180 visitMaskedStore(I, true /* IsCompressing */);
7181 return;
7182 case Intrinsic::speculative_load:
7183 visitSpeculativeLoad(I);
7184 return;
7185 case Intrinsic::powi:
7186 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7187 getValue(I.getArgOperand(1)), DAG));
7188 return;
7189 case Intrinsic::log:
7190 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7191 return;
7192 case Intrinsic::log2:
7193 setValue(&I,
7194 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7195 return;
7196 case Intrinsic::log10:
7197 setValue(&I,
7198 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7199 return;
7200 case Intrinsic::exp:
7201 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7202 return;
7203 case Intrinsic::exp2:
7204 setValue(&I,
7205 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7206 return;
7207 case Intrinsic::pow:
7208 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7209 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7210 return;
7211 case Intrinsic::sqrt:
7212 case Intrinsic::fabs:
7213 case Intrinsic::sin:
7214 case Intrinsic::cos:
7215 case Intrinsic::tan:
7216 case Intrinsic::asin:
7217 case Intrinsic::acos:
7218 case Intrinsic::atan:
7219 case Intrinsic::sinh:
7220 case Intrinsic::cosh:
7221 case Intrinsic::tanh:
7222 case Intrinsic::exp10:
7223 case Intrinsic::floor:
7224 case Intrinsic::ceil:
7225 case Intrinsic::trunc:
7226 case Intrinsic::rint:
7227 case Intrinsic::nearbyint:
7228 case Intrinsic::round:
7229 case Intrinsic::roundeven:
7230 case Intrinsic::canonicalize: {
7231 unsigned Opcode;
7232 // clang-format off
7233 switch (Intrinsic) {
7234 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7235 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7236 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7237 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7238 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7239 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7240 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7241 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7242 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7243 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7244 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7245 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7246 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7247 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7248 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7249 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7250 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7251 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7252 case Intrinsic::round: Opcode = ISD::FROUND; break;
7253 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7254 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7255 }
7256 // clang-format on
7257
7258 setValue(&I, DAG.getNode(Opcode, sdl,
7259 getValue(I.getArgOperand(0)).getValueType(),
7260 getValue(I.getArgOperand(0)), Flags));
7261 return;
7262 }
7263 case Intrinsic::atan2:
7264 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7265 getValue(I.getArgOperand(0)).getValueType(),
7266 getValue(I.getArgOperand(0)),
7267 getValue(I.getArgOperand(1)), Flags));
7268 return;
7269 case Intrinsic::lround:
7270 case Intrinsic::llround:
7271 case Intrinsic::lrint:
7272 case Intrinsic::llrint: {
7273 unsigned Opcode;
7274 // clang-format off
7275 switch (Intrinsic) {
7276 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7277 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7278 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7279 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7280 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7281 }
7282 // clang-format on
7283
7284 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7285 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7286 getValue(I.getArgOperand(0))));
7287 return;
7288 }
7289 case Intrinsic::minnum:
7290 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7291 getValue(I.getArgOperand(0)).getValueType(),
7292 getValue(I.getArgOperand(0)),
7293 getValue(I.getArgOperand(1)), Flags));
7294 return;
7295 case Intrinsic::maxnum:
7296 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7297 getValue(I.getArgOperand(0)).getValueType(),
7298 getValue(I.getArgOperand(0)),
7299 getValue(I.getArgOperand(1)), Flags));
7300 return;
7301 case Intrinsic::minimum:
7302 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7303 getValue(I.getArgOperand(0)).getValueType(),
7304 getValue(I.getArgOperand(0)),
7305 getValue(I.getArgOperand(1)), Flags));
7306 return;
7307 case Intrinsic::maximum:
7308 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7309 getValue(I.getArgOperand(0)).getValueType(),
7310 getValue(I.getArgOperand(0)),
7311 getValue(I.getArgOperand(1)), Flags));
7312 return;
7313 case Intrinsic::minimumnum:
7314 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7315 getValue(I.getArgOperand(0)).getValueType(),
7316 getValue(I.getArgOperand(0)),
7317 getValue(I.getArgOperand(1)), Flags));
7318 return;
7319 case Intrinsic::maximumnum:
7320 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7321 getValue(I.getArgOperand(0)).getValueType(),
7322 getValue(I.getArgOperand(0)),
7323 getValue(I.getArgOperand(1)), Flags));
7324 return;
7325 case Intrinsic::copysign:
7326 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7327 getValue(I.getArgOperand(0)).getValueType(),
7328 getValue(I.getArgOperand(0)),
7329 getValue(I.getArgOperand(1)), Flags));
7330 return;
7331 case Intrinsic::ldexp:
7332 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7333 getValue(I.getArgOperand(0)).getValueType(),
7334 getValue(I.getArgOperand(0)),
7335 getValue(I.getArgOperand(1)), Flags));
7336 return;
7337 case Intrinsic::modf:
7338 case Intrinsic::sincos:
7339 case Intrinsic::sincospi:
7340 case Intrinsic::frexp: {
7341 unsigned Opcode;
7342 switch (Intrinsic) {
7343 default:
7344 llvm_unreachable("unexpected intrinsic");
7345 case Intrinsic::sincos:
7346 Opcode = ISD::FSINCOS;
7347 break;
7348 case Intrinsic::sincospi:
7349 Opcode = ISD::FSINCOSPI;
7350 break;
7351 case Intrinsic::modf:
7352 Opcode = ISD::FMODF;
7353 break;
7354 case Intrinsic::frexp:
7355 Opcode = ISD::FFREXP;
7356 break;
7357 }
7358 SmallVector<EVT, 2> ValueVTs;
7359 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7360 SDVTList VTs = DAG.getVTList(ValueVTs);
7361 setValue(
7362 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7363 return;
7364 }
7365 case Intrinsic::arithmetic_fence: {
7366 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7367 getValue(I.getArgOperand(0)).getValueType(),
7368 getValue(I.getArgOperand(0)), Flags));
7369 return;
7370 }
7371 case Intrinsic::fma:
7372 setValue(&I, DAG.getNode(
7373 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7374 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7375 getValue(I.getArgOperand(2)), Flags));
7376 return;
7377#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7378 case Intrinsic::INTRINSIC:
7379#include "llvm/IR/ConstrainedOps.def"
7380 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7381 return;
7382#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7383#include "llvm/IR/VPIntrinsics.def"
7384 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7385 return;
7386 case Intrinsic::fptrunc_round: {
7387 // Get the last argument, the metadata and convert it to an integer in the
7388 // call
7389 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7390 std::optional<RoundingMode> RoundMode =
7391 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7392
7393 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7394
7395 // Propagate fast-math-flags from IR to node(s).
7396 SDNodeFlags Flags;
7397 Flags.copyFMF(*cast<FPMathOperator>(&I));
7398 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7399
7400 SDValue Result;
7401 Result = DAG.getNode(
7402 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7403 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7404 setValue(&I, Result);
7405
7406 return;
7407 }
7408 case Intrinsic::fmuladd: {
7409 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7410 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7411 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7412 getValue(I.getArgOperand(0)).getValueType(),
7413 getValue(I.getArgOperand(0)),
7414 getValue(I.getArgOperand(1)),
7415 getValue(I.getArgOperand(2)), Flags));
7416 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7417 // TODO: Support splitting the vector.
7418 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7419 getValue(I.getArgOperand(0)).getValueType(),
7420 getValue(I.getArgOperand(0)),
7421 getValue(I.getArgOperand(1)),
7422 getValue(I.getArgOperand(2)), Flags));
7423 } else {
7424 // TODO: Intrinsic calls should have fast-math-flags.
7425 SDValue Mul = DAG.getNode(
7426 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7427 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7428 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7429 getValue(I.getArgOperand(0)).getValueType(),
7430 Mul, getValue(I.getArgOperand(2)), Flags);
7431 setValue(&I, Add);
7432 }
7433 return;
7434 }
7435 case Intrinsic::fptosi_sat: {
7436 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7437 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7438 getValue(I.getArgOperand(0)),
7439 DAG.getValueType(VT.getScalarType())));
7440 return;
7441 }
7442 case Intrinsic::fptoui_sat: {
7443 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7444 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7445 getValue(I.getArgOperand(0)),
7446 DAG.getValueType(VT.getScalarType())));
7447 return;
7448 }
7449 case Intrinsic::convert_from_arbitrary_fp: {
7450 // Extract format metadata and convert to semantics enum.
7451 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7452 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7453 StringRef FormatStr = cast<MDString>(MD)->getString();
7454 const fltSemantics *SrcSem =
7456 if (!SrcSem) {
7457 DAG.getContext()->emitError(
7458 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7459 "'");
7460 setValue(&I, DAG.getPOISON(DstVT));
7461 return;
7462 }
7464
7465 SDValue IntVal = getValue(I.getArgOperand(0));
7466
7467 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7468 SDValue SemConst =
7469 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7470 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7471 SemConst));
7472 return;
7473 }
7474 case Intrinsic::convert_to_arbitrary_fp: {
7475 // Extract format metadata and convert to semantics enum.
7476 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7477 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7478 StringRef FormatStr = cast<MDString>(MD)->getString();
7479 const fltSemantics *DstSem =
7481 if (!DstSem) {
7482 DAG.getContext()->emitError(
7483 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7484 "'");
7485 setValue(&I, DAG.getPOISON(DstVT));
7486 return;
7487 }
7489
7490 Metadata *RoundMD =
7491 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7492 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7493 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7494 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7495 "Dynamic rounding mode should have been rejected by the verifier");
7496
7497 uint64_t Saturate =
7498 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7499
7500 SDValue FloatVal = getValue(I.getArgOperand(0));
7501
7502 SDValue SemConst =
7503 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7504 SDValue RoundConst =
7505 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7506 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7507 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7508 SemConst, RoundConst, SatConst));
7509 return;
7510 }
7511 case Intrinsic::set_rounding:
7512 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7513 {getRoot(), getValue(I.getArgOperand(0))});
7514 setValue(&I, Res);
7515 DAG.setRoot(Res.getValue(0));
7516 return;
7517 case Intrinsic::is_fpclass: {
7518 const DataLayout DLayout = DAG.getDataLayout();
7519 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7520 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7521 FPClassTest Test = static_cast<FPClassTest>(
7522 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7523 MachineFunction &MF = DAG.getMachineFunction();
7524 const Function &F = MF.getFunction();
7525 SDValue Op = getValue(I.getArgOperand(0));
7526 SDNodeFlags Flags;
7527 Flags.setNoFPExcept(
7528 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7529 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7530 // expansion can use illegal types. Making expansion early allows
7531 // legalizing these types prior to selection.
7532 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7533 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7534 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7535 setValue(&I, Result);
7536 return;
7537 }
7538
7539 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7540 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7541 setValue(&I, V);
7542 return;
7543 }
7544 case Intrinsic::get_fpenv: {
7545 const DataLayout DLayout = DAG.getDataLayout();
7546 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7547 Align TempAlign = DAG.getEVTAlign(EnvVT);
7548 SDValue Chain = getRoot();
7549 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7550 // and temporary storage in stack.
7551 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7552 Res = DAG.getNode(
7553 ISD::GET_FPENV, sdl,
7554 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7555 MVT::Other),
7556 Chain);
7557 } else {
7558 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7559 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7560 auto MPI =
7561 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7562 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7564 TempAlign);
7565 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7566 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7567 }
7568 setValue(&I, Res);
7569 DAG.setRoot(Res.getValue(1));
7570 return;
7571 }
7572 case Intrinsic::set_fpenv: {
7573 const DataLayout DLayout = DAG.getDataLayout();
7574 SDValue Env = getValue(I.getArgOperand(0));
7575 EVT EnvVT = Env.getValueType();
7576 Align TempAlign = DAG.getEVTAlign(EnvVT);
7577 SDValue Chain = getRoot();
7578 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7579 // environment from memory.
7580 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7581 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7582 } else {
7583 // Allocate space in stack, copy environment bits into it and use this
7584 // memory in SET_FPENV_MEM.
7585 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7586 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7587 auto MPI =
7588 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7589 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7591 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7593 TempAlign);
7594 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7595 }
7596 DAG.setRoot(Chain);
7597 return;
7598 }
7599 case Intrinsic::reset_fpenv:
7600 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7601 return;
7602 case Intrinsic::get_fpmode:
7603 Res = DAG.getNode(
7604 ISD::GET_FPMODE, sdl,
7605 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7606 MVT::Other),
7607 DAG.getRoot());
7608 setValue(&I, Res);
7609 DAG.setRoot(Res.getValue(1));
7610 return;
7611 case Intrinsic::set_fpmode:
7612 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7613 getValue(I.getArgOperand(0)));
7614 DAG.setRoot(Res);
7615 return;
7616 case Intrinsic::reset_fpmode: {
7617 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7618 DAG.setRoot(Res);
7619 return;
7620 }
7621 case Intrinsic::pcmarker: {
7622 SDValue Tmp = getValue(I.getArgOperand(0));
7623 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7624 return;
7625 }
7626 case Intrinsic::readcyclecounter: {
7627 SDValue Op = getRoot();
7628 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7629 DAG.getVTList(MVT::i64, MVT::Other), Op);
7630 setValue(&I, Res);
7631 DAG.setRoot(Res.getValue(1));
7632 return;
7633 }
7634 case Intrinsic::readsteadycounter: {
7635 SDValue Op = getRoot();
7636 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7637 DAG.getVTList(MVT::i64, MVT::Other), Op);
7638 setValue(&I, Res);
7639 DAG.setRoot(Res.getValue(1));
7640 return;
7641 }
7642 case Intrinsic::bitreverse:
7643 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7644 getValue(I.getArgOperand(0)).getValueType(),
7645 getValue(I.getArgOperand(0))));
7646 return;
7647 case Intrinsic::bswap:
7648 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7649 getValue(I.getArgOperand(0)).getValueType(),
7650 getValue(I.getArgOperand(0))));
7651 return;
7652 case Intrinsic::cttz: {
7653 SDValue Arg = getValue(I.getArgOperand(0));
7654 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7655 EVT Ty = Arg.getValueType();
7656 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7657 sdl, Ty, Arg));
7658 return;
7659 }
7660 case Intrinsic::ctlz: {
7661 SDValue Arg = getValue(I.getArgOperand(0));
7662 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7663 EVT Ty = Arg.getValueType();
7664 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7665 sdl, Ty, Arg));
7666 return;
7667 }
7668 case Intrinsic::ctpop: {
7669 SDValue Arg = getValue(I.getArgOperand(0));
7670 EVT Ty = Arg.getValueType();
7671 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7672 return;
7673 }
7674 case Intrinsic::fshl:
7675 case Intrinsic::fshr: {
7676 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7677 SDValue X = getValue(I.getArgOperand(0));
7678 SDValue Y = getValue(I.getArgOperand(1));
7679 SDValue Z = getValue(I.getArgOperand(2));
7680 EVT VT = X.getValueType();
7681
7682 if (X == Y) {
7683 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7684 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7685 } else {
7686 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7687 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7688 }
7689 return;
7690 }
7691 case Intrinsic::clmul: {
7692 SDValue X = getValue(I.getArgOperand(0));
7693 SDValue Y = getValue(I.getArgOperand(1));
7694 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7695 return;
7696 }
7697 case Intrinsic::pext: {
7698 SDValue X = getValue(I.getArgOperand(0));
7699 SDValue Y = getValue(I.getArgOperand(1));
7700 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7701 return;
7702 }
7703 case Intrinsic::pdep: {
7704 SDValue X = getValue(I.getArgOperand(0));
7705 SDValue Y = getValue(I.getArgOperand(1));
7706 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7707 return;
7708 }
7709 case Intrinsic::smulh:
7710 case Intrinsic::umulh: {
7711 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7712 SDValue X = getValue(I.getArgOperand(0));
7713 SDValue Y = getValue(I.getArgOperand(1));
7714 setValue(&I, DAG.getNode(Opc, sdl, X.getValueType(), X, Y));
7715 return;
7716 }
7717 case Intrinsic::sadd_sat: {
7718 SDValue Op1 = getValue(I.getArgOperand(0));
7719 SDValue Op2 = getValue(I.getArgOperand(1));
7720 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7721 return;
7722 }
7723 case Intrinsic::uadd_sat: {
7724 SDValue Op1 = getValue(I.getArgOperand(0));
7725 SDValue Op2 = getValue(I.getArgOperand(1));
7726 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7727 return;
7728 }
7729 case Intrinsic::ssub_sat: {
7730 SDValue Op1 = getValue(I.getArgOperand(0));
7731 SDValue Op2 = getValue(I.getArgOperand(1));
7732 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7733 return;
7734 }
7735 case Intrinsic::usub_sat: {
7736 SDValue Op1 = getValue(I.getArgOperand(0));
7737 SDValue Op2 = getValue(I.getArgOperand(1));
7738 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7739 return;
7740 }
7741 case Intrinsic::sshl_sat:
7742 case Intrinsic::ushl_sat: {
7743 SDValue Op1 = getValue(I.getArgOperand(0));
7744 SDValue Op2 = getValue(I.getArgOperand(1));
7745
7746 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7747 Op1.getValueType(), DAG.getDataLayout());
7748
7749 // Coerce the shift amount to the right type if we can. This exposes the
7750 // truncate or zext to optimization early.
7751 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7752 assert(ShiftTy.getSizeInBits() >=
7754 "Unexpected shift type");
7755 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7756 }
7757
7758 unsigned Opc =
7759 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7760 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7761 return;
7762 }
7763 case Intrinsic::smul_fix:
7764 case Intrinsic::umul_fix:
7765 case Intrinsic::smul_fix_sat:
7766 case Intrinsic::umul_fix_sat: {
7767 SDValue Op1 = getValue(I.getArgOperand(0));
7768 SDValue Op2 = getValue(I.getArgOperand(1));
7769 SDValue Op3 = getValue(I.getArgOperand(2));
7770 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7771 Op1.getValueType(), Op1, Op2, Op3));
7772 return;
7773 }
7774 case Intrinsic::sdiv_fix:
7775 case Intrinsic::udiv_fix:
7776 case Intrinsic::sdiv_fix_sat:
7777 case Intrinsic::udiv_fix_sat: {
7778 SDValue Op1 = getValue(I.getArgOperand(0));
7779 SDValue Op2 = getValue(I.getArgOperand(1));
7780 SDValue Op3 = getValue(I.getArgOperand(2));
7782 Op1, Op2, Op3, DAG, TLI));
7783 return;
7784 }
7785 case Intrinsic::smax: {
7786 SDValue Op1 = getValue(I.getArgOperand(0));
7787 SDValue Op2 = getValue(I.getArgOperand(1));
7788 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7789 return;
7790 }
7791 case Intrinsic::smin: {
7792 SDValue Op1 = getValue(I.getArgOperand(0));
7793 SDValue Op2 = getValue(I.getArgOperand(1));
7794 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7795 return;
7796 }
7797 case Intrinsic::umax: {
7798 SDValue Op1 = getValue(I.getArgOperand(0));
7799 SDValue Op2 = getValue(I.getArgOperand(1));
7800 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7801 return;
7802 }
7803 case Intrinsic::umin: {
7804 SDValue Op1 = getValue(I.getArgOperand(0));
7805 SDValue Op2 = getValue(I.getArgOperand(1));
7806 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7807 return;
7808 }
7809 case Intrinsic::abs: {
7810 SDValue Op1 = getValue(I.getArgOperand(0));
7811 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7812 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7813 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7814 return;
7815 }
7816 case Intrinsic::scmp: {
7817 SDValue Op1 = getValue(I.getArgOperand(0));
7818 SDValue Op2 = getValue(I.getArgOperand(1));
7819 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7820 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7821 break;
7822 }
7823 case Intrinsic::ucmp: {
7824 SDValue Op1 = getValue(I.getArgOperand(0));
7825 SDValue Op2 = getValue(I.getArgOperand(1));
7826 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7827 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7828 break;
7829 }
7830 case Intrinsic::stackaddress:
7831 case Intrinsic::stacksave: {
7832 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7834 SDValue Op = getRoot();
7835 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7836 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7837 setValue(&I, Res);
7838 DAG.setRoot(Res.getValue(1));
7839 return;
7840 }
7841 case Intrinsic::stackrestore:
7842 Res = getValue(I.getArgOperand(0));
7843 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7844 return;
7845 case Intrinsic::get_dynamic_area_offset: {
7846 SDValue Op = getRoot();
7847 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7848 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7849 Op);
7850 DAG.setRoot(Op);
7851 setValue(&I, Res);
7852 return;
7853 }
7854 case Intrinsic::stackguard: {
7855 MachineFunction &MF = DAG.getMachineFunction();
7856 const Module &M = *MF.getFunction().getParent();
7857 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7858 SDValue Chain = getRoot();
7859 if (TLI.useLoadStackGuardNode(M)) {
7860 Res = getLoadStackGuard(DAG, sdl, Chain);
7861 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7862 } else {
7863 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7864 if (!Global) {
7865 LLVMContext &Ctx = *DAG.getContext();
7866 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7867 setValue(&I, DAG.getPOISON(PtrTy));
7868 return;
7869 }
7870
7871 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7872 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7873 MachinePointerInfo(Global, 0), Align,
7875 }
7876 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7877 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7878 // post-RA expansion of LOAD_STACK_GUARD.
7879 if (TLI.useStackGuardMixFP() && !TLI.useLoadStackGuardNode(M))
7880 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7881 DAG.setRoot(Chain);
7882 setValue(&I, Res);
7883 return;
7884 }
7885 case Intrinsic::stackprotector: {
7886 // Emit code into the DAG to store the stack guard onto the stack.
7887 MachineFunction &MF = DAG.getMachineFunction();
7888 MachineFrameInfo &MFI = MF.getFrameInfo();
7889 const Module &M = *MF.getFunction().getParent();
7890 SDValue Src, Chain = getRoot();
7891
7892 if (TLI.useLoadStackGuardNode(M))
7893 Src = getLoadStackGuard(DAG, sdl, Chain);
7894 else
7895 Src = getValue(I.getArgOperand(0)); // The guard's value.
7896
7897 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7898
7899 int FI = FuncInfo.StaticAllocaMap[Slot];
7900 MFI.setStackProtectorIndex(FI);
7901 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7902
7903 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7904
7905 // Store the stack protector onto the stack.
7906 Res = DAG.getStore(
7907 Chain, sdl, Src, FIN,
7908 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7909 MaybeAlign(), MachineMemOperand::MOVolatile);
7910 setValue(&I, Res);
7911 DAG.setRoot(Res);
7912 return;
7913 }
7914 case Intrinsic::objectsize:
7915 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7916
7917 case Intrinsic::is_constant:
7918 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7919
7920 case Intrinsic::annotation:
7921 case Intrinsic::ptr_annotation:
7922 case Intrinsic::launder_invariant_group:
7923 // Drop the intrinsic, but forward the value
7924 setValue(&I, getValue(I.getOperand(0)));
7925 return;
7926
7927 case Intrinsic::type_test:
7928 case Intrinsic::public_type_test:
7929 case Intrinsic::type_checked_load:
7930 case Intrinsic::type_checked_load_relative: {
7931 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7932 // before code generation. Surviving until here usually indicates a
7933 // misconfiguration, for instance when devirtualization is enabled but LTO
7934 // does not actually run.
7935 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7936 *I.getFunction(),
7937 Intrinsic::getBaseName(Intrinsic) +
7938 " intrinsic must be lowered by the LowerTypeTests pass "
7939 "before code generation",
7940 sdl.getDebugLoc()));
7941
7942 // Lower the result to poison so that compilation can continue and collect
7943 // any further diagnostics.
7944 setValueToPoison(&I, sdl);
7945 return;
7946 }
7947
7948 case Intrinsic::assume:
7949 case Intrinsic::experimental_noalias_scope_decl:
7950 case Intrinsic::var_annotation:
7951 case Intrinsic::sideeffect:
7952 // Discard annotate attributes, noalias scope declarations, assumptions, and
7953 // artificial side-effects.
7954 return;
7955
7956 case Intrinsic::codeview_annotation: {
7957 // Emit a label associated with this metadata.
7958 MachineFunction &MF = DAG.getMachineFunction();
7959 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7960 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7961 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7962 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7963 DAG.setRoot(Res);
7964 return;
7965 }
7966
7967 case Intrinsic::init_trampoline: {
7968 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7969
7970 SDValue Ops[6];
7971 Ops[0] = getRoot();
7972 Ops[1] = getValue(I.getArgOperand(0));
7973 Ops[2] = getValue(I.getArgOperand(1));
7974 Ops[3] = getValue(I.getArgOperand(2));
7975 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7976 Ops[5] = DAG.getSrcValue(F);
7977
7978 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7979
7980 DAG.setRoot(Res);
7981 return;
7982 }
7983 case Intrinsic::adjust_trampoline:
7984 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7985 TLI.getPointerTy(DAG.getDataLayout()),
7986 getValue(I.getArgOperand(0))));
7987 return;
7988 case Intrinsic::gcroot: {
7989 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7990 "only valid in functions with gc specified, enforced by Verifier");
7991 assert(GFI && "implied by previous");
7992 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7993 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7994
7995 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7996 GFI->addStackRoot(FI->getIndex(), TypeMap);
7997 return;
7998 }
7999 case Intrinsic::gcread:
8000 case Intrinsic::gcwrite:
8001 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
8002 case Intrinsic::get_rounding:
8003 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
8004 setValue(&I, Res);
8005 DAG.setRoot(Res.getValue(1));
8006 return;
8007
8008 case Intrinsic::expect:
8009 case Intrinsic::expect_with_probability:
8010 // Just replace __builtin_expect(exp, c) and
8011 // __builtin_expect_with_probability(exp, c, p) with EXP.
8012 setValue(&I, getValue(I.getArgOperand(0)));
8013 return;
8014
8015 case Intrinsic::ubsantrap:
8016 case Intrinsic::debugtrap:
8017 case Intrinsic::trap: {
8018 StringRef TrapFuncName =
8019 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
8020 if (TrapFuncName.empty()) {
8021 switch (Intrinsic) {
8022 case Intrinsic::trap:
8023 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
8024 break;
8025 case Intrinsic::debugtrap:
8026 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
8027 break;
8028 case Intrinsic::ubsantrap:
8029 DAG.setRoot(DAG.getNode(
8030 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
8031 DAG.getTargetConstant(
8032 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
8033 MVT::i32)));
8034 break;
8035 default: llvm_unreachable("unknown trap intrinsic");
8036 }
8037 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
8038 I.hasFnAttr(Attribute::NoMerge));
8039 return;
8040 }
8042 if (Intrinsic == Intrinsic::ubsantrap) {
8043 Value *Arg = I.getArgOperand(0);
8044 Args.emplace_back(Arg, getValue(Arg));
8045 }
8046
8047 TargetLowering::CallLoweringInfo CLI(DAG);
8048 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
8049 CallingConv::C, I.getType(),
8050 DAG.getExternalSymbol(TrapFuncName.data(),
8051 TLI.getPointerTy(DAG.getDataLayout())),
8052 std::move(Args));
8053 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
8054 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8055 DAG.setRoot(Result.second);
8056 return;
8057 }
8058
8059 case Intrinsic::allow_runtime_check:
8060 case Intrinsic::allow_ubsan_check:
8061 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
8062 return;
8063
8064 case Intrinsic::uadd_with_overflow:
8065 case Intrinsic::sadd_with_overflow:
8066 case Intrinsic::usub_with_overflow:
8067 case Intrinsic::ssub_with_overflow:
8068 case Intrinsic::umul_with_overflow:
8069 case Intrinsic::smul_with_overflow: {
8071 switch (Intrinsic) {
8072 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8073 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
8074 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
8075 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
8076 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
8077 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
8078 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
8079 }
8080 SDValue Op1 = getValue(I.getArgOperand(0));
8081 SDValue Op2 = getValue(I.getArgOperand(1));
8082
8083 EVT ResultVT = Op1.getValueType();
8084 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
8085
8086 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
8087 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
8088 return;
8089 }
8090 case Intrinsic::prefetch: {
8091 SDValue Ops[5];
8092 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8094 Ops[0] = DAG.getRoot();
8095 Ops[1] = getValue(I.getArgOperand(0));
8096 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
8097 MVT::i32);
8098 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
8099 MVT::i32);
8100 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
8101 MVT::i32);
8102 SDValue Result = DAG.getMemIntrinsicNode(
8103 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
8104 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
8105 /* align */ std::nullopt, Flags);
8106
8107 // Chain the prefetch in parallel with any pending loads, to stay out of
8108 // the way of later optimizations.
8109 PendingLoads.push_back(Result);
8110 Result = getRoot();
8111 DAG.setRoot(Result);
8112 return;
8113 }
8114 case Intrinsic::lifetime_start:
8115 case Intrinsic::lifetime_end: {
8116 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
8117 // Stack coloring is not enabled in O0, discard region information.
8118 if (TM.getOptLevel() == CodeGenOptLevel::None)
8119 return;
8120
8121 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
8122 if (!LifetimeObject)
8123 return;
8124
8125 // First check that the Alloca is static, otherwise it won't have a
8126 // valid frame index.
8127 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
8128 if (SI == FuncInfo.StaticAllocaMap.end())
8129 return;
8130
8131 const int FrameIndex = SI->second;
8132 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
8133 DAG.setRoot(Res);
8134 return;
8135 }
8136 case Intrinsic::pseudoprobe: {
8137 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
8138 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8139 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
8140 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
8141 DAG.setRoot(Res);
8142 return;
8143 }
8144 case Intrinsic::invariant_start:
8145 // Discard region information.
8146 setValue(&I,
8147 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
8148 return;
8149 case Intrinsic::invariant_end:
8150 // Discard region information.
8151 return;
8152 case Intrinsic::clear_cache: {
8153 SDValue InputChain = DAG.getRoot();
8154 SDValue StartVal = getValue(I.getArgOperand(0));
8155 SDValue EndVal = getValue(I.getArgOperand(1));
8156 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
8157 {InputChain, StartVal, EndVal});
8158 setValue(&I, Res);
8159 DAG.setRoot(Res);
8160 return;
8161 }
8162 case Intrinsic::donothing:
8163 case Intrinsic::seh_try_begin:
8164 case Intrinsic::seh_scope_begin:
8165 case Intrinsic::seh_try_end:
8166 case Intrinsic::seh_scope_end:
8167 // ignore
8168 return;
8169 case Intrinsic::experimental_stackmap:
8170 visitStackmap(I);
8171 return;
8172 case Intrinsic::experimental_patchpoint_void:
8173 case Intrinsic::experimental_patchpoint:
8174 visitPatchpoint(I);
8175 return;
8176 case Intrinsic::experimental_gc_statepoint:
8178 return;
8179 case Intrinsic::experimental_gc_result:
8180 visitGCResult(cast<GCResultInst>(I));
8181 return;
8182 case Intrinsic::experimental_gc_relocate:
8183 visitGCRelocate(cast<GCRelocateInst>(I));
8184 return;
8185 case Intrinsic::instrprof_cover:
8186 llvm_unreachable("instrprof failed to lower a cover");
8187 case Intrinsic::instrprof_increment:
8188 llvm_unreachable("instrprof failed to lower an increment");
8189 case Intrinsic::instrprof_timestamp:
8190 llvm_unreachable("instrprof failed to lower a timestamp");
8191 case Intrinsic::instrprof_value_profile:
8192 llvm_unreachable("instrprof failed to lower a value profiling call");
8193 case Intrinsic::instrprof_mcdc_parameters:
8194 llvm_unreachable("instrprof failed to lower mcdc parameters");
8195 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8196 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8197 case Intrinsic::localescape: {
8198 MachineFunction &MF = DAG.getMachineFunction();
8199 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8200
8201 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8202 // is the same on all targets.
8203 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8204 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8205 if (isa<ConstantPointerNull>(Arg))
8206 continue; // Skip null pointers. They represent a hole in index space.
8207 AllocaInst *Slot = cast<AllocaInst>(Arg);
8208 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8209 "can only escape static allocas");
8210 int FI = FuncInfo.StaticAllocaMap[Slot];
8211 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8213 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8214 TII->get(TargetOpcode::LOCAL_ESCAPE))
8215 .addSym(FrameAllocSym)
8216 .addFrameIndex(FI);
8217 }
8218
8219 return;
8220 }
8221
8222 case Intrinsic::localrecover: {
8223 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8224 MachineFunction &MF = DAG.getMachineFunction();
8225
8226 // Get the symbol that defines the frame offset.
8227 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8228 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8229 unsigned IdxVal =
8230 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8231 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8233
8234 Value *FP = I.getArgOperand(1);
8235 SDValue FPVal = getValue(FP);
8236 EVT PtrVT = FPVal.getValueType();
8237
8238 // Create a MCSymbol for the label to avoid any target lowering
8239 // that would make this PC relative.
8240 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8241 SDValue OffsetVal =
8242 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8243
8244 // Add the offset to the FP.
8245 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8246 setValue(&I, Add);
8247
8248 return;
8249 }
8250
8251 case Intrinsic::fake_use: {
8252 Value *V = I.getArgOperand(0);
8253 SDValue Ops[2];
8254 // For Values not declared or previously used in this basic block, the
8255 // NodeMap will not have an entry, and `getValue` will assert if V has no
8256 // valid register value.
8257 auto FakeUseValue = [&]() -> SDValue {
8258 SDValue &N = NodeMap[V];
8259 if (N.getNode())
8260 return N;
8261
8262 // If there's a virtual register allocated and initialized for this
8263 // value, use it.
8264 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8265 return copyFromReg;
8266 // FIXME: Do we want to preserve constants? It seems pointless.
8267 if (isa<Constant>(V))
8268 return getValue(V);
8269 return SDValue();
8270 }();
8271 if (!FakeUseValue || FakeUseValue.isUndef())
8272 return;
8273 Ops[0] = getRoot();
8274 Ops[1] = FakeUseValue;
8275 // Also, do not translate a fake use with an undef operand, or any other
8276 // empty SDValues.
8277 if (!Ops[1] || Ops[1].isUndef())
8278 return;
8279 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8280 return;
8281 }
8282
8283 case Intrinsic::reloc_none: {
8284 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8285 StringRef SymbolName = cast<MDString>(MD)->getString();
8286 SDValue Ops[2] = {
8287 getRoot(),
8288 DAG.getTargetExternalSymbol(
8289 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8290 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8291 return;
8292 }
8293
8294 case Intrinsic::cond_loop: {
8295 SDValue InputChain = DAG.getRoot();
8296 SDValue P = getValue(I.getArgOperand(0));
8297 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8298 {InputChain, P});
8299 setValue(&I, Res);
8300 DAG.setRoot(Res);
8301 return;
8302 }
8303
8304 case Intrinsic::eh_exceptionpointer:
8305 case Intrinsic::eh_exceptioncode: {
8306 // Get the exception pointer vreg, copy from it, and resize it to fit.
8307 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8308 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8309 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8310 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8311 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8312 if (Intrinsic == Intrinsic::eh_exceptioncode)
8313 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8314 setValue(&I, N);
8315 return;
8316 }
8317 case Intrinsic::xray_customevent: {
8318 // Here we want to make sure that the intrinsic behaves as if it has a
8319 // specific calling convention.
8320 const auto &Triple = DAG.getTarget().getTargetTriple();
8321 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8322 Triple.getArch() != Triple::hexagon)
8323 return;
8324
8326
8327 // We want to say that we always want the arguments in registers.
8328 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8329 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8331 SDValue Chain = getRoot();
8332 Ops.push_back(LogEntryVal);
8333 Ops.push_back(StrSizeVal);
8334 Ops.push_back(Chain);
8335
8336 // We need to enforce the calling convention for the callsite, so that
8337 // argument ordering is enforced correctly, and that register allocation can
8338 // see that some registers may be assumed clobbered and have to preserve
8339 // them across calls to the intrinsic.
8340 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8341 sdl, NodeTys, Ops);
8342 SDValue patchableNode = SDValue(MN, 0);
8343 DAG.setRoot(patchableNode);
8344 setValue(&I, patchableNode);
8345 return;
8346 }
8347 case Intrinsic::xray_typedevent: {
8348 // Here we want to make sure that the intrinsic behaves as if it has a
8349 // specific calling convention.
8350 const auto &Triple = DAG.getTarget().getTargetTriple();
8351 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8352 Triple.getArch() != Triple::hexagon)
8353 return;
8354
8356
8357 // We want to say that we always want the arguments in registers.
8358 // It's unclear to me how manipulating the selection DAG here forces callers
8359 // to provide arguments in registers instead of on the stack.
8360 SDValue LogTypeId = getValue(I.getArgOperand(0));
8361 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8362 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8363 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8364 SDValue Chain = getRoot();
8365 Ops.push_back(LogTypeId);
8366 Ops.push_back(LogEntryVal);
8367 Ops.push_back(StrSizeVal);
8368 Ops.push_back(Chain);
8369
8370 // We need to enforce the calling convention for the callsite, so that
8371 // argument ordering is enforced correctly, and that register allocation can
8372 // see that some registers may be assumed clobbered and have to preserve
8373 // them across calls to the intrinsic.
8374 MachineSDNode *MN = DAG.getMachineNode(
8375 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8376 SDValue patchableNode = SDValue(MN, 0);
8377 DAG.setRoot(patchableNode);
8378 setValue(&I, patchableNode);
8379 return;
8380 }
8381 case Intrinsic::experimental_deoptimize:
8383 return;
8384 case Intrinsic::stepvector:
8385 visitStepVector(I);
8386 return;
8387 case Intrinsic::vector_reduce_fadd:
8388 case Intrinsic::vector_reduce_fmul:
8389 case Intrinsic::vector_reduce_add:
8390 case Intrinsic::vector_reduce_mul:
8391 case Intrinsic::vector_reduce_and:
8392 case Intrinsic::vector_reduce_or:
8393 case Intrinsic::vector_reduce_xor:
8394 case Intrinsic::vector_reduce_smax:
8395 case Intrinsic::vector_reduce_smin:
8396 case Intrinsic::vector_reduce_umax:
8397 case Intrinsic::vector_reduce_umin:
8398 case Intrinsic::vector_reduce_fmax:
8399 case Intrinsic::vector_reduce_fmin:
8400 case Intrinsic::vector_reduce_fmaximum:
8401 case Intrinsic::vector_reduce_fminimum:
8402 case Intrinsic::vector_reduce_fmaximumnum:
8403 case Intrinsic::vector_reduce_fminimumnum:
8404 visitVectorReduce(I, Intrinsic);
8405 return;
8406
8407 case Intrinsic::icall_branch_funnel: {
8409 Ops.push_back(getValue(I.getArgOperand(0)));
8410
8411 int64_t Offset;
8413 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8414 if (!Base)
8416 "llvm.icall.branch.funnel operand must be a GlobalValue");
8417 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8418
8419 struct BranchFunnelTarget {
8420 int64_t Offset;
8421 SDValue Target;
8422 };
8424
8425 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8427 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8428 if (ElemBase != Base)
8429 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8430 "to the same GlobalValue");
8431
8432 SDValue Val = getValue(I.getArgOperand(Op + 1));
8433 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8434 if (!GA)
8436 "llvm.icall.branch.funnel operand must be a GlobalValue");
8437 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8438 GA->getGlobal(), sdl, Val.getValueType(),
8439 GA->getOffset())});
8440 }
8441 llvm::sort(Targets,
8442 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8443 return T1.Offset < T2.Offset;
8444 });
8445
8446 for (auto &T : Targets) {
8447 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8448 Ops.push_back(T.Target);
8449 }
8450
8451 Ops.push_back(DAG.getRoot()); // Chain
8452 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8453 MVT::Other, Ops),
8454 0);
8455 DAG.setRoot(N);
8456 setValue(&I, N);
8457 HasTailCall = true;
8458 return;
8459 }
8460
8461 case Intrinsic::wasm_landingpad_index:
8462 // Information this intrinsic contained has been transferred to
8463 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8464 // delete it now.
8465 return;
8466
8467 case Intrinsic::aarch64_settag:
8468 case Intrinsic::aarch64_settag_zero: {
8469 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8470 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8471 SDValue Val = TSI.EmitTargetCodeForSetTag(
8472 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8473 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8474 ZeroMemory);
8475 DAG.setRoot(Val);
8476 setValue(&I, Val);
8477 return;
8478 }
8479 case Intrinsic::amdgcn_cs_chain: {
8480 // At this point we don't care if it's amdgpu_cs_chain or
8481 // amdgpu_cs_chain_preserve.
8483
8484 Type *RetTy = I.getType();
8485 assert(RetTy->isVoidTy() && "Should not return");
8486
8487 SDValue Callee = getValue(I.getOperand(0));
8488
8489 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8490 // We'll also tack the value of the EXEC mask at the end.
8492 Args.reserve(3);
8493
8494 for (unsigned Idx : {2, 3, 1}) {
8495 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8496 I.getOperand(Idx)->getType());
8497 Arg.setAttributes(&I, Idx);
8498 Args.push_back(Arg);
8499 }
8500
8501 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8502 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8503 Args[2].IsInReg = true; // EXEC should be inreg
8504
8505 // Forward the flags and any additional arguments.
8506 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8507 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8508 I.getOperand(Idx)->getType());
8509 Arg.setAttributes(&I, Idx);
8510 Args.push_back(Arg);
8511 }
8512
8513 TargetLowering::CallLoweringInfo CLI(DAG);
8514 CLI.setDebugLoc(getCurSDLoc())
8515 .setChain(getRoot())
8516 .setCallee(CC, RetTy, Callee, std::move(Args))
8517 .setNoReturn(true)
8518 .setTailCall(true)
8519 .setConvergent(I.isConvergent());
8520 CLI.CB = &I;
8521 std::pair<SDValue, SDValue> Result =
8522 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8523 (void)Result;
8524 assert(!Result.first.getNode() && !Result.second.getNode() &&
8525 "Should've lowered as tail call");
8526
8527 HasTailCall = true;
8528 return;
8529 }
8530 case Intrinsic::amdgcn_call_whole_wave: {
8532 bool isTailCall = I.isTailCall();
8533
8534 // The first argument is the callee. Skip it when assembling the call args.
8535 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8536 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8537 I.getArgOperand(Idx)->getType());
8538 Arg.setAttributes(&I, Idx);
8539
8540 // If we have an explicit sret argument that is an Instruction, (i.e., it
8541 // might point to function-local memory), we can't meaningfully tail-call.
8542 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8543 isTailCall = false;
8544
8545 Args.push_back(Arg);
8546 }
8547
8548 SDValue ConvControlToken;
8549 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8550 auto *Token = Bundle->Inputs[0].get();
8551 ConvControlToken = getValue(Token);
8552 }
8553
8554 TargetLowering::CallLoweringInfo CLI(DAG);
8555 CLI.setDebugLoc(getCurSDLoc())
8556 .setChain(getRoot())
8557 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8558 getValue(I.getArgOperand(0)), std::move(Args))
8559 .setTailCall(isTailCall && canTailCall(I))
8560 .setIsPreallocated(
8561 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8562 .setConvergent(I.isConvergent())
8563 .setConvergenceControlToken(ConvControlToken);
8564 CLI.CB = &I;
8565
8566 std::pair<SDValue, SDValue> Result =
8567 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8568
8569 if (Result.first.getNode())
8570 setValue(&I, Result.first);
8571 return;
8572 }
8573 case Intrinsic::ptrmask: {
8574 SDValue Ptr = getValue(I.getOperand(0));
8575 SDValue Mask = getValue(I.getOperand(1));
8576
8577 // On arm64_32, pointers are 32 bits when stored in memory, but
8578 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8579 // match the index type, but the pointer is 64 bits, so the mask must be
8580 // zero-extended up to 64 bits to match the pointer.
8581 EVT PtrVT =
8582 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8583 EVT MemVT =
8584 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8585 assert(PtrVT == Ptr.getValueType());
8586 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8587 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8588 // 128-bit, so we have to pad the mask with ones for unused bits.
8589 auto HighOnes = DAG.getNode(
8590 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8591 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8592 PtrVT, sdl));
8593 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8594 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8595 } else if (Mask.getValueType() != PtrVT)
8596 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8597
8598 assert(Mask.getValueType() == PtrVT);
8599 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8600 return;
8601 }
8602 case Intrinsic::threadlocal_address: {
8603 setValue(&I, getValue(I.getOperand(0)));
8604 return;
8605 }
8606 case Intrinsic::get_active_lane_mask: {
8607 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8608 SDValue Index = getValue(I.getOperand(0));
8609 SDValue TripCount = getValue(I.getOperand(1));
8610 EVT ElementVT = Index.getValueType();
8611
8612 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8613 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8614 TripCount));
8615 return;
8616 }
8617
8618 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8619 CCVT.getVectorElementCount());
8620
8621 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8622 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8623 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8624 SDValue VectorInduction = DAG.getNode(
8625 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8626 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8627 VectorTripCount, ISD::CondCode::SETULT);
8628 setValue(&I, SetCC);
8629 return;
8630 }
8631 case Intrinsic::experimental_get_vector_length: {
8632 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8633 "Expected positive VF");
8634 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8635 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8636
8637 SDValue Count = getValue(I.getOperand(0));
8638 EVT CountVT = Count.getValueType();
8639
8640 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8641 visitTargetIntrinsic(I, Intrinsic);
8642 return;
8643 }
8644
8645 // Expand to a umin between the trip count and the maximum elements the type
8646 // can hold.
8647 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8648
8649 // Extend the trip count to at least the result VT.
8650 if (CountVT.bitsLT(VT)) {
8651 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8652 CountVT = VT;
8653 }
8654
8655 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8656 ElementCount::get(VF, IsScalable));
8657
8658 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8659 // Clip to the result type if needed.
8660 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8661
8662 setValue(&I, Trunc);
8663 return;
8664 }
8665 case Intrinsic::vector_partial_reduce_add: {
8666 SDValue Acc = getValue(I.getOperand(0));
8667 SDValue Input = getValue(I.getOperand(1));
8668 setValue(&I,
8669 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8670 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8671 return;
8672 }
8673 case Intrinsic::vector_partial_reduce_fadd: {
8674 SDValue Acc = getValue(I.getOperand(0));
8675 SDValue Input = getValue(I.getOperand(1));
8676 setValue(&I, DAG.getNode(
8677 ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(), Acc,
8678 Input, DAG.getConstantFP(1.0, sdl, Input.getValueType())));
8679 return;
8680 }
8681 case Intrinsic::experimental_cttz_elts: {
8682 SDValue Op = getValue(I.getOperand(0));
8683 EVT OpVT = Op.getValueType();
8684 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8685 bool ZeroIsPoison =
8686 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8687 if (OpVT.getVectorElementType() != MVT::i1) {
8688 // Compare the input vector elements to zero & use to count trailing
8689 // zeros.
8690 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8691 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8692 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8693 }
8694 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8696 sdl, RetTy, Op));
8697 return;
8698 }
8699 case Intrinsic::vector_insert: {
8700 SDValue Vec = getValue(I.getOperand(0));
8701 SDValue SubVec = getValue(I.getOperand(1));
8702 SDValue Index = getValue(I.getOperand(2));
8703
8704 // The intrinsic's index type is i64, but the SDNode requires an index type
8705 // suitable for the target. Convert the index as required.
8706 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8707 if (Index.getValueType() != VectorIdxTy)
8708 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8709
8710 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8711 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8712 Index));
8713 return;
8714 }
8715 case Intrinsic::vector_extract: {
8716 SDValue Vec = getValue(I.getOperand(0));
8717 SDValue Index = getValue(I.getOperand(1));
8718 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8719
8720 // The intrinsic's index type is i64, but the SDNode requires an index type
8721 // suitable for the target. Convert the index as required.
8722 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8723 if (Index.getValueType() != VectorIdxTy)
8724 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8725
8726 setValue(&I,
8727 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8728 return;
8729 }
8730 case Intrinsic::experimental_vector_match: {
8731 SDValue Op1 = getValue(I.getOperand(0));
8732 SDValue Op2 = getValue(I.getOperand(1));
8733 SDValue Mask = getValue(I.getOperand(2));
8734 EVT ResVT = Mask.getValueType();
8735 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8736 return;
8737 }
8738 case Intrinsic::vector_reverse:
8739 visitVectorReverse(I);
8740 return;
8741 case Intrinsic::vector_splice_left:
8742 case Intrinsic::vector_splice_right:
8743 visitVectorSplice(I);
8744 return;
8745 case Intrinsic::callbr_landingpad:
8746 visitCallBrLandingPad(I);
8747 return;
8748 case Intrinsic::vector_interleave2:
8749 visitVectorInterleave(I, 2);
8750 return;
8751 case Intrinsic::vector_interleave3:
8752 visitVectorInterleave(I, 3);
8753 return;
8754 case Intrinsic::vector_interleave4:
8755 visitVectorInterleave(I, 4);
8756 return;
8757 case Intrinsic::vector_interleave5:
8758 visitVectorInterleave(I, 5);
8759 return;
8760 case Intrinsic::vector_interleave6:
8761 visitVectorInterleave(I, 6);
8762 return;
8763 case Intrinsic::vector_interleave7:
8764 visitVectorInterleave(I, 7);
8765 return;
8766 case Intrinsic::vector_interleave8:
8767 visitVectorInterleave(I, 8);
8768 return;
8769 case Intrinsic::vector_deinterleave2:
8770 visitVectorDeinterleave(I, 2);
8771 return;
8772 case Intrinsic::vector_deinterleave3:
8773 visitVectorDeinterleave(I, 3);
8774 return;
8775 case Intrinsic::vector_deinterleave4:
8776 visitVectorDeinterleave(I, 4);
8777 return;
8778 case Intrinsic::vector_deinterleave5:
8779 visitVectorDeinterleave(I, 5);
8780 return;
8781 case Intrinsic::vector_deinterleave6:
8782 visitVectorDeinterleave(I, 6);
8783 return;
8784 case Intrinsic::vector_deinterleave7:
8785 visitVectorDeinterleave(I, 7);
8786 return;
8787 case Intrinsic::vector_deinterleave8:
8788 visitVectorDeinterleave(I, 8);
8789 return;
8790 case Intrinsic::vector_repeat: {
8791 SDValue Vec = getValue(I.getOperand(0));
8792 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8793 setValue(&I, DAG.getNode(ISD::VECTOR_REPEAT, sdl, ResultVT, Vec));
8794 return;
8795 }
8796 case Intrinsic::experimental_vector_compress:
8797 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8798 getValue(I.getArgOperand(0)).getValueType(),
8799 getValue(I.getArgOperand(0)),
8800 getValue(I.getArgOperand(1)),
8801 getValue(I.getArgOperand(2)), Flags));
8802 return;
8803 case Intrinsic::experimental_convergence_anchor:
8804 case Intrinsic::experimental_convergence_entry:
8805 case Intrinsic::experimental_convergence_loop:
8806 visitConvergenceControl(I, Intrinsic);
8807 return;
8808 case Intrinsic::experimental_vector_histogram_add: {
8809 visitVectorHistogram(I, Intrinsic);
8810 return;
8811 }
8812 case Intrinsic::experimental_vector_extract_last_active: {
8813 visitVectorExtractLastActive(I, Intrinsic);
8814 return;
8815 }
8816 case Intrinsic::loop_dependence_war_mask:
8817 setValue(&I,
8819 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8820 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8821 DAG.getConstant(0, sdl, MVT::i64)));
8822 return;
8823 case Intrinsic::loop_dependence_raw_mask:
8824 setValue(&I,
8826 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8827 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8828 DAG.getConstant(0, sdl, MVT::i64)));
8829 return;
8830 case Intrinsic::masked_udiv:
8831 setValue(&I,
8832 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8833 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8834 getValue(I.getOperand(2))));
8835 return;
8836 case Intrinsic::masked_sdiv:
8837 setValue(&I,
8838 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8839 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8840 getValue(I.getOperand(2))));
8841 return;
8842 case Intrinsic::masked_urem:
8843 setValue(&I,
8844 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8845 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8846 getValue(I.getOperand(2))));
8847 return;
8848 case Intrinsic::masked_srem:
8849 setValue(&I,
8850 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8851 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8852 getValue(I.getOperand(2))));
8853 return;
8854 }
8855}
8856
8857void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8859 assert(Result.getNode()->getNumValues() == 2);
8860 SDValue OutChain = Result.getValue(1);
8861 assert(OutChain.getValueType() == MVT::Other);
8862
8863 // Instead of updating the root immediately, push the produced chain to the
8864 // appropriate list, deferring the update until the root is requested. In this
8865 // case, the nodes from the lists are chained using TokenFactor, indicating
8866 // that the operations are independent.
8867 //
8868 // In particular, the root is updated before any call that might access the
8869 // floating-point environment, except for constrained intrinsics.
8870 switch (EB) {
8873 PendingConstrainedFP.push_back(OutChain);
8874 break;
8876 PendingConstrainedFPStrict.push_back(OutChain);
8877 break;
8878 }
8879}
8880
8881void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8882 const ConstrainedFPIntrinsic &FPI) {
8883 SDLoc sdl = getCurSDLoc();
8884
8885 // We do not need to serialize constrained FP intrinsics against
8886 // each other or against (nonvolatile) loads, so they can be
8887 // chained like loads.
8889 SDValue Chain = getFPOperationRoot(EB);
8891 Opers.push_back(Chain);
8892 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8893 Opers.push_back(getValue(FPI.getArgOperand(I)));
8894
8895 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8896 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8897 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8898
8899 SDNodeFlags Flags;
8901 Flags.setNoFPExcept(true);
8902
8903 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8904 Flags.copyFMF(*FPOp);
8905
8906 unsigned Opcode;
8907 switch (FPI.getIntrinsicID()) {
8908 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8909#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8910 case Intrinsic::INTRINSIC: \
8911 Opcode = ISD::STRICT_##DAGN; \
8912 break;
8913#include "llvm/IR/ConstrainedOps.def"
8914 case Intrinsic::experimental_constrained_fmuladd: {
8915 Opcode = ISD::STRICT_FMA;
8916 // Break fmuladd into fmul and fadd.
8917 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8918 Opers.pop_back();
8919 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8920 pushFPOpOutChain(Mul, EB);
8921 Opcode = ISD::STRICT_FADD;
8922 Opers.clear();
8923 Opers.push_back(Mul.getValue(1));
8924 Opers.push_back(Mul.getValue(0));
8925 Opers.push_back(getValue(FPI.getArgOperand(2)));
8926 }
8927 break;
8928 }
8929 }
8930
8931 // A few strict DAG nodes carry additional operands that are not
8932 // set up by the default code above.
8933 switch (Opcode) {
8934 default: break;
8936 Opers.push_back(
8937 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8938 break;
8939 case ISD::STRICT_FSETCC:
8940 case ISD::STRICT_FSETCCS: {
8941 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8942 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8943 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8944 Condition = getFCmpCodeWithoutNaN(Condition);
8945 Opers.push_back(DAG.getCondCode(Condition));
8946 break;
8947 }
8948 }
8949
8950 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8951 pushFPOpOutChain(Result, EB);
8952
8953 SDValue FPResult = Result.getValue(0);
8954 setValue(&FPI, FPResult);
8955}
8956
8957static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8958 std::optional<unsigned> ResOPC;
8959 switch (VPIntrin.getIntrinsicID()) {
8960 case Intrinsic::vp_cttz_elts: {
8961 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8962 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8963 break;
8964 }
8965#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8966 case Intrinsic::VPID: \
8967 ResOPC = ISD::VPSD; \
8968 break;
8969#include "llvm/IR/VPIntrinsics.def"
8970 }
8971
8972 if (!ResOPC)
8974 "Inconsistency: no SDNode available for this VPIntrinsic!");
8975
8976 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8977 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8978 if (VPIntrin.getFastMathFlags().allowReassoc())
8979 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8980 : ISD::VP_REDUCE_FMUL;
8981 }
8982
8983 return *ResOPC;
8984}
8985
8986void SelectionDAGBuilder::visitVPLoad(
8987 const VPIntrinsic &VPIntrin, EVT VT,
8988 const SmallVectorImpl<SDValue> &OpValues) {
8989 SDLoc DL = getCurSDLoc();
8990 Value *PtrOperand = VPIntrin.getArgOperand(0);
8991 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8992 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8993 const MDNode *Ranges = getRangeMetadata(VPIntrin);
8994 SDValue LD;
8995 // Do not serialize variable-length loads of constant memory with
8996 // anything.
8997 if (!Alignment)
8998 Alignment = DAG.getEVTAlign(VT);
8999 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9000 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9001 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9003 MachineMemOperand::Flags MMOFlags =
9004 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9005 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9006 MachinePointerInfo(PtrOperand), MMOFlags,
9008 MMOMetadata(AAInfo, Ranges));
9009 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9010 MMO, false /*IsExpanding */);
9011 if (AddToChain)
9012 PendingLoads.push_back(LD.getValue(1));
9013 setValue(&VPIntrin, LD);
9014}
9015
9016void SelectionDAGBuilder::visitVPLoadFF(
9017 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
9018 const SmallVectorImpl<SDValue> &OpValues) {
9019 assert(OpValues.size() == 3 && "Unexpected number of operands");
9020 SDLoc DL = getCurSDLoc();
9021 Value *PtrOperand = VPIntrin.getArgOperand(0);
9022 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9023 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9024 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
9025 SDValue LD;
9026 // Do not serialize variable-length loads of constant memory with
9027 // anything.
9028 if (!Alignment)
9029 Alignment = DAG.getEVTAlign(VT);
9030 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9031 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9032 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9033 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9034 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
9036 MMOMetadata(AAInfo, Ranges));
9037 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9038 MMO);
9039 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
9040 if (AddToChain)
9041 PendingLoads.push_back(LD.getValue(2));
9042 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
9043}
9044
9045void SelectionDAGBuilder::visitVPGather(
9046 const VPIntrinsic &VPIntrin, EVT VT,
9047 const SmallVectorImpl<SDValue> &OpValues) {
9048 SDLoc DL = getCurSDLoc();
9049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9050 Value *PtrOperand = VPIntrin.getArgOperand(0);
9051 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9052 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9053 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9054 SDValue LD;
9055 if (!Alignment)
9056 Alignment = DAG.getEVTAlign(VT.getScalarType());
9057 unsigned AS =
9058 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9059 MachineMemOperand::Flags MMOFlags =
9060 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9061 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9062 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9063 *Alignment, MMOMetadata(AAInfo, Ranges));
9064 SDValue Base, Index, Scale;
9065 bool UniformBase =
9066 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9067 VT.getScalarStoreSize());
9068 if (!UniformBase) {
9069 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9070 Index = getValue(PtrOperand);
9071 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9072 }
9073 EVT IdxVT = Index.getValueType();
9074 EVT EltTy = IdxVT.getVectorElementType();
9075 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9076 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9077 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9078 }
9079 LD = DAG.getGatherVP(
9080 DAG.getVTList(VT, MVT::Other), VT, DL,
9081 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
9083 PendingLoads.push_back(LD.getValue(1));
9084 setValue(&VPIntrin, LD);
9085}
9086
9087void SelectionDAGBuilder::visitVPStore(
9088 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9089 SDLoc DL = getCurSDLoc();
9090 Value *PtrOperand = VPIntrin.getArgOperand(1);
9091 EVT VT = OpValues[0].getValueType();
9092 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9093 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9094 SDValue ST;
9095 if (!Alignment)
9096 Alignment = DAG.getEVTAlign(VT);
9097 SDValue Ptr = OpValues[1];
9098 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
9099 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9100 MachineMemOperand::Flags MMOFlags =
9101 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9102 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9103 MachinePointerInfo(PtrOperand), MMOFlags,
9104 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
9105 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
9106 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
9107 /* IsTruncating */ false, /*IsCompressing*/ false);
9108 DAG.setRoot(ST);
9109 setValue(&VPIntrin, ST);
9110}
9111
9112void SelectionDAGBuilder::visitVPScatter(
9113 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9114 SDLoc DL = getCurSDLoc();
9115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9116 Value *PtrOperand = VPIntrin.getArgOperand(1);
9117 EVT VT = OpValues[0].getValueType();
9118 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9119 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9120 SDValue ST;
9121 if (!Alignment)
9122 Alignment = DAG.getEVTAlign(VT.getScalarType());
9123 unsigned AS =
9124 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9125 MachineMemOperand::Flags MMOFlags =
9126 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9127 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9128 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9129 *Alignment, AAInfo);
9130 SDValue Base, Index, Scale;
9131 bool UniformBase =
9132 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9133 VT.getScalarStoreSize());
9134 if (!UniformBase) {
9135 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9136 Index = getValue(PtrOperand);
9137 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9138 }
9139 EVT IdxVT = Index.getValueType();
9140 EVT EltTy = IdxVT.getVectorElementType();
9141 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9142 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9143 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9144 }
9145 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
9146 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9147 OpValues[2], OpValues[3]},
9148 MMO, ISD::SIGNED_SCALED);
9149 DAG.setRoot(ST);
9150 setValue(&VPIntrin, ST);
9151}
9152
9153void SelectionDAGBuilder::visitVPStridedLoad(
9154 const VPIntrinsic &VPIntrin, EVT VT,
9155 const SmallVectorImpl<SDValue> &OpValues) {
9156 SDLoc DL = getCurSDLoc();
9157 Value *PtrOperand = VPIntrin.getArgOperand(0);
9158 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9159 if (!Alignment)
9160 Alignment = DAG.getEVTAlign(VT.getScalarType());
9161 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9162 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9163 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9164 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9165 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9166 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9168 MachineMemOperand::Flags MMOFlags =
9169 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9170 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9171 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9172 *Alignment, MMOMetadata(AAInfo, Ranges));
9173
9174 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
9175 OpValues[2], OpValues[3], MMO,
9176 false /*IsExpanding*/);
9177
9178 if (AddToChain)
9179 PendingLoads.push_back(LD.getValue(1));
9180 setValue(&VPIntrin, LD);
9181}
9182
9183void SelectionDAGBuilder::visitVPStridedStore(
9184 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9185 SDLoc DL = getCurSDLoc();
9186 Value *PtrOperand = VPIntrin.getArgOperand(1);
9187 EVT VT = OpValues[0].getValueType();
9188 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9189 if (!Alignment)
9190 Alignment = DAG.getEVTAlign(VT.getScalarType());
9191 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9192 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9193 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9194 MachineMemOperand::Flags MMOFlags =
9195 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9196 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9197 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9198 *Alignment, AAInfo);
9199
9200 SDValue ST = DAG.getStridedStoreVP(
9201 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9202 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9203 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9204 /*IsCompressing*/ false);
9205
9206 DAG.setRoot(ST);
9207 setValue(&VPIntrin, ST);
9208}
9209
9210void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9211 const VPIntrinsic &VPIntrin) {
9212 SDLoc DL = getCurSDLoc();
9213 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9214
9215 auto IID = VPIntrin.getIntrinsicID();
9216
9217 SmallVector<EVT, 4> ValueVTs;
9218 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9219 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9220 SDVTList VTs = DAG.getVTList(ValueVTs);
9221
9222 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9223
9224 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9225 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9226 "Unexpected target EVL type");
9227
9228 // Request operands.
9229 SmallVector<SDValue, 7> OpValues;
9230 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9231 auto Op = getValue(VPIntrin.getArgOperand(I));
9232 if (I == EVLParamPos)
9233 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9234 OpValues.push_back(Op);
9235 }
9236
9237 switch (Opcode) {
9238 default: {
9239 SDNodeFlags SDFlags;
9240 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9241 SDFlags.copyFMF(*FPMO);
9242 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9243 setValue(&VPIntrin, Result);
9244 break;
9245 }
9246 case ISD::VP_LOAD:
9247 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9248 break;
9249 case ISD::VP_LOAD_FF:
9250 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9251 break;
9252 case ISD::VP_GATHER:
9253 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9254 break;
9255 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9256 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9257 break;
9258 case ISD::VP_STORE:
9259 visitVPStore(VPIntrin, OpValues);
9260 break;
9261 case ISD::VP_SCATTER:
9262 visitVPScatter(VPIntrin, OpValues);
9263 break;
9264 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9265 visitVPStridedStore(VPIntrin, OpValues);
9266 break;
9267 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9268 case ISD::VP_CTTZ_ELTS: {
9269 SDValue Result =
9270 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9271 setValue(&VPIntrin, Result);
9272 break;
9273 }
9274 }
9275}
9276
9278 const BasicBlock *EHPadBB,
9279 MCSymbol *&BeginLabel) {
9280 MachineFunction &MF = DAG.getMachineFunction();
9281
9282 // Skip emitting EH_LABEL on targets whose exception tables don't reference
9283 // them (32-bit x86 SEH, Wasm).
9285 BeginLabel = nullptr;
9286 return Chain;
9287 }
9288
9289 // Insert a label before the invoke call to mark the try range. This can be
9290 // used to detect deletion of the invoke via the MachineModuleInfo.
9291 BeginLabel = MF.getContext().createTempSymbol();
9292
9293 // For SjLj, keep track of which landing pads go with which invokes
9294 // so as to maintain the ordering of pads in the LSDA.
9295 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9296 if (CallSiteIndex) {
9297 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9298 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9299
9300 // Now that the call site is handled, stop tracking it.
9301 FuncInfo.setCurrentCallSite(0);
9302 }
9303
9304 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9305}
9306
9307SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9308 const BasicBlock *EHPadBB,
9309 MCSymbol *BeginLabel) {
9310 // No labels were emitted.
9311 if (!BeginLabel)
9312 return Chain;
9313
9315
9316 // Insert a label at the end of the invoke call to mark the try range. This
9317 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9318 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9319 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9320
9321 // Inform MachineModuleInfo of range.
9323 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9324 // actually use outlined funclets and their LSDA info style.
9325 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9326 assert(II && "II should've been set");
9327 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9328 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9329 } else if (!isScopedEHPersonality(Pers)) {
9330 assert(EHPadBB);
9331 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9332 }
9333
9334 return Chain;
9335}
9336
9337std::pair<SDValue, SDValue>
9339 const BasicBlock *EHPadBB) {
9340 MCSymbol *BeginLabel = nullptr;
9341
9342 if (EHPadBB) {
9343 // Both PendingLoads and PendingExports must be flushed here;
9344 // this call might not return.
9345 (void)getRoot();
9346 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9347 CLI.setChain(getRoot());
9348 }
9349
9350 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9351 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9352
9353 assert((CLI.IsTailCall || Result.second.getNode()) &&
9354 "Non-null chain expected with non-tail call!");
9355 assert((Result.second.getNode() || !Result.first.getNode()) &&
9356 "Null value expected with tail call!");
9357
9358 if (!Result.second.getNode()) {
9359 // As a special case, a null chain means that a tail call has been emitted
9360 // and the DAG root is already updated.
9361 HasTailCall = true;
9362
9363 // Since there's no actual continuation from this block, nothing can be
9364 // relying on us setting vregs for them.
9365 PendingExports.clear();
9366 } else {
9367 DAG.setRoot(Result.second);
9368 }
9369
9370 if (EHPadBB) {
9371 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9372 BeginLabel));
9373 Result.second = getRoot();
9374 }
9375
9376 return Result;
9377}
9378
9380 bool isMustTailCall = CB.isMustTailCall();
9381
9382 // Avoid emitting tail calls in functions with the disable-tail-calls
9383 // attribute.
9384 const Function *Caller = CB.getParent()->getParent();
9385 if (!isMustTailCall &&
9386 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9387 return false;
9388
9389 // We can't tail call inside a function with a swifterror argument. Lowering
9390 // does not support this yet. It would have to move into the swifterror
9391 // register before the call.
9392 if (DAG.hasSwiftErrorArg())
9393 return false;
9394
9395 // Check if target-independent constraints permit a tail call here.
9396 // Target-dependent constraints are checked within TLI->LowerCallTo.
9397 return isInTailCallPosition(CB, DAG.getTarget());
9398}
9399
9401 bool isTailCall, bool isMustTailCall,
9402 const BasicBlock *EHPadBB,
9403 const TargetLowering::PtrAuthInfo *PAI) {
9404 auto &DL = DAG.getDataLayout();
9405 FunctionType *FTy = CB.getFunctionType();
9406 Type *RetTy = CB.getType();
9407
9409 Args.reserve(CB.arg_size());
9410
9411 const Value *SwiftErrorVal = nullptr;
9412 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9413
9414 if (isTailCall)
9415 isTailCall = canTailCall(CB);
9416
9417 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9418 const Value *V = *I;
9419
9420 // Skip empty types
9421 if (V->getType()->isEmptyTy())
9422 continue;
9423
9424 SDValue ArgNode = getValue(V);
9425 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9426 Entry.setAttributes(&CB, I - CB.arg_begin());
9427
9428 // Use swifterror virtual register as input to the call.
9429 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9430 SwiftErrorVal = V;
9431 // We find the virtual register for the actual swifterror argument.
9432 // Instead of using the Value, we use the virtual register instead.
9433 Entry.Node =
9434 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9435 EVT(TLI.getPointerTy(DL)));
9436 }
9437
9438 Args.push_back(Entry);
9439
9440 // If we have an explicit sret argument that is an Instruction, (i.e., it
9441 // might point to function-local memory), we can't meaningfully tail-call.
9442 if (Entry.IsSRet && isa<Instruction>(V))
9443 isTailCall = false;
9444 }
9445
9446 // If call site has a cfguardtarget operand bundle, create and add an
9447 // additional ArgListEntry.
9448 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9449 Value *V = Bundle->Inputs[0];
9451 Entry.IsCFGuardTarget = true;
9452 Args.push_back(Entry);
9453 }
9454
9455 // Disable tail calls if there is an swifterror argument. Targets have not
9456 // been updated to support tail calls.
9457 if (TLI.supportSwiftError() && SwiftErrorVal)
9458 isTailCall = false;
9459
9460 ConstantInt *CFIType = nullptr;
9461 if (CB.isIndirectCall()) {
9462 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9463 if (!TLI.supportKCFIBundles())
9465 "Target doesn't support calls with kcfi operand bundles.");
9466 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9467 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9468 }
9469 }
9470
9471 SDValue ConvControlToken;
9472 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9473 auto *Token = Bundle->Inputs[0].get();
9474 ConvControlToken = getValue(Token);
9475 }
9476
9477 GlobalValue *DeactivationSymbol = nullptr;
9479 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9480 }
9481
9484 .setChain(getRoot())
9485 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9486 .setTailCall(isTailCall)
9490 .setCFIType(CFIType)
9491 .setConvergenceControlToken(ConvControlToken)
9492 .setDeactivationSymbol(DeactivationSymbol);
9493
9494 // Set the pointer authentication info if we have it.
9495 if (PAI) {
9496 if (!TLI.supportPtrAuthBundles())
9498 "This target doesn't support calls with ptrauth operand bundles.");
9499 CLI.setPtrAuth(*PAI);
9500 }
9501
9502 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9503
9504 if (Result.first.getNode()) {
9505 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9506 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, CB, Result.first);
9507 setValue(&CB, Result.first);
9508 }
9509
9510 // The last element of CLI.InVals has the SDValue for swifterror return.
9511 // Here we copy it to a virtual register and update SwiftErrorMap for
9512 // book-keeping.
9513 if (SwiftErrorVal && TLI.supportSwiftError()) {
9514 // Get the last element of InVals.
9515 SDValue Src = CLI.InVals.back();
9516 Register VReg =
9517 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9518 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9519 DAG.setRoot(CopyNode);
9520 }
9521}
9522
9523static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9524 SelectionDAGBuilder &Builder) {
9525 // Check to see if this load can be trivially constant folded, e.g. if the
9526 // input is from a string literal.
9527 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9528 // Cast pointer to the type we really want to load.
9529 Type *LoadTy =
9530 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9531 if (LoadVT.isVector())
9532 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9533 if (const Constant *LoadCst =
9534 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9535 LoadTy, Builder.DAG.getDataLayout()))
9536 return Builder.getValue(LoadCst);
9537 }
9538
9539 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9540 // still constant memory, the input chain can be the entry node.
9541 SDValue Root;
9542 bool ConstantMemory = false;
9543
9544 // Do not serialize (non-volatile) loads of constant memory with anything.
9545 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9546 Root = Builder.DAG.getEntryNode();
9547 ConstantMemory = true;
9548 } else {
9549 // Do not serialize non-volatile loads against each other.
9550 Root = Builder.DAG.getRoot();
9551 }
9552
9553 SDValue Ptr = Builder.getValue(PtrVal);
9554 SDValue LoadVal =
9555 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9556 MachinePointerInfo(PtrVal), Align(1));
9557
9558 if (!ConstantMemory)
9559 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9560 return LoadVal;
9561}
9562
9563/// Record the value for an instruction that produces an integer result,
9564/// converting the type where necessary.
9565void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9566 SDValue Value,
9567 bool IsSigned) {
9568 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9569 I.getType(), true);
9570 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9571 setValue(&I, Value);
9572}
9573
9574/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9575/// true and lower it. Otherwise return false, and it will be lowered like a
9576/// normal call.
9577/// The caller already checked that \p I calls the appropriate LibFunc with a
9578/// correct prototype.
9579bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9580 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9581 const Value *Size = I.getArgOperand(2);
9582 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9583 if (CSize && CSize->getZExtValue() == 0) {
9584 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9585 I.getType(), true);
9586 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9587 return true;
9588 }
9589
9590 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9591 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9592 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9593 getValue(Size), &I);
9594 if (Res.first.getNode()) {
9595 processIntegerCallValue(I, Res.first, true);
9596 PendingLoads.push_back(Res.second);
9597 return true;
9598 }
9599
9600 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9601 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9602 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9603 return false;
9604
9605 // If the target has a fast compare for the given size, it will return a
9606 // preferred load type for that size. Require that the load VT is legal and
9607 // that the target supports unaligned loads of that type. Otherwise, return
9608 // INVALID.
9609 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9610 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9611 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9612 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9613 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9614 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9615 // TODO: Check alignment of src and dest ptrs.
9616 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9617 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9618 if (!TLI.isTypeLegal(LVT) ||
9619 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9620 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9622 }
9623
9624 return LVT;
9625 };
9626
9627 // This turns into unaligned loads. We only do this if the target natively
9628 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9629 // we'll only produce a small number of byte loads.
9630 MVT LoadVT;
9631 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9632 switch (NumBitsToCompare) {
9633 default:
9634 return false;
9635 case 16:
9636 LoadVT = MVT::i16;
9637 break;
9638 case 32:
9639 LoadVT = MVT::i32;
9640 break;
9641 case 64:
9642 case 128:
9643 case 256:
9644 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9645 break;
9646 }
9647
9648 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9649 return false;
9650
9651 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9652 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9653
9654 // Bitcast to a wide integer type if the loads are vectors.
9655 if (LoadVT.isVector()) {
9656 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9657 LoadL = DAG.getBitcast(CmpVT, LoadL);
9658 LoadR = DAG.getBitcast(CmpVT, LoadR);
9659 }
9660
9661 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9662 processIntegerCallValue(I, Cmp, false);
9663 return true;
9664}
9665
9666/// See if we can lower a memchr call into an optimized form. If so, return
9667/// true and lower it. Otherwise return false, and it will be lowered like a
9668/// normal call.
9669/// The caller already checked that \p I calls the appropriate LibFunc with a
9670/// correct prototype.
9671bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9672 const Value *Src = I.getArgOperand(0);
9673 const Value *Char = I.getArgOperand(1);
9674 const Value *Length = I.getArgOperand(2);
9675
9676 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9677 std::pair<SDValue, SDValue> Res =
9678 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9679 getValue(Src), getValue(Char), getValue(Length),
9680 MachinePointerInfo(Src));
9681 if (Res.first.getNode()) {
9682 setValue(&I, Res.first);
9683 PendingLoads.push_back(Res.second);
9684 return true;
9685 }
9686
9687 return false;
9688}
9689
9690/// See if we can lower a memccpy call into an optimized form. If so, return
9691/// true and lower it, otherwise return false and it will be lowered like a
9692/// normal call.
9693/// The caller already checked that \p I calls the appropriate LibFunc with a
9694/// correct prototype.
9695bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9696 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9697 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9698 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9699 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9700 getValue(I.getArgOperand(3)), &I);
9701
9702 if (Res.first) {
9703 processIntegerCallValue(I, Res.first, true);
9704 PendingLoads.push_back(Res.second);
9705 return true;
9706 }
9707 return false;
9708}
9709
9710/// See if we can lower a mempcpy call into an optimized form. If so, return
9711/// true and lower it. Otherwise return false, and it will be lowered like a
9712/// normal call.
9713/// The caller already checked that \p I calls the appropriate LibFunc with a
9714/// correct prototype.
9715bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9716 SDValue Dst = getValue(I.getArgOperand(0));
9717 SDValue Src = getValue(I.getArgOperand(1));
9718 SDValue Size = getValue(I.getArgOperand(2));
9719
9720 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9721 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9722
9723 SDLoc sdl = getCurSDLoc();
9724
9725 // In the mempcpy context we need to pass in a false value for isTailCall
9726 // because the return pointer needs to be adjusted by the size of
9727 // the copied memory.
9728 SDValue Root = getMemoryRoot();
9729 SDValue MC = DAG.getMemcpy(
9730 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9731 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9732 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9733 assert(MC.getNode() != nullptr &&
9734 "** memcpy should not be lowered as TailCall in mempcpy context **");
9735 DAG.setRoot(MC);
9736
9737 // Check if Size needs to be truncated or extended.
9738 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9739
9740 // Adjust return pointer to point just past the last dst byte.
9741 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9742 setValue(&I, DstPlusSize);
9743 return true;
9744}
9745
9746/// See if we can lower a strcpy call into an optimized form. If so, return
9747/// true and lower it, otherwise return false and it will be lowered like a
9748/// normal call.
9749/// The caller already checked that \p I calls the appropriate LibFunc with a
9750/// correct prototype.
9751bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9752 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9753
9754 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9755 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9756 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9757 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9758 if (Res.first.getNode()) {
9759 setValue(&I, Res.first);
9760 DAG.setRoot(Res.second);
9761 return true;
9762 }
9763
9764 return false;
9765}
9766
9767/// See if we can lower a strcmp call into an optimized form. If so, return
9768/// true and lower it, otherwise return false and it will be lowered like a
9769/// normal call.
9770/// The caller already checked that \p I calls the appropriate LibFunc with a
9771/// correct prototype.
9772bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9773 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9774
9775 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9776 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9777 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9778 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9779 if (Res.first.getNode()) {
9780 processIntegerCallValue(I, Res.first, true);
9781 PendingLoads.push_back(Res.second);
9782 return true;
9783 }
9784
9785 return false;
9786}
9787
9788/// See if we can lower a strlen call into an optimized form. If so, return
9789/// true and lower it, otherwise return false and it will be lowered like a
9790/// normal call.
9791/// The caller already checked that \p I calls the appropriate LibFunc with a
9792/// correct prototype.
9793bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9794 const Value *Arg0 = I.getArgOperand(0);
9795
9796 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9797 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9798 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9799 if (Res.first.getNode()) {
9800 processIntegerCallValue(I, Res.first, false);
9801 PendingLoads.push_back(Res.second);
9802 return true;
9803 }
9804
9805 return false;
9806}
9807
9808/// See if we can lower a strnlen 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::visitStrNLenCall(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 =
9818 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9819 getValue(Arg0), getValue(Arg1),
9820 MachinePointerInfo(Arg0));
9821 if (Res.first.getNode()) {
9822 processIntegerCallValue(I, Res.first, false);
9823 PendingLoads.push_back(Res.second);
9824 return true;
9825 }
9826
9827 return false;
9828}
9829
9830/// See if we can lower a Strstr call into an optimized form. If so, return
9831/// true and lower it, otherwise return false and it will be lowered like a
9832/// normal call.
9833/// The caller already checked that \p I calls the appropriate LibFunc with a
9834/// correct prototype.
9835bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9836 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9837 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9838 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9839 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9840 if (Res.first) {
9841 processIntegerCallValue(I, Res.first, false);
9842 PendingLoads.push_back(Res.second);
9843 return true;
9844 }
9845 return false;
9846}
9847
9848/// See if we can lower a unary floating-point operation into an SDNode with
9849/// the specified Opcode. If so, return true and lower it, otherwise return
9850/// false and it will be lowered like a normal call.
9851/// The caller already checked that \p I calls the appropriate LibFunc with a
9852/// correct prototype.
9853bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9854 unsigned Opcode) {
9855 // We already checked this call's prototype; verify it doesn't modify errno.
9856 // Do not perform optimizations for call sites that require strict
9857 // floating-point semantics.
9858 if (!I.onlyReadsMemory() || I.isStrictFP())
9859 return false;
9860
9861 SDNodeFlags Flags;
9862 Flags.copyFMF(cast<FPMathOperator>(I));
9863
9864 SDValue Tmp = getValue(I.getArgOperand(0));
9865 setValue(&I,
9866 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9867 return true;
9868}
9869
9870/// See if we can lower a binary floating-point operation into an SDNode with
9871/// the specified Opcode. If so, return true and lower it. Otherwise return
9872/// false, and it will be lowered like a normal call.
9873/// The caller already checked that \p I calls the appropriate LibFunc with a
9874/// correct prototype.
9875bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9876 unsigned Opcode) {
9877 // We already checked this call's prototype; verify it doesn't modify errno.
9878 // Do not perform optimizations for call sites that require strict
9879 // floating-point semantics.
9880 if (!I.onlyReadsMemory() || I.isStrictFP())
9881 return false;
9882
9883 SDNodeFlags Flags;
9884 Flags.copyFMF(cast<FPMathOperator>(I));
9885
9886 SDValue Tmp0 = getValue(I.getArgOperand(0));
9887 SDValue Tmp1 = getValue(I.getArgOperand(1));
9888 EVT VT = Tmp0.getValueType();
9889 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9890 return true;
9891}
9892
9893void SelectionDAGBuilder::visitCall(const CallInst &I) {
9894 // Handle inline assembly differently.
9895 if (I.isInlineAsm()) {
9896 visitInlineAsm(I);
9897 return;
9898 }
9899
9901
9902 if (Function *F = I.getCalledFunction()) {
9903 if (F->isDeclaration()) {
9904 // Is this an LLVM intrinsic?
9905 if (unsigned IID = F->getIntrinsicID()) {
9906 visitIntrinsicCall(I, IID);
9907 return;
9908 }
9909 }
9910
9911 // Check for well-known libc/libm calls. If the function is internal, it
9912 // can't be a library call. Don't do the check if marked as nobuiltin for
9913 // some reason.
9914 // This code should not handle libcalls that are already canonicalized to
9915 // intrinsics by the middle-end.
9916 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9917 ? LibInfo->getLibFunc(*F)
9918 : NotLibFunc;
9919 if (LibInfo->hasOptimizedCodeGen(Func)) {
9920 switch (Func) {
9921 default: break;
9922 case LibFunc_bcmp:
9923 if (visitMemCmpBCmpCall(I))
9924 return;
9925 break;
9926 case LibFunc_copysign:
9927 case LibFunc_copysignf:
9928 case LibFunc_copysignl:
9929 // We already checked this call's prototype; verify it doesn't modify
9930 // errno.
9931 if (I.onlyReadsMemory()) {
9932 SDValue LHS = getValue(I.getArgOperand(0));
9933 SDValue RHS = getValue(I.getArgOperand(1));
9935 LHS.getValueType(), LHS, RHS));
9936 return;
9937 }
9938 break;
9939 case LibFunc_sin:
9940 case LibFunc_sinf:
9941 case LibFunc_sinl:
9942 if (visitUnaryFloatCall(I, ISD::FSIN))
9943 return;
9944 break;
9945 case LibFunc_cos:
9946 case LibFunc_cosf:
9947 case LibFunc_cosl:
9948 if (visitUnaryFloatCall(I, ISD::FCOS))
9949 return;
9950 break;
9951 case LibFunc_tan:
9952 case LibFunc_tanf:
9953 case LibFunc_tanl:
9954 if (visitUnaryFloatCall(I, ISD::FTAN))
9955 return;
9956 break;
9957 case LibFunc_asin:
9958 case LibFunc_asinf:
9959 case LibFunc_asinl:
9960 if (visitUnaryFloatCall(I, ISD::FASIN))
9961 return;
9962 break;
9963 case LibFunc_acos:
9964 case LibFunc_acosf:
9965 case LibFunc_acosl:
9966 if (visitUnaryFloatCall(I, ISD::FACOS))
9967 return;
9968 break;
9969 case LibFunc_atan:
9970 case LibFunc_atanf:
9971 case LibFunc_atanl:
9972 if (visitUnaryFloatCall(I, ISD::FATAN))
9973 return;
9974 break;
9975 case LibFunc_atan2:
9976 case LibFunc_atan2f:
9977 case LibFunc_atan2l:
9978 if (visitBinaryFloatCall(I, ISD::FATAN2))
9979 return;
9980 break;
9981 case LibFunc_sinh:
9982 case LibFunc_sinhf:
9983 case LibFunc_sinhl:
9984 if (visitUnaryFloatCall(I, ISD::FSINH))
9985 return;
9986 break;
9987 case LibFunc_cosh:
9988 case LibFunc_coshf:
9989 case LibFunc_coshl:
9990 if (visitUnaryFloatCall(I, ISD::FCOSH))
9991 return;
9992 break;
9993 case LibFunc_tanh:
9994 case LibFunc_tanhf:
9995 case LibFunc_tanhl:
9996 if (visitUnaryFloatCall(I, ISD::FTANH))
9997 return;
9998 break;
9999 case LibFunc_sqrt:
10000 case LibFunc_sqrtf:
10001 case LibFunc_sqrtl:
10002 case LibFunc_sqrt_finite:
10003 case LibFunc_sqrtf_finite:
10004 case LibFunc_sqrtl_finite:
10005 if (visitUnaryFloatCall(I, ISD::FSQRT))
10006 return;
10007 break;
10008 case LibFunc_log2:
10009 case LibFunc_log2f:
10010 case LibFunc_log2l:
10011 if (visitUnaryFloatCall(I, ISD::FLOG2))
10012 return;
10013 break;
10014 case LibFunc_exp2:
10015 case LibFunc_exp2f:
10016 case LibFunc_exp2l:
10017 if (visitUnaryFloatCall(I, ISD::FEXP2))
10018 return;
10019 break;
10020 case LibFunc_exp10:
10021 case LibFunc_exp10f:
10022 case LibFunc_exp10l:
10023 if (visitUnaryFloatCall(I, ISD::FEXP10))
10024 return;
10025 break;
10026 case LibFunc_ldexp:
10027 case LibFunc_ldexpf:
10028 case LibFunc_ldexpl:
10029 if (visitBinaryFloatCall(I, ISD::FLDEXP))
10030 return;
10031 break;
10032 case LibFunc_strstr:
10033 if (visitStrstrCall(I))
10034 return;
10035 break;
10036 case LibFunc_memcmp:
10037 if (visitMemCmpBCmpCall(I))
10038 return;
10039 break;
10040 case LibFunc_memccpy:
10041 if (visitMemCCpyCall(I))
10042 return;
10043 break;
10044 case LibFunc_mempcpy:
10045 if (visitMemPCpyCall(I))
10046 return;
10047 break;
10048 case LibFunc_memchr:
10049 if (visitMemChrCall(I))
10050 return;
10051 break;
10052 case LibFunc_strcpy:
10053 if (visitStrCpyCall(I, false))
10054 return;
10055 break;
10056 case LibFunc_stpcpy:
10057 if (visitStrCpyCall(I, true))
10058 return;
10059 break;
10060 case LibFunc_strcmp:
10061 if (visitStrCmpCall(I))
10062 return;
10063 break;
10064 case LibFunc_strlen:
10065 if (visitStrLenCall(I))
10066 return;
10067 break;
10068 case LibFunc_strnlen:
10069 if (visitStrNLenCall(I))
10070 return;
10071 break;
10072 }
10073 }
10074 }
10075
10076 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
10077 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
10078 return;
10079 }
10080
10081 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
10082 // have to do anything here to lower funclet bundles.
10083 // CFGuardTarget bundles are lowered in LowerCallTo.
10085 I, "calls",
10090
10091 SDValue Callee = getValue(I.getCalledOperand());
10092
10093 if (I.hasDeoptState())
10094 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
10095 else
10096 // Check if we can potentially perform a tail call. More detailed checking
10097 // is be done within LowerCallTo, after more information about the call is
10098 // known.
10099 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
10100}
10101
10103 const CallBase &CB, const BasicBlock *EHPadBB) {
10104 auto PAB = CB.getOperandBundle("ptrauth");
10105 const Value *CalleeV = CB.getCalledOperand();
10106
10107 // Gather the call ptrauth data from the operand bundle:
10108 // [ i32 <key>, i64 <discriminator> ]
10109 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
10110 const Value *Discriminator = PAB->Inputs[1];
10111
10112 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
10113 assert(Discriminator->getType()->isIntegerTy(64) &&
10114 "Invalid ptrauth discriminator");
10115
10116 // Look through ptrauth constants to find the raw callee.
10117 // Do a direct unauthenticated call if we found it and everything matches.
10118 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
10119 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
10120 DAG.getDataLayout()))
10121 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
10122 CB.isMustTailCall(), EHPadBB);
10123
10124 // Functions should never be ptrauth-called directly.
10125 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
10126
10127 // Otherwise, do an authenticated indirect call.
10128 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
10129 getValue(Discriminator)};
10130
10131 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
10132 EHPadBB, &PAI);
10133}
10134
10135namespace {
10136
10137/// AsmOperandInfo - This contains information for each constraint that we are
10138/// lowering.
10139class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
10140public:
10141 /// CallOperand - If this is the result output operand or a clobber
10142 /// this is null, otherwise it is the incoming operand to the CallInst.
10143 /// This gets modified as the asm is processed.
10144 SDValue CallOperand;
10145
10146 /// AssignedRegs - If this is a register or register class operand, this
10147 /// contains the set of register corresponding to the operand.
10148 RegsForValue AssignedRegs;
10149
10150 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
10151 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
10152 }
10153
10154 /// Whether or not this operand accesses memory
10155 bool hasMemory(const TargetLowering &TLI) const {
10156 // Indirect operand accesses access memory.
10157 if (isIndirect)
10158 return true;
10159
10160 for (const auto &Code : Codes)
10162 return true;
10163
10164 return false;
10165 }
10166};
10167
10168
10169} // end anonymous namespace
10170
10171/// Make sure that the output operand \p OpInfo and its corresponding input
10172/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10173/// out).
10174static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10175 SDISelAsmOperandInfo &MatchingOpInfo,
10176 SelectionDAG &DAG) {
10177 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10178 return;
10179
10181 const auto &TLI = DAG.getTargetLoweringInfo();
10182
10183 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10184 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
10185 OpInfo.ConstraintVT);
10186 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10187 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
10188 MatchingOpInfo.ConstraintVT);
10189 const bool OutOpIsIntOrFP =
10190 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10191 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10192 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10193 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10194 // FIXME: error out in a more elegant fashion
10195 report_fatal_error("Unsupported asm: input constraint"
10196 " with a matching output constraint of"
10197 " incompatible type!");
10198 }
10199 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10200}
10201
10202/// Get a direct memory input to behave well as an indirect operand.
10203/// This may introduce stores, hence the need for a \p Chain.
10204/// \return The (possibly updated) chain.
10205static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10206 SDISelAsmOperandInfo &OpInfo,
10207 SelectionDAG &DAG) {
10208 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10209
10210 // If we don't have an indirect input, put it in the constpool if we can,
10211 // otherwise spill it to a stack slot.
10212 // TODO: This isn't quite right. We need to handle these according to
10213 // the addressing mode that the constraint wants. Also, this may take
10214 // an additional register for the computation and we don't want that
10215 // either.
10216
10217 // If the operand is a float, integer, or vector constant, spill to a
10218 // constant pool entry to get its address.
10219 const Value *OpVal = OpInfo.CallOperandVal;
10220 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10222 OpInfo.CallOperand = DAG.getConstantPool(
10223 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10224 return Chain;
10225 }
10226
10227 // Otherwise, create a stack slot and emit a store to it before the asm.
10228 Type *Ty = OpVal->getType();
10229 auto &DL = DAG.getDataLayout();
10230 TypeSize TySize = DL.getTypeAllocSize(Ty);
10233 int StackID = 0;
10234 if (TySize.isScalable())
10235 StackID = TFI->getStackIDForScalableVectors();
10236 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10237 DL.getPrefTypeAlign(Ty), false,
10238 nullptr, StackID);
10239 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10240 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10242 TLI.getMemValueType(DL, Ty));
10243 OpInfo.CallOperand = StackSlot;
10244
10245 return Chain;
10246}
10247
10248/// GetRegistersForValue - Assign registers (virtual or physical) for the
10249/// specified operand. We prefer to assign virtual registers, to allow the
10250/// register allocator to handle the assignment process. However, if the asm
10251/// uses features that we can't model on machineinstrs, we have SDISel do the
10252/// allocation. This produces generally horrible, but correct, code.
10253///
10254/// OpInfo describes the operand
10255/// RefOpInfo describes the matching operand if any, the operand otherwise
10256static std::optional<unsigned>
10258 SDISelAsmOperandInfo &OpInfo,
10259 SDISelAsmOperandInfo &RefOpInfo) {
10260 LLVMContext &Context = *DAG.getContext();
10261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10262
10266
10267 // No work to do for memory/address operands.
10268 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10269 OpInfo.ConstraintType == TargetLowering::C_Address)
10270 return std::nullopt;
10271
10272 // If this is a constraint for a single physreg, or a constraint for a
10273 // register class, find it.
10274 unsigned AssignedReg;
10275 const TargetRegisterClass *RC;
10276 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10277 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10278 // RC is unset only on failure. Return immediately.
10279 if (!RC)
10280 return std::nullopt;
10281
10282 // Get the actual register value type. This is important, because the user
10283 // may have asked for (e.g.) the AX register in i32 type. We need to
10284 // remember that AX is actually i16 to get the right extension.
10285 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10286
10287 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10288 // If this is an FP operand in an integer register (or visa versa), or more
10289 // generally if the operand value disagrees with the register class we plan
10290 // to stick it in, fix the operand type.
10291 //
10292 // If this is an input value, the bitcast to the new type is done now.
10293 // Bitcast for output value is done at the end of visitInlineAsm().
10294 if ((OpInfo.Type == InlineAsm::isOutput ||
10295 OpInfo.Type == InlineAsm::isInput) &&
10296 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10297 // Try to convert to the first EVT that the reg class contains. If the
10298 // types are identical size, use a bitcast to convert (e.g. two differing
10299 // vector types). Note: output bitcast is done at the end of
10300 // visitInlineAsm().
10301 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10302 // Exclude indirect inputs while they are unsupported because the code
10303 // to perform the load is missing and thus OpInfo.CallOperand still
10304 // refers to the input address rather than the pointed-to value.
10305 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10306 OpInfo.CallOperand =
10307 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10308 OpInfo.ConstraintVT = RegVT;
10309 // If the operand is an FP value and we want it in integer registers,
10310 // use the corresponding integer type. This turns an f64 value into
10311 // i64, which can be passed with two i32 values on a 32-bit machine.
10312 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10313 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10314 if (OpInfo.Type == InlineAsm::isInput)
10315 OpInfo.CallOperand =
10316 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10317 OpInfo.ConstraintVT = VT;
10318 }
10319 }
10320 }
10321
10322 // No need to allocate a matching input constraint since the constraint it's
10323 // matching to has already been allocated.
10324 if (OpInfo.isMatchingInputConstraint())
10325 return std::nullopt;
10326
10327 EVT ValueVT = OpInfo.ConstraintVT;
10328 if (OpInfo.ConstraintVT == MVT::Other)
10329 ValueVT = RegVT;
10330
10331 // Initialize NumRegs.
10332 unsigned NumRegs = 1;
10333 if (OpInfo.ConstraintVT != MVT::Other)
10334 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10335
10336 // If this is a constraint for a specific physical register, like {r17},
10337 // assign it now.
10338
10339 // If this associated to a specific register, initialize iterator to correct
10340 // place. If virtual, make sure we have enough registers
10341
10342 // Initialize iterator if necessary
10345
10346 // Do not check for single registers.
10347 if (AssignedReg) {
10348 I = std::find(I, RC->end(), AssignedReg);
10349 if (I == RC->end()) {
10350 // RC does not contain the selected register, which indicates a
10351 // mismatch between the register and the required type/bitwidth.
10352 return {AssignedReg};
10353 }
10354 }
10355
10356 for (; NumRegs; --NumRegs, ++I) {
10357 assert(I != RC->end() && "Ran out of registers to allocate!");
10358 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10359 Regs.push_back(R);
10360 }
10361
10362 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10363 return std::nullopt;
10364}
10365
10366static unsigned
10368 const std::vector<SDValue> &AsmNodeOperands) {
10369 // Scan until we find the definition we already emitted of this operand.
10370 unsigned CurOp = InlineAsm::Op_FirstOperand;
10371 for (; OperandNo; --OperandNo) {
10372 // Advance to the next operand.
10373 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10374 const InlineAsm::Flag F(OpFlag);
10375 assert(
10376 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10377 "Skipped past definitions?");
10378 CurOp += F.getNumOperandRegisters() + 1;
10379 }
10380 return CurOp;
10381}
10382
10383namespace {
10384
10385class ExtraFlags {
10386 unsigned Flags = 0;
10387
10388public:
10389 explicit ExtraFlags(const CallBase &Call) {
10390 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10391 if (IA->hasSideEffects())
10393 if (IA->isAlignStack())
10395 if (IA->canThrow())
10397 if (Call.isConvergent())
10399 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10400 }
10401
10402 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10403 // Ideally, we would only check against memory constraints. However, the
10404 // meaning of an Other constraint can be target-specific and we can't easily
10405 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10406 // for Other constraints as well.
10409 if (OpInfo.Type == InlineAsm::isInput)
10411 else if (OpInfo.Type == InlineAsm::isOutput)
10413 else if (OpInfo.Type == InlineAsm::isClobber)
10415 }
10416 }
10417
10418 unsigned get() const { return Flags; }
10419};
10420
10421} // end anonymous namespace
10422
10423static bool isFunction(SDValue Op) {
10424 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10425 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10426 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10427
10428 // In normal "call dllimport func" instruction (non-inlineasm) it force
10429 // indirect access by specifing call opcode. And usually specially print
10430 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10431 // not do in this way now. (In fact, this is similar with "Data Access"
10432 // action). So here we ignore dllimport function.
10433 if (Fn && !Fn->hasDLLImportStorageClass())
10434 return true;
10435 }
10436 }
10437 return false;
10438}
10439
10440namespace {
10441
10442struct ConstraintDecisionInfo {
10443 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10444 std::vector<SDValue> AsmNodeOperands;
10445 SDValue Glue, Chain;
10446 bool HasSideEffect = false;
10447 MCSymbol *BeginLabel = nullptr;
10448
10449 SmallVector<char> Buffer;
10450 raw_svector_ostream ErrorMsg;
10451
10452 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10453};
10454
10455} // end anonymous namespace
10456
10457/// Construct operand info objects.
10458static bool
10459constructOperandInfo(ConstraintDecisionInfo &Info,
10460 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10461 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10462 ExtraFlags &ExtraInfo) {
10463 for (auto &T : TargetConstraints) {
10464 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10465 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10466
10467 if (OpInfo.CallOperandVal)
10468 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10469
10470 if (!Info.HasSideEffect)
10471 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10472
10473 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10474 // FIXME: Could we compute this on OpInfo rather than T?
10475
10476 // Compute the constraint code and ConstraintType to use.
10478
10479 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10480 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10481 // We've delayed emitting a diagnostic like the "n" constraint because
10482 // inlining could cause an integer showing up.
10483 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10484 << "' expects an integer constant expression";
10485 return true;
10486 }
10487
10488 ExtraInfo.update(T);
10489 }
10490
10491 return false;
10492}
10493
10494/// Compute which constraint option to use for each operand.
10495static void
10496computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10497 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10498 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10499 const TargetMachine &TM, SelectionDAG &DAG) {
10500 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10502 IA->collectAsmStrs(AsmStrs);
10503
10504 int OpNo = -1;
10505 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10506 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10507 OpNo++;
10508
10509 // If this is an output operand with a matching input operand, look up the
10510 // matching input. If their types mismatch, e.g. one is an integer, the
10511 // other is floating point, or their sizes are different, flag it as an
10512 // error.
10513 if (OpInfo.hasMatchingInput()) {
10514 SDISelAsmOperandInfo &Input =
10515 Info.ConstraintOperands[OpInfo.MatchingInput];
10516 patchMatchingInput(OpInfo, Input, DAG);
10517 }
10518
10519 // Compute the constraint code and ConstraintType to use.
10520 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10521
10522 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10523 OpInfo.Type == InlineAsm::isClobber) ||
10524 OpInfo.ConstraintType == TargetLowering::C_Address)
10525 continue;
10526
10527 // In Linux PIC model, there are 4 cases about value/label addressing:
10528 //
10529 // 1: Function call or Label jmp inside the module.
10530 // 2: Data access (such as global variable, static variable) inside module.
10531 // 3: Function call or Label jmp outside the module.
10532 // 4: Data access (such as global variable) outside the module.
10533 //
10534 // Due to current llvm inline asm architecture designed to not "recognize"
10535 // the asm code, there are quite troubles for us to treat mem addressing
10536 // differently for same value/adress used in different instuctions.
10537 // For example, in pic model, call a func may in plt way or direclty
10538 // pc-related, but lea/mov a function adress may use got.
10539 //
10540 // Here we try to "recognize" function call for the case 1 and case 3 in
10541 // inline asm. And try to adjust the constraint for them.
10542 //
10543 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10544 // label, so here we don't handle jmp function label now, but we need to
10545 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10546 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10547 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10549 OpInfo.isIndirect = false;
10550 OpInfo.ConstraintType = TargetLowering::C_Address;
10551 }
10552
10553 // If this is a memory input, and if the operand is not indirect, do what we
10554 // need to provide an address for the memory input.
10555 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10556 !OpInfo.isIndirect) {
10557 assert((OpInfo.isMultipleAlternative ||
10558 (OpInfo.Type == InlineAsm::isInput)) &&
10559 "Can only indirectify direct input operands!");
10560
10561 // Memory operands really want the address of the value.
10562 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10563 OpInfo, DAG);
10564
10565 // There is no longer a Value* corresponding to this operand.
10566 OpInfo.CallOperandVal = nullptr;
10567
10568 // It is now an indirect operand.
10569 OpInfo.isIndirect = true;
10570 }
10571 }
10572}
10573
10574/// Prepare DAG-level operands. As part of this, assign virtual and physical
10575/// registers for inputs and output.
10576static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10577 const CallBase &Call,
10578 SelectionDAGBuilder &Builder,
10579 const TargetLowering &TLI,
10580 SelectionDAG &DAG) {
10581 SDLoc DL = Builder.getCurSDLoc();
10582 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10583 // Assign Registers.
10584 SDISelAsmOperandInfo &RefOpInfo =
10585 OpInfo.isMatchingInputConstraint()
10586 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10587 : OpInfo;
10588 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10589 if (RegError) {
10590 const MachineFunction &MF = DAG.getMachineFunction();
10592 const char *RegName = TRI.getName(*RegError);
10593 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10594 << OpInfo.ConstraintCode
10595 << "' does not match required type";
10596 return true;
10597 }
10598
10599 auto DetectWriteToReservedRegister = [&]() {
10600 const MachineFunction &MF = DAG.getMachineFunction();
10602
10603 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10604 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10605 Info.ErrorMsg << "write to reserved register '"
10606 << TRI.getRegAsmName(Reg) << "'";
10607 return true;
10608 }
10609 }
10610
10611 return false;
10612 };
10613 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10614 (OpInfo.Type == InlineAsm::isInput &&
10615 !OpInfo.isMatchingInputConstraint())) &&
10616 "Only address as input operand is allowed.");
10617
10618 switch (OpInfo.Type) {
10620 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10621 const InlineAsm::ConstraintCode ConstraintID =
10622 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10624 "Failed to convert memory constraint code to constraint id.");
10625
10626 // Add information to the INLINEASM node to know about this output.
10628 OpFlags.setMemConstraint(ConstraintID);
10629 Info.AsmNodeOperands.push_back(
10630 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10631 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10632 } else {
10633 // Otherwise, this outputs to a register (directly for C_Register /
10634 // C_RegisterClass, and a target-defined fashion for
10635 // C_Immediate/C_Other). Find a register that we can use.
10636 if (OpInfo.AssignedRegs.Regs.empty()) {
10637 Info.ErrorMsg << "could not allocate output register for "
10638 << "constraint '" << OpInfo.ConstraintCode << "'";
10639 return true;
10640 }
10641
10642 if (DetectWriteToReservedRegister())
10643 return true;
10644
10645 // Add information to the INLINEASM node to know that this register is
10646 // set.
10647 OpInfo.AssignedRegs.AddInlineAsmOperands(
10648 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10650 false, 0, DL, DAG, Info.AsmNodeOperands);
10651 }
10652 break;
10653
10654 case InlineAsm::isInput:
10655 case InlineAsm::isLabel: {
10656 SDValue InOperandVal = OpInfo.CallOperand;
10657
10658 if (OpInfo.isMatchingInputConstraint()) {
10659 // If this is required to match an output register we have already set,
10660 // just use its register.
10661 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10662 Info.AsmNodeOperands);
10663 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10664 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10665 if (OpInfo.isIndirect) {
10666 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10667 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10668 << "tied indirect register inputs";
10669 return true;
10670 }
10671
10674 MachineRegisterInfo &MRI = MF.getRegInfo();
10676 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10677 Register TiedReg = R->getReg();
10678 MVT RegVT = R->getSimpleValueType(0);
10679 const TargetRegisterClass *RC =
10680 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
10681 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10682 : TRI.getMinimalPhysRegClass(TiedReg);
10683 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10684 Regs.push_back(MRI.createVirtualRegister(RC));
10685
10686 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10687
10688 // Use the produced MatchedRegs object to
10689 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10690 &Info.Glue, &Call);
10692 OpInfo.getMatchedOperand(), DL, DAG,
10693 Info.AsmNodeOperands);
10694 break;
10695 }
10696
10697 assert(Flag.isMemKind() && "Unknown matching constraint!");
10698 assert(Flag.getNumOperandRegisters() == 1 &&
10699 "Unexpected number of operands");
10700
10701 // Add information to the INLINEASM node to know about this input.
10702 // See InlineAsm.h isUseOperandTiedToDef.
10703 Flag.clearMemConstraint();
10704 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10705 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10706 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10707 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10708 break;
10709 }
10710
10711 // Treat indirect 'X' constraint as memory.
10712 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10713 OpInfo.isIndirect)
10714 OpInfo.ConstraintType = TargetLowering::C_Memory;
10715
10716 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10717 OpInfo.ConstraintType == TargetLowering::C_Other) {
10718 std::vector<SDValue> Ops;
10719 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10720 Ops, DAG);
10721 if (Ops.empty()) {
10722 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10723 if (isa<ConstantSDNode>(InOperandVal)) {
10724 Info.ErrorMsg << "value out of range for constraint '"
10725 << OpInfo.ConstraintCode << "'";
10726 return true;
10727 }
10728
10729 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10730 << OpInfo.ConstraintCode << "'";
10731 return true;
10732 }
10733
10734 // Add information to the INLINEASM node to know about this input.
10735 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10736 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10737 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10738 llvm::append_range(Info.AsmNodeOperands, Ops);
10739 break;
10740 }
10741
10742 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10743 assert((OpInfo.isIndirect ||
10744 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10745 "Operand must be indirect to be a mem!");
10746 assert(InOperandVal.getValueType() ==
10747 TLI.getPointerTy(DAG.getDataLayout()) &&
10748 "Memory operands expect pointer values");
10749
10750 const InlineAsm::ConstraintCode ConstraintID =
10751 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10753 "Failed to convert memory constraint code to constraint id.");
10754
10755 // Add information to the INLINEASM node to know about this input.
10757 ResOpType.setMemConstraint(ConstraintID);
10758 Info.AsmNodeOperands.push_back(
10759 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10760 Info.AsmNodeOperands.push_back(InOperandVal);
10761 break;
10762 }
10763
10764 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10765 const InlineAsm::ConstraintCode ConstraintID =
10766 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10768 "Failed to convert memory constraint code to constraint id.");
10769
10771
10772 SDValue AsmOp = InOperandVal;
10773 if (isFunction(InOperandVal)) {
10774 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10775 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10776 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10777 InOperandVal.getValueType(),
10778 GA->getOffset());
10779 }
10780
10781 // Add information to the INLINEASM node to know about this input.
10782 ResOpType.setMemConstraint(ConstraintID);
10783
10784 Info.AsmNodeOperands.push_back(
10785 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10786 Info.AsmNodeOperands.push_back(AsmOp);
10787 break;
10788 }
10789
10790 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10791 OpInfo.ConstraintType != TargetLowering::C_Register) {
10792 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10793 << "'";
10794 return true;
10795 }
10796
10797 // TODO: Support this.
10798 if (OpInfo.isIndirect) {
10799 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10800 << "constraint '" << OpInfo.ConstraintCode << "'";
10801 return true;
10802 }
10803
10804 // Copy the input into the appropriate registers.
10805 if (OpInfo.AssignedRegs.Regs.empty()) {
10806 Info.ErrorMsg << "could not allocate input reg for constraint '"
10807 << OpInfo.ConstraintCode << "'";
10808 return true;
10809 }
10810
10811 if (DetectWriteToReservedRegister())
10812 return true;
10813
10814 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10815 &Info.Glue, &Call);
10816 OpInfo.AssignedRegs.AddInlineAsmOperands(
10817 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10818 break;
10819 }
10820
10822 // Add the clobbered value to the operand list, so that the register
10823 // allocator is aware that the physreg got clobbered.
10824 if (!OpInfo.AssignedRegs.Regs.empty())
10825 OpInfo.AssignedRegs.AddInlineAsmOperands(
10826 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10827 break;
10828 }
10829 }
10830
10831 return false;
10832}
10833
10834/// DetermineConstraints - Find the constraints to use for inline asm operands.
10835static bool
10836determineConstraints(ConstraintDecisionInfo &Info,
10837 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10838 const CallBase &Call, SelectionDAGBuilder &Builder,
10839 const TargetLowering &TLI, const TargetMachine &TM,
10840 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10841 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10842 ExtraFlags ExtraInfo(Call);
10843
10844 // First pass: Construct operand info objects.
10845 Info.HasSideEffect = IA->hasSideEffects();
10846 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10847 return true;
10848
10849 // We won't need to flush pending loads if this asm doesn't touch
10850 // memory and is nonvolatile.
10851 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10852
10853 bool IsCallBr = isa<CallBrInst>(Call);
10854 bool EmitEHLabels = isa<InvokeInst>(Call);
10855 if (IsCallBr || EmitEHLabels)
10856 // If this is a callbr or invoke we need to flush pending exports since
10857 // inlineasm_br and invoke are terminators.
10858 // We need to do this before nodes are glued to the inlineasm_br node.
10859 Info.Chain = Builder.getControlRoot();
10860
10861 if (EmitEHLabels)
10862 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10863
10864 // Second pass: Compute which constraint option to use.
10865 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10866
10867 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10868 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10869 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10870 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10871
10872 // If we have a !srcloc metadata node associated with it, we want to attach
10873 // this to the ultimately generated inline asm machineinstr. To do this, we
10874 // pass in the third operand as this (potentially null) inline asm MDNode.
10875 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10876 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10877
10878 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10879 // bits as operand 3.
10880 Info.AsmNodeOperands.push_back(
10881 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10882 TLI.getPointerTy(DAG.getDataLayout())));
10883
10884 // Third pass: Prepare DAG-level operands
10885 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10886}
10887
10888/// visitInlineAsm - Handle a call to an InlineAsm object.
10889void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10890 const BasicBlock *EHPadBB) {
10891 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10893 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
10894
10895 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10896 "InvokeInst must have an EHPadBB");
10897
10898 ConstraintDecisionInfo Info;
10899 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
10900 EHPadBB))
10901 return emitInlineAsmError(Call, Info.ErrorMsg.str());
10902
10903 SDValue Glue = Info.Glue;
10904 SDValue Chain = Info.Chain;
10905
10906 // Finish up input operands. Set the input chain and add the flag last.
10907 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10908 if (Glue.getNode())
10909 Info.AsmNodeOperands.push_back(Glue);
10910
10911 bool IsCallBr = isa<CallBrInst>(Call);
10912 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10913 Chain =
10914 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
10915 Info.AsmNodeOperands);
10916 Glue = Chain.getValue(1);
10917
10918 // Do additional work to generate outputs.
10919
10920 SmallVector<EVT, 1> ResultVTs;
10921 SmallVector<SDValue, 1> ResultValues;
10922 SmallVector<SDValue, 8> OutChains;
10923
10924 llvm::Type *CallResultType = Call.getType();
10925 ArrayRef<Type *> ResultTypes;
10926 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10927 ResultTypes = StructResult->elements();
10928 else if (!CallResultType->isVoidTy())
10929 ResultTypes = ArrayRef(CallResultType);
10930
10931 auto CurResultType = ResultTypes.begin();
10932 auto handleRegAssign = [&](SDValue V) {
10933 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10934 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10935 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10936 ++CurResultType;
10937 // If the type of the inline asm call site return value is different but has
10938 // same size as the type of the asm output bitcast it. One example of this
10939 // is for vectors with different width / number of elements. This can
10940 // happen for register classes that can contain multiple different value
10941 // types. The preg or vreg allocated may not have the same VT as was
10942 // expected.
10943 //
10944 // This can also happen for a return value that disagrees with the register
10945 // class it is put in, eg. a double in a general-purpose register on a
10946 // 32-bit machine.
10947 if (ResultVT != V.getValueType() &&
10948 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10949 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10950 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10951 V.getValueType().isInteger()) {
10952 // If a result value was tied to an input value, the computed result
10953 // may have a wider width than the expected result. Extract the
10954 // relevant portion.
10955 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10956 }
10957 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10958 ResultVTs.push_back(ResultVT);
10959 ResultValues.push_back(V);
10960 };
10961
10962 // Deal with output operands.
10963 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10964 if (OpInfo.Type == InlineAsm::isOutput) {
10965 SDValue Val;
10966 // Skip trivial output operands.
10967 if (OpInfo.AssignedRegs.Regs.empty())
10968 continue;
10969
10970 switch (OpInfo.ConstraintType) {
10973 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10974 Chain, &Glue, &Call);
10975 break;
10978 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10979 OpInfo, DAG);
10980 break;
10982 break; // Already handled.
10984 break; // Silence warning.
10986 assert(false && "Unexpected unknown constraint");
10987 }
10988
10989 // Indirect output manifest as stores. Record output chains.
10990 if (OpInfo.isIndirect) {
10991 const Value *Ptr = OpInfo.CallOperandVal;
10992 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10993 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10994 MachinePointerInfo(Ptr));
10995 OutChains.push_back(Store);
10996 } else {
10997 // generate CopyFromRegs to associated registers.
10998 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10999 if (Val.getOpcode() == ISD::MERGE_VALUES) {
11000 for (const SDValue &V : Val->op_values())
11001 handleRegAssign(V);
11002 } else
11003 handleRegAssign(Val);
11004 }
11005 }
11006 }
11007
11008 // Set results.
11009 if (!ResultValues.empty()) {
11010 assert(CurResultType == ResultTypes.end() &&
11011 "Mismatch in number of ResultTypes");
11012 assert(ResultValues.size() == ResultTypes.size() &&
11013 "Mismatch in number of output operands in asm result");
11014
11015 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11016 DAG.getVTList(ResultVTs), ResultValues);
11017 setValue(&Call, V);
11018 }
11019
11020 // Collect store chains.
11021 if (!OutChains.empty())
11022 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
11023
11024 if (const auto *II = dyn_cast<InvokeInst>(&Call))
11025 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
11026
11027 // Only Update Root if inline assembly has a memory effect.
11028 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
11029 IsCallBr || isa<InvokeInst>(Call))
11030 DAG.setRoot(Chain);
11031}
11032
11033void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
11034 const Twine &Message) {
11035 LLVMContext &Ctx = *DAG.getContext();
11036 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
11037
11038 // Make sure we leave the DAG in a valid state
11039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11040 SmallVector<EVT, 1> ValueVTs;
11041 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
11042
11043 if (ValueVTs.empty())
11044 return;
11045
11047 for (const EVT &VT : ValueVTs)
11048 Ops.push_back(DAG.getUNDEF(VT));
11049
11050 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
11051}
11052
11053void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
11054 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
11055 MVT::Other, getRoot(),
11056 getValue(I.getArgOperand(0)),
11057 DAG.getSrcValue(I.getArgOperand(0))));
11058}
11059
11060void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
11061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11062 const DataLayout &DL = DAG.getDataLayout();
11063 SDValue V = DAG.getVAArg(
11064 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
11065 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
11066 DL.getABITypeAlign(I.getType()).value());
11067 DAG.setRoot(V.getValue(1));
11068
11069 if (I.getType()->isPointerTy())
11070 V = DAG.getPtrExtOrTrunc(
11071 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
11072 setValue(&I, V);
11073}
11074
11075void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
11076 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
11077 MVT::Other, getRoot(),
11078 getValue(I.getArgOperand(0)),
11079 DAG.getSrcValue(I.getArgOperand(0))));
11080}
11081
11082void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
11083 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
11084 MVT::Other, getRoot(),
11085 getValue(I.getArgOperand(0)),
11086 getValue(I.getArgOperand(1)),
11087 DAG.getSrcValue(I.getArgOperand(0)),
11088 DAG.getSrcValue(I.getArgOperand(1))));
11089}
11090
11092 const Instruction &I,
11093 SDValue Op) {
11094 std::optional<ConstantRange> CR = getRange(I);
11095
11096 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
11097 return Op;
11098
11099 APInt Hi = CR->getUnsignedMax();
11100 unsigned Bits = std::max(Hi.getActiveBits(),
11101 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
11102
11103 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11104
11105 SDLoc SL = getCurSDLoc();
11106
11107 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
11108 DAG.getValueType(SmallVT));
11109 unsigned NumVals = Op.getNode()->getNumValues();
11110 if (NumVals == 1)
11111 return ZExt;
11112
11114
11115 Ops.push_back(ZExt);
11116 for (unsigned I = 1; I != NumVals; ++I)
11117 Ops.push_back(Op.getValue(I));
11118
11119 return DAG.getMergeValues(Ops, SL);
11120}
11121
11123 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
11124 FPClassTest Classes = getNoFPClass(I);
11125 if (Classes == fcNone)
11126 return Op;
11127
11128 SDLoc SL = getCurSDLoc();
11129 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
11130
11131 if (Op.getOpcode() != ISD::MERGE_VALUES) {
11132 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
11133 TestConst);
11134 }
11135
11136 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
11137 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
11138 SDValue MergeOp = Op.getOperand(I);
11139 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
11140 MergeOp, TestConst);
11141 }
11142
11143 return DAG.getMergeValues(Ops, SL);
11144}
11145
11146/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
11147/// the call being lowered.
11148///
11149/// This is a helper for lowering intrinsics that follow a target calling
11150/// convention or require stack pointer adjustment. Only a subset of the
11151/// intrinsic's operands need to participate in the calling convention.
11154 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11155 AttributeSet RetAttrs, bool IsPatchPoint) {
11157 Args.reserve(NumArgs);
11158
11159 // Populate the argument list.
11160 // Attributes for args start at offset 1, after the return attribute.
11161 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11162 ArgI != ArgE; ++ArgI) {
11163 const Value *V = Call->getOperand(ArgI);
11164
11165 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11166
11167 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11168 Entry.setAttributes(Call, ArgI);
11169 Args.push_back(Entry);
11170 }
11171
11173 .setChain(getRoot())
11174 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
11175 RetAttrs)
11176 .setDiscardResult(Call->use_empty())
11177 .setIsPatchPoint(IsPatchPoint)
11179 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
11180}
11181
11182/// Add a stack map intrinsic call's live variable operands to a stackmap
11183/// or patchpoint target node's operand list.
11184///
11185/// Constants are converted to TargetConstants purely as an optimization to
11186/// avoid constant materialization and register allocation.
11187///
11188/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11189/// generate addess computation nodes, and so FinalizeISel can convert the
11190/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11191/// address materialization and register allocation, but may also be required
11192/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11193/// alloca in the entry block, then the runtime may assume that the alloca's
11194/// StackMap location can be read immediately after compilation and that the
11195/// location is valid at any point during execution (this is similar to the
11196/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11197/// only available in a register, then the runtime would need to trap when
11198/// execution reaches the StackMap in order to read the alloca's location.
11199static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11201 SelectionDAGBuilder &Builder) {
11202 SelectionDAG &DAG = Builder.DAG;
11203 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11204 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11205
11206 // Things on the stack are pointer-typed, meaning that they are already
11207 // legal and can be emitted directly to target nodes.
11209 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11210 } else {
11211 // Otherwise emit a target independent node to be legalised.
11212 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11213 }
11214 }
11215}
11216
11217/// Lower llvm.experimental.stackmap.
11218void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11219 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11220 // [live variables...])
11221
11222 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11223
11224 SDValue Chain, InGlue, Callee;
11226
11227 SDLoc DL = getCurSDLoc();
11229
11230 // The stackmap intrinsic only records the live variables (the arguments
11231 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11232 // intrinsic, this won't be lowered to a function call. This means we don't
11233 // have to worry about calling conventions and target specific lowering code.
11234 // Instead we perform the call lowering right here.
11235 //
11236 // chain, flag = CALLSEQ_START(chain, 0, 0)
11237 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11238 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11239 //
11240 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11241 InGlue = Chain.getValue(1);
11242
11243 // Add the STACKMAP operands, starting with DAG house-keeping.
11244 Ops.push_back(Chain);
11245 Ops.push_back(InGlue);
11246
11247 // Add the <id>, <numShadowBytes> operands.
11248 //
11249 // These do not require legalisation, and can be emitted directly to target
11250 // constant nodes.
11251 SDValue ID = getValue(CI.getArgOperand(0));
11252 assert(ID.getValueType() == MVT::i64);
11253 SDValue IDConst =
11254 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11255 Ops.push_back(IDConst);
11256
11257 SDValue Shad = getValue(CI.getArgOperand(1));
11258 assert(Shad.getValueType() == MVT::i32);
11259 SDValue ShadConst =
11260 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11261 Ops.push_back(ShadConst);
11262
11263 // Add the live variables.
11264 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11265
11266 // Create the STACKMAP node.
11267 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11268 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11269 InGlue = Chain.getValue(1);
11270
11271 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11272
11273 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11274
11275 // Set the root to the target-lowered call chain.
11276 DAG.setRoot(Chain);
11277
11278 // Inform the Frame Information that we have a stackmap in this function.
11279 FuncInfo.MF->getFrameInfo().setHasStackMap();
11280}
11281
11282/// Lower llvm.experimental.patchpoint directly to its target opcode.
11283void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11284 const BasicBlock *EHPadBB) {
11285 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11286 // i32 <numBytes>,
11287 // i8* <target>,
11288 // i32 <numArgs>,
11289 // [Args...],
11290 // [live variables...])
11291
11293 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11294 bool HasDef = !CB.getType()->isVoidTy();
11295 SDLoc dl = getCurSDLoc();
11297
11298 // Handle immediate and symbolic callees.
11299 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11300 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11301 /*isTarget=*/true);
11302 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11303 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11304 SDLoc(SymbolicCallee),
11305 SymbolicCallee->getValueType(0));
11306
11307 // Get the real number of arguments participating in the call <numArgs>
11308 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
11309 unsigned NumArgs = NArgVal->getAsZExtVal();
11310
11311 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11312 // Intrinsics include all meta-operands up to but not including CC.
11313 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11314 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11315 "Not enough arguments provided to the patchpoint intrinsic");
11316
11317 // For AnyRegCC the arguments are lowered later on manually.
11318 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11319 Type *ReturnTy =
11320 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11321
11322 TargetLowering::CallLoweringInfo CLI(DAG);
11323 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11324 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11325 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11326
11327 SDNode *CallEnd = Result.second.getNode();
11328 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11329 CallEnd = CallEnd->getOperand(0).getNode();
11330 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11331 CallEnd = CallEnd->getOperand(0).getNode();
11332
11333 /// Get a call instruction from the call sequence chain.
11334 /// Tail calls are not allowed.
11335 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11336 "Expected a callseq node.");
11337 SDNode *Call = CallEnd->getOperand(0).getNode();
11338 bool HasGlue = Call->getGluedNode();
11339
11340 // Replace the target specific call node with the patchable intrinsic.
11342
11343 // Push the chain.
11344 Ops.push_back(*(Call->op_begin()));
11345
11346 // Optionally, push the glue (if any).
11347 if (HasGlue)
11348 Ops.push_back(*(Call->op_end() - 1));
11349
11350 // Push the register mask info.
11351 if (HasGlue)
11352 Ops.push_back(*(Call->op_end() - 2));
11353 else
11354 Ops.push_back(*(Call->op_end() - 1));
11355
11356 // Add the <id> and <numBytes> constants.
11357 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
11358 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11359 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
11360 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11361
11362 // Add the callee.
11363 Ops.push_back(Callee);
11364
11365 // Adjust <numArgs> to account for any arguments that have been passed on the
11366 // stack instead.
11367 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11368 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11369 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11370 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11371
11372 // Add the calling convention
11373 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11374
11375 // Add the arguments we omitted previously. The register allocator should
11376 // place these in any free register.
11377 if (IsAnyRegCC)
11378 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11379 Ops.push_back(getValue(CB.getArgOperand(i)));
11380
11381 // Push the arguments from the call instruction.
11382 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11383 Ops.append(Call->op_begin() + 2, e);
11384
11385 // Push live variables for the stack map.
11386 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11387
11388 SDVTList NodeTys;
11389 if (IsAnyRegCC && HasDef) {
11390 // Create the return types based on the intrinsic definition
11391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11392 SmallVector<EVT, 3> ValueVTs;
11393 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11394 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11395
11396 // There is always a chain and a glue type at the end
11397 ValueVTs.push_back(MVT::Other);
11398 ValueVTs.push_back(MVT::Glue);
11399 NodeTys = DAG.getVTList(ValueVTs);
11400 } else
11401 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11402
11403 // Replace the target specific call node with a PATCHPOINT node.
11404 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11405
11406 // Update the NodeMap.
11407 if (HasDef) {
11408 if (IsAnyRegCC)
11409 setValue(&CB, SDValue(PPV.getNode(), 0));
11410 else
11411 setValue(&CB, Result.first);
11412 }
11413
11414 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11415 // call sequence. Furthermore the location of the chain and glue can change
11416 // when the AnyReg calling convention is used and the intrinsic returns a
11417 // value.
11418 if (IsAnyRegCC && HasDef) {
11419 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11420 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11421 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11422 } else
11423 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11424 DAG.DeleteNode(Call);
11425
11426 // Inform the Frame Information that we have a patchpoint in this function.
11427 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11428}
11429
11430void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11431 unsigned Intrinsic) {
11432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11433 SDValue Op1 = getValue(I.getArgOperand(0));
11434 SDValue Op2;
11435 if (I.arg_size() > 1)
11436 Op2 = getValue(I.getArgOperand(1));
11437 SDLoc dl = getCurSDLoc();
11438 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11439 SDValue Res;
11440 SDNodeFlags SDFlags;
11441 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11442 SDFlags.copyFMF(*FPMO);
11443
11444 switch (Intrinsic) {
11445 case Intrinsic::vector_reduce_fadd:
11446 if (SDFlags.hasAllowReassociation())
11447 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11448 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11449 SDFlags);
11450 else
11451 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11452 break;
11453 case Intrinsic::vector_reduce_fmul:
11454 if (SDFlags.hasAllowReassociation())
11455 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11456 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11457 SDFlags);
11458 else
11459 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11460 break;
11461 case Intrinsic::vector_reduce_add:
11462 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11463 break;
11464 case Intrinsic::vector_reduce_mul:
11465 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11466 break;
11467 case Intrinsic::vector_reduce_and:
11468 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11469 break;
11470 case Intrinsic::vector_reduce_or:
11471 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11472 break;
11473 case Intrinsic::vector_reduce_xor:
11474 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11475 break;
11476 case Intrinsic::vector_reduce_smax:
11477 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11478 break;
11479 case Intrinsic::vector_reduce_smin:
11480 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11481 break;
11482 case Intrinsic::vector_reduce_umax:
11483 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11484 break;
11485 case Intrinsic::vector_reduce_umin:
11486 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11487 break;
11488 case Intrinsic::vector_reduce_fmax:
11489 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11490 break;
11491 case Intrinsic::vector_reduce_fmin:
11492 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11493 break;
11494 case Intrinsic::vector_reduce_fmaximum:
11495 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11496 break;
11497 case Intrinsic::vector_reduce_fminimum:
11498 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11499 break;
11500 case Intrinsic::vector_reduce_fmaximumnum:
11501 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11502 break;
11503 case Intrinsic::vector_reduce_fminimumnum:
11504 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11505 break;
11506 default:
11507 llvm_unreachable("Unhandled vector reduce intrinsic");
11508 }
11509 setValue(&I, Res);
11510}
11511
11512/// Returns an AttributeList representing the attributes applied to the return
11513/// value of the given call.
11516 if (CLI.RetSExt)
11517 Attrs.push_back(Attribute::SExt);
11518 if (CLI.RetZExt)
11519 Attrs.push_back(Attribute::ZExt);
11520 if (CLI.IsInReg)
11521 Attrs.push_back(Attribute::InReg);
11522
11523 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11524 Attrs);
11525}
11526
11527/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11528/// implementation, which just calls LowerCall.
11529/// FIXME: When all targets are
11530/// migrated to using LowerCall, this hook should be integrated into SDISel.
11531std::pair<SDValue, SDValue>
11533 LLVMContext &Context = CLI.RetTy->getContext();
11534
11535 // Handle the incoming return values from the call.
11536 CLI.Ins.clear();
11537 SmallVector<Type *, 4> RetOrigTys;
11539 auto &DL = CLI.DAG.getDataLayout();
11540 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11541
11542 SmallVector<EVT, 4> RetVTs;
11543 if (CLI.RetTy != CLI.OrigRetTy) {
11544 assert(RetOrigTys.size() == 1 &&
11545 "Only supported for non-aggregate returns");
11546 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11547 } else {
11548 for (Type *Ty : RetOrigTys)
11549 RetVTs.push_back(getValueType(DL, Ty));
11550 }
11551
11552 if (CLI.IsPostTypeLegalization) {
11553 // If we are lowering a libcall after legalization, split the return type.
11554 SmallVector<Type *, 4> OldRetOrigTys;
11555 SmallVector<EVT, 4> OldRetVTs;
11556 SmallVector<TypeSize, 4> OldOffsets;
11557 RetOrigTys.swap(OldRetOrigTys);
11558 RetVTs.swap(OldRetVTs);
11559 Offsets.swap(OldOffsets);
11560
11561 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11562 EVT RetVT = OldRetVTs[i];
11563 uint64_t Offset = OldOffsets[i];
11564 MVT RegisterVT = getRegisterType(Context, RetVT);
11565 unsigned NumRegs = getNumRegisters(Context, RetVT);
11566 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11567 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11568 RetVTs.append(NumRegs, RegisterVT);
11569 for (unsigned j = 0; j != NumRegs; ++j)
11570 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11571 }
11572 }
11573
11575 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11576
11577 bool CanLowerReturn =
11579 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11580
11581 SDValue DemoteStackSlot;
11582 int DemoteStackIdx = -100;
11583 if (!CanLowerReturn) {
11584 // FIXME: equivalent assert?
11585 // assert(!CS.hasInAllocaArgument() &&
11586 // "sret demotion is incompatible with inalloca");
11587 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11588 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11590 DemoteStackIdx =
11591 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11592 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11593
11594 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11595 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11596 Entry.IsSRet = true;
11597 Entry.Alignment = Alignment;
11598 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11599 CLI.NumFixedArgs += 1;
11600 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11601 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(Context);
11602
11603 // sret demotion isn't compatible with tail-calls, since the sret argument
11604 // points into the callers stack frame.
11605 CLI.IsTailCall = false;
11606 } else {
11607 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11608 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11609 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11610 ISD::ArgFlagsTy Flags;
11611 if (NeedsRegBlock) {
11612 Flags.setInConsecutiveRegs();
11613 if (I == RetVTs.size() - 1)
11614 Flags.setInConsecutiveRegsLast();
11615 }
11616 EVT VT = RetVTs[I];
11617 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11618 unsigned NumRegs =
11619 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11620 for (unsigned i = 0; i != NumRegs; ++i) {
11621 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11623 if (CLI.RetTy->isPointerTy()) {
11624 Ret.Flags.setPointer();
11626 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11627 }
11628 if (CLI.RetSExt)
11629 Ret.Flags.setSExt();
11630 if (CLI.RetZExt)
11631 Ret.Flags.setZExt();
11632 if (CLI.IsInReg)
11633 Ret.Flags.setInReg();
11634 CLI.Ins.push_back(Ret);
11635 }
11636 }
11637 }
11638
11639 // We push in swifterror return as the last element of CLI.Ins.
11640 ArgListTy &Args = CLI.getArgs();
11641 if (supportSwiftError()) {
11642 for (const ArgListEntry &Arg : Args) {
11643 if (Arg.IsSwiftError) {
11644 ISD::ArgFlagsTy Flags;
11645 Flags.setSwiftError();
11647 PointerType::getUnqual(Context),
11648 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11649 CLI.Ins.push_back(Ret);
11650 }
11651 }
11652 }
11653
11654 // Handle all of the outgoing arguments.
11655 CLI.Outs.clear();
11656 CLI.OutVals.clear();
11657 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11658 SmallVector<Type *, 4> OrigArgTys;
11659 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11660 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11661 Type *FinalType = Args[i].Ty;
11662 if (Args[i].IsByVal)
11663 FinalType = Args[i].IndirectType;
11664 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11665 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11666 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11667 ++Value) {
11668 Type *OrigArgTy = OrigArgTys[Value];
11669 Type *ArgTy = OrigArgTy;
11670 if (Args[i].Ty != Args[i].OrigTy) {
11671 assert(Value == 0 && "Only supported for non-aggregate arguments");
11672 ArgTy = Args[i].Ty;
11673 }
11674
11675 EVT VT = getValueType(DL, ArgTy);
11676 SDValue Op = SDValue(Args[i].Node.getNode(),
11677 Args[i].Node.getResNo() + Value);
11678 ISD::ArgFlagsTy Flags;
11679
11680 // Certain targets (such as MIPS), may have a different ABI alignment
11681 // for a type depending on the context. Give the target a chance to
11682 // specify the alignment it wants.
11683 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11684 Flags.setOrigAlign(OriginalAlignment);
11685
11686 if (i >= CLI.NumFixedArgs)
11687 Flags.setVarArg();
11688 if (ArgTy->isPointerTy()) {
11689 Flags.setPointer();
11690 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11691 }
11692 if (Args[i].IsZExt)
11693 Flags.setZExt();
11694 if (Args[i].IsSExt)
11695 Flags.setSExt();
11696 if (Args[i].IsNoExt)
11697 Flags.setNoExt();
11698 if (Args[i].IsInReg) {
11699 // If we are using vectorcall calling convention, a structure that is
11700 // passed InReg - is surely an HVA
11702 isa<StructType>(FinalType)) {
11703 // The first value of a structure is marked
11704 if (0 == Value)
11705 Flags.setHvaStart();
11706 Flags.setHva();
11707 }
11708 // Set InReg Flag
11709 Flags.setInReg();
11710 }
11711 if (Args[i].IsSRet)
11712 Flags.setSRet();
11713 if (Args[i].IsSwiftSelf)
11714 Flags.setSwiftSelf();
11715 if (Args[i].IsSwiftAsync)
11716 Flags.setSwiftAsync();
11717 if (Args[i].IsSwiftError)
11718 Flags.setSwiftError();
11719 if (Args[i].IsCFGuardTarget)
11720 Flags.setCFGuardTarget();
11721 if (Args[i].IsByVal)
11722 Flags.setByVal();
11723 if (Args[i].IsByRef)
11724 Flags.setByRef();
11725 if (Args[i].IsPreallocated) {
11726 Flags.setPreallocated();
11727 // Set the byval flag for CCAssignFn callbacks that don't know about
11728 // preallocated. This way we can know how many bytes we should've
11729 // allocated and how many bytes a callee cleanup function will pop. If
11730 // we port preallocated to more targets, we'll have to add custom
11731 // preallocated handling in the various CC lowering callbacks.
11732 Flags.setByVal();
11733 }
11734 if (Args[i].IsInAlloca) {
11735 Flags.setInAlloca();
11736 // Set the byval flag for CCAssignFn callbacks that don't know about
11737 // inalloca. This way we can know how many bytes we should've allocated
11738 // and how many bytes a callee cleanup function will pop. If we port
11739 // inalloca to more targets, we'll have to add custom inalloca handling
11740 // in the various CC lowering callbacks.
11741 Flags.setByVal();
11742 }
11743 Align MemAlign;
11744 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11745 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11746 Flags.setByValSize(FrameSize);
11747
11748 // info is not there but there are cases it cannot get right.
11749 if (auto MA = Args[i].Alignment)
11750 MemAlign = *MA;
11751 else
11752 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11753 } else if (auto MA = Args[i].Alignment) {
11754 MemAlign = *MA;
11755 } else {
11756 MemAlign = OriginalAlignment;
11757 }
11758 Flags.setMemAlign(MemAlign);
11759 if (Args[i].IsNest)
11760 Flags.setNest();
11761 if (NeedsRegBlock)
11762 Flags.setInConsecutiveRegs();
11763
11764 MVT PartVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11765 unsigned NumParts =
11766 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11767 SmallVector<SDValue, 4> Parts(NumParts);
11768 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11769
11770 if (Args[i].IsSExt)
11771 ExtendKind = ISD::SIGN_EXTEND;
11772 else if (Args[i].IsZExt)
11773 ExtendKind = ISD::ZERO_EXTEND;
11774
11775 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11776 // for now.
11777 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11779 assert((CLI.RetTy == Args[i].Ty ||
11780 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11782 Args[i].Ty->getPointerAddressSpace())) &&
11783 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11784 // Before passing 'returned' to the target lowering code, ensure that
11785 // either the register MVT and the actual EVT are the same size or that
11786 // the return value and argument are extended in the same way; in these
11787 // cases it's safe to pass the argument register value unchanged as the
11788 // return register value (although it's at the target's option whether
11789 // to do so)
11790 // TODO: allow code generation to take advantage of partially preserved
11791 // registers rather than clobbering the entire register when the
11792 // parameter extension method is not compatible with the return
11793 // extension method
11794 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11795 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11796 CLI.RetZExt == Args[i].IsZExt))
11797 Flags.setReturned();
11798 }
11799
11800 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11801 CLI.CallConv, ExtendKind);
11802
11803 for (unsigned j = 0; j != NumParts; ++j) {
11804 // if it isn't first piece, alignment must be 1
11805 // For scalable vectors the scalable part is currently handled
11806 // by individual targets, so we just use the known minimum size here.
11807 ISD::OutputArg MyFlags(
11808 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11809 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11810 if (NumParts > 1 && j == 0)
11811 MyFlags.Flags.setSplit();
11812 else if (j != 0) {
11813 MyFlags.Flags.setOrigAlign(Align(1));
11814 if (j == NumParts - 1)
11815 MyFlags.Flags.setSplitEnd();
11816 }
11817
11818 CLI.Outs.push_back(MyFlags);
11819 CLI.OutVals.push_back(Parts[j]);
11820 }
11821
11822 if (NeedsRegBlock && Value == NumValues - 1)
11823 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11824 }
11825 }
11826
11828 CLI.Chain = LowerCall(CLI, InVals);
11829
11830 // Update CLI.InVals to use outside of this function.
11831 CLI.InVals = InVals;
11832
11833 // Verify that the target's LowerCall behaved as expected.
11834 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11835 "LowerCall didn't return a valid chain!");
11836 assert((!CLI.IsTailCall || InVals.empty()) &&
11837 "LowerCall emitted a return value for a tail call!");
11838 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11839 "LowerCall didn't emit the correct number of values!");
11840
11841 // For a tail call, the return value is merely live-out and there aren't
11842 // any nodes in the DAG representing it. Return a special value to
11843 // indicate that a tail call has been emitted and no more Instructions
11844 // should be processed in the current block.
11845 if (CLI.IsTailCall) {
11846 CLI.DAG.setRoot(CLI.Chain);
11847 return std::make_pair(SDValue(), SDValue());
11848 }
11849
11850#ifndef NDEBUG
11851 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11852 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11853 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11854 "LowerCall emitted a value with the wrong type!");
11855 }
11856#endif
11857
11858 SmallVector<SDValue, 4> ReturnValues;
11859 if (!CanLowerReturn) {
11860 // The instruction result is the result of loading from the
11861 // hidden sret parameter.
11862 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11863
11864 unsigned NumValues = RetVTs.size();
11865 ReturnValues.resize(NumValues);
11866 SmallVector<SDValue, 4> Chains(NumValues);
11867
11868 // An aggregate return value cannot wrap around the address space, so
11869 // offsets to its parts don't wrap either.
11871 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11872 for (unsigned i = 0; i < NumValues; ++i) {
11874 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11876 SDValue L = CLI.DAG.getLoad(
11877 RetVTs[i], CLI.DL, CLI.Chain, Add,
11879 DemoteStackIdx, Offsets[i]),
11880 HiddenSRetAlign);
11881 ReturnValues[i] = L;
11882 Chains[i] = L.getValue(1);
11883 }
11884
11885 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11886 } else {
11887 // Collect the legal value parts into potentially illegal values
11888 // that correspond to the original function's return values.
11889 std::optional<ISD::NodeType> AssertOp;
11890 if (CLI.RetSExt)
11891 AssertOp = ISD::AssertSext;
11892 else if (CLI.RetZExt)
11893 AssertOp = ISD::AssertZext;
11894 unsigned CurReg = 0;
11895 for (EVT VT : RetVTs) {
11896 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11897 unsigned NumRegs =
11898 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11899
11900 ReturnValues.push_back(getCopyFromParts(
11901 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11902 CLI.Chain, CLI.CallConv, AssertOp));
11903 CurReg += NumRegs;
11904 }
11905
11906 // For a function returning void, there is no return value. We can't create
11907 // such a node, so we just return a null return value in that case. In
11908 // that case, nothing will actually look at the value.
11909 if (ReturnValues.empty())
11910 return std::make_pair(SDValue(), CLI.Chain);
11911 }
11912
11913 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11914 CLI.DAG.getVTList(RetVTs), ReturnValues);
11915 return std::make_pair(Res, CLI.Chain);
11916}
11917
11918/// Places new result values for the node in Results (their number
11919/// and types must exactly match those of the original return values of
11920/// the node), or leaves Results empty, which indicates that the node is not
11921/// to be custom lowered after all.
11924 SelectionDAG &DAG) const {
11925 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11926
11927 if (!Res.getNode())
11928 return;
11929
11930 // If the original node has one result, take the return value from
11931 // LowerOperation as is. It might not be result number 0.
11932 if (N->getNumValues() == 1) {
11933 Results.push_back(Res);
11934 return;
11935 }
11936
11937 // If the original node has multiple results, then the return node should
11938 // have the same number of results.
11939 assert((N->getNumValues() == Res->getNumValues()) &&
11940 "Lowering returned the wrong number of results!");
11941
11942 // Places new result values base on N result number.
11943 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11944 Results.push_back(Res.getValue(I));
11945}
11946
11948 llvm_unreachable("LowerOperation not implemented for this target!");
11949}
11950
11952 Register Reg,
11953 ISD::NodeType ExtendType) {
11955 assert((Op.getOpcode() != ISD::CopyFromReg ||
11956 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11957 "Copy from a reg to the same reg!");
11958 assert(!Reg.isPhysical() && "Is a physreg");
11959
11960 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11961 // If this is an InlineAsm we have to match the registers required, not the
11962 // notional registers required by the type.
11963
11964 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11965 std::nullopt); // This is not an ABI copy.
11966 SDValue Chain = DAG.getEntryNode();
11967
11968 if (ExtendType == ISD::ANY_EXTEND) {
11969 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11970 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11971 ExtendType = PreferredExtendIt->second;
11972 }
11973 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11974 PendingExports.push_back(Chain);
11975}
11976
11978
11979/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11980/// entry block, return true. This includes arguments used by switches, since
11981/// the switch may expand into multiple basic blocks.
11982static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11983 // With FastISel active, we may be splitting blocks, so force creation
11984 // of virtual registers for all non-dead arguments.
11985 if (FastISel)
11986 return A->use_empty();
11987
11988 const BasicBlock &Entry = A->getParent()->front();
11989 for (const User *U : A->users())
11990 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11991 return false; // Use not in entry block.
11992
11993 return true;
11994}
11995
11997 DenseMap<const Argument *,
11998 std::pair<const AllocaInst *, const StoreInst *>>;
11999
12000/// Scan the entry block of the function in FuncInfo for arguments that look
12001/// like copies into a local alloca. Record any copied arguments in
12002/// ArgCopyElisionCandidates.
12003static void
12005 FunctionLoweringInfo *FuncInfo,
12006 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
12007 // Record the state of every static alloca used in the entry block. Argument
12008 // allocas are all used in the entry block, so we need approximately as many
12009 // entries as we have arguments.
12010 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
12012 unsigned NumArgs = FuncInfo->Fn->arg_size();
12013 StaticAllocas.reserve(NumArgs * 2);
12014
12015 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
12016 if (!V)
12017 return nullptr;
12018 V = V->stripPointerCasts();
12019 const auto *AI = dyn_cast<AllocaInst>(V);
12020 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
12021 return nullptr;
12022 auto Iter = StaticAllocas.insert({AI, Unknown});
12023 return &Iter.first->second;
12024 };
12025
12026 // Look for stores of arguments to static allocas. Look through bitcasts and
12027 // GEPs to handle type coercions, as long as the alloca is fully initialized
12028 // by the store. Any non-store use of an alloca escapes it and any subsequent
12029 // unanalyzed store might write it.
12030 // FIXME: Handle structs initialized with multiple stores.
12031 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
12032 // Look for stores, and handle non-store uses conservatively.
12033 const auto *SI = dyn_cast<StoreInst>(&I);
12034 if (!SI) {
12035 // We will look through cast uses, so ignore them completely.
12036 if (I.isCast())
12037 continue;
12038 // Ignore debug info and pseudo op intrinsics, they don't escape or store
12039 // to allocas.
12040 if (I.isDebugOrPseudoInst())
12041 continue;
12042 // This is an unknown instruction. Assume it escapes or writes to all
12043 // static alloca operands.
12044 for (const Use &U : I.operands()) {
12045 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
12046 *Info = StaticAllocaInfo::Clobbered;
12047 }
12048 continue;
12049 }
12050
12051 // If the stored value is a static alloca, mark it as escaped.
12052 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
12053 *Info = StaticAllocaInfo::Clobbered;
12054
12055 // Check if the destination is a static alloca.
12056 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
12057 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
12058 if (!Info)
12059 continue;
12060 const AllocaInst *AI = cast<AllocaInst>(Dst);
12061
12062 // Skip allocas that have been initialized or clobbered.
12063 if (*Info != StaticAllocaInfo::Unknown)
12064 continue;
12065
12066 // Check if the stored value is an argument, and that this store fully
12067 // initializes the alloca.
12068 // If the argument type has padding bits we can't directly forward a pointer
12069 // as the upper bits may contain garbage.
12070 // Don't elide copies from the same argument twice.
12071 const Value *Val = SI->getValueOperand()->stripPointerCasts();
12072 const auto *Arg = dyn_cast<Argument>(Val);
12073 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
12074 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
12075 Arg->getType()->isEmptyTy() || !AllocaSize ||
12076 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
12077 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
12078 ArgCopyElisionCandidates.count(Arg)) {
12079 *Info = StaticAllocaInfo::Clobbered;
12080 continue;
12081 }
12082
12083 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
12084 << '\n');
12085
12086 // Mark this alloca and store for argument copy elision.
12087 *Info = StaticAllocaInfo::Elidable;
12088 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
12089
12090 // Stop scanning if we've seen all arguments. This will happen early in -O0
12091 // builds, which is useful, because -O0 builds have large entry blocks and
12092 // many allocas.
12093 if (ArgCopyElisionCandidates.size() == NumArgs)
12094 break;
12095 }
12096}
12097
12098/// Try to elide argument copies from memory into a local alloca. Succeeds if
12099/// ArgVal is a load from a suitable fixed stack object.
12102 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
12103 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
12104 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
12105 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
12106 // Check if this is a load from a fixed stack object.
12107 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
12108 if (!LNode)
12109 return;
12110 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
12111 if (!FINode)
12112 return;
12113
12114 // Check that the fixed stack object is the right size and alignment.
12115 // Look at the alignment that the user wrote on the alloca instead of looking
12116 // at the stack object.
12117 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
12118 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
12119 const AllocaInst *AI = ArgCopyIter->second.first;
12120 int FixedIndex = FINode->getIndex();
12121 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
12122 int OldIndex = AllocaIndex;
12123 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
12124 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
12125 LLVM_DEBUG(
12126 dbgs() << " argument copy elision failed due to bad fixed stack "
12127 "object size\n");
12128 return;
12129 }
12130 Align RequiredAlignment = AI->getAlign();
12131 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
12132 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
12133 "greater than stack argument alignment ("
12134 << DebugStr(RequiredAlignment) << " vs "
12135 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
12136 return;
12137 }
12138
12139 // Perform the elision. Delete the old stack object and replace its only use
12140 // in the variable info map. Mark the stack object as mutable and aliased.
12141 LLVM_DEBUG({
12142 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
12143 << " Replacing frame index " << OldIndex << " with " << FixedIndex
12144 << '\n';
12145 });
12146 MFI.RemoveStackObject(OldIndex);
12147 MFI.setIsImmutableObjectIndex(FixedIndex, false);
12148 MFI.setIsAliasedObjectIndex(FixedIndex, true);
12149 AllocaIndex = FixedIndex;
12150 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
12151 for (SDValue ArgVal : ArgVals)
12152 Chains.push_back(ArgVal.getValue(1));
12153
12154 // Avoid emitting code for the store implementing the copy.
12155 const StoreInst *SI = ArgCopyIter->second.second;
12156 ElidedArgCopyInstrs.insert(SI);
12157
12158 // Check for uses of the argument again so that we can avoid exporting ArgVal
12159 // if it is't used by anything other than the store.
12160 for (const Value *U : Arg.users()) {
12161 if (U != SI) {
12162 ArgHasUses = true;
12163 break;
12164 }
12165 }
12166}
12167
12168void SelectionDAGISel::LowerArguments(const Function &F) {
12169 SelectionDAG &DAG = SDB->DAG;
12170 SDLoc dl = SDB->getCurSDLoc();
12171 const DataLayout &DL = DAG.getDataLayout();
12173
12174 // In Naked functions we aren't going to save any registers.
12175 if (F.hasFnAttribute(Attribute::Naked))
12176 return;
12177
12178 if (!FuncInfo->CanLowerReturn) {
12179 // Put in an sret pointer parameter before all the other parameters.
12180 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12181
12182 ISD::ArgFlagsTy Flags;
12183 Flags.setSRet();
12184 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
12185 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12187 Ins.push_back(RetArg);
12188 }
12189
12190 // Look for stores of arguments to static allocas. Mark such arguments with a
12191 // flag to ask the target to give us the memory location of that argument if
12192 // available.
12193 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12195 ArgCopyElisionCandidates);
12196
12197 // Set up the incoming argument description vector.
12198 for (const Argument &Arg : F.args()) {
12199 unsigned ArgNo = Arg.getArgNo();
12201 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12202 bool isArgValueUsed = !Arg.use_empty();
12203 Type *FinalType = Arg.getType();
12204 if (Arg.hasAttribute(Attribute::ByVal))
12205 FinalType = Arg.getParamByValType();
12206 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12207 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12208 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12209 ++Value) {
12210 Type *ArgTy = Types[Value];
12211 EVT VT = TLI->getValueType(DL, ArgTy);
12212 ISD::ArgFlagsTy Flags;
12213
12214 if (ArgTy->isPointerTy()) {
12215 Flags.setPointer();
12216 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12217 }
12218 if (Arg.hasAttribute(Attribute::ZExt))
12219 Flags.setZExt();
12220 if (Arg.hasAttribute(Attribute::SExt))
12221 Flags.setSExt();
12222 if (Arg.hasAttribute(Attribute::InReg)) {
12223 // If we are using vectorcall calling convention, a structure that is
12224 // passed InReg - is surely an HVA
12225 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12226 isa<StructType>(Arg.getType())) {
12227 // The first value of a structure is marked
12228 if (0 == Value)
12229 Flags.setHvaStart();
12230 Flags.setHva();
12231 }
12232 // Set InReg Flag
12233 Flags.setInReg();
12234 }
12235 if (Arg.hasAttribute(Attribute::StructRet))
12236 Flags.setSRet();
12237 if (Arg.hasAttribute(Attribute::SwiftSelf))
12238 Flags.setSwiftSelf();
12239 if (Arg.hasAttribute(Attribute::SwiftAsync))
12240 Flags.setSwiftAsync();
12241 if (Arg.hasAttribute(Attribute::SwiftError))
12242 Flags.setSwiftError();
12243 if (Arg.hasAttribute(Attribute::ByVal))
12244 Flags.setByVal();
12245 if (Arg.hasAttribute(Attribute::ByRef))
12246 Flags.setByRef();
12247 if (Arg.hasAttribute(Attribute::InAlloca)) {
12248 Flags.setInAlloca();
12249 // Set the byval flag for CCAssignFn callbacks that don't know about
12250 // inalloca. This way we can know how many bytes we should've allocated
12251 // and how many bytes a callee cleanup function will pop. If we port
12252 // inalloca to more targets, we'll have to add custom inalloca handling
12253 // in the various CC lowering callbacks.
12254 Flags.setByVal();
12255 }
12256 if (Arg.hasAttribute(Attribute::Preallocated)) {
12257 Flags.setPreallocated();
12258 // Set the byval flag for CCAssignFn callbacks that don't know about
12259 // preallocated. This way we can know how many bytes we should've
12260 // allocated and how many bytes a callee cleanup function will pop. If
12261 // we port preallocated to more targets, we'll have to add custom
12262 // preallocated handling in the various CC lowering callbacks.
12263 Flags.setByVal();
12264 }
12265
12266 // Certain targets (such as MIPS), may have a different ABI alignment
12267 // for a type depending on the context. Give the target a chance to
12268 // specify the alignment it wants.
12269 const Align OriginalAlignment(
12270 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12271 Flags.setOrigAlign(OriginalAlignment);
12272
12273 Align MemAlign;
12274 Type *ArgMemTy = nullptr;
12275 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12276 Flags.isByRef()) {
12277 if (!ArgMemTy)
12278 ArgMemTy = Arg.getPointeeInMemoryValueType();
12279
12280 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12281
12282 // For in-memory arguments, size and alignment should be passed from FE.
12283 // BE will guess if this info is not there but there are cases it cannot
12284 // get right.
12285 if (auto ParamAlign = Arg.getParamStackAlign())
12286 MemAlign = *ParamAlign;
12287 else if ((ParamAlign = Arg.getParamAlign()))
12288 MemAlign = *ParamAlign;
12289 else
12290 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12291 if (Flags.isByRef())
12292 Flags.setByRefSize(MemSize);
12293 else
12294 Flags.setByValSize(MemSize);
12295 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12296 MemAlign = *ParamAlign;
12297 } else {
12298 MemAlign = OriginalAlignment;
12299 }
12300 Flags.setMemAlign(MemAlign);
12301
12302 if (Arg.hasAttribute(Attribute::Nest))
12303 Flags.setNest();
12304 if (NeedsRegBlock)
12305 Flags.setInConsecutiveRegs();
12306 if (ArgCopyElisionCandidates.count(&Arg))
12307 Flags.setCopyElisionCandidate();
12308 if (Arg.hasAttribute(Attribute::Returned))
12309 Flags.setReturned();
12310
12311 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12312 *CurDAG->getContext(), F.getCallingConv(), VT);
12313 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12314 *CurDAG->getContext(), F.getCallingConv(), VT);
12315 for (unsigned i = 0; i != NumRegs; ++i) {
12316 // For scalable vectors, use the minimum size; individual targets
12317 // are responsible for handling scalable vector arguments and
12318 // return values.
12319 ISD::InputArg MyFlags(
12320 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12321 i * RegisterVT.getStoreSize().getKnownMinValue());
12322 if (NumRegs > 1 && i == 0)
12323 MyFlags.Flags.setSplit();
12324 // if it isn't first piece, alignment must be 1
12325 else if (i > 0) {
12326 MyFlags.Flags.setOrigAlign(Align(1));
12327 if (i == NumRegs - 1)
12328 MyFlags.Flags.setSplitEnd();
12329 }
12330 Ins.push_back(MyFlags);
12331 }
12332 if (NeedsRegBlock && Value == NumValues - 1)
12333 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12334 }
12335 }
12336
12337 // Call the target to set up the argument values.
12339 SDValue NewRoot = TLI->LowerFormalArguments(
12340 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12341
12342 // Verify that the target's LowerFormalArguments behaved as expected.
12343 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12344 "LowerFormalArguments didn't return a valid chain!");
12345 assert(InVals.size() == Ins.size() &&
12346 "LowerFormalArguments didn't emit the correct number of values!");
12347 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12348 "LowerFormalArguments emitted a null value!");
12349
12350 // Update the DAG with the new chain value resulting from argument lowering.
12351 DAG.setRoot(NewRoot);
12352
12353 // Set up the argument values.
12354 unsigned i = 0;
12355 if (!FuncInfo->CanLowerReturn) {
12356 // Create a virtual register for the sret pointer, and put in a copy
12357 // from the sret argument into it.
12358 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12359 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12360 std::optional<ISD::NodeType> AssertOp;
12361 SDValue ArgValue =
12362 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12363 F.getCallingConv(), AssertOp);
12364
12365 MachineFunction& MF = SDB->DAG.getMachineFunction();
12366 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12367 Register SRetReg =
12368 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12369 FuncInfo->DemoteRegister = SRetReg;
12370 NewRoot =
12371 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12372 DAG.setRoot(NewRoot);
12373
12374 // i indexes lowered arguments. Bump it past the hidden sret argument.
12375 ++i;
12376 }
12377
12379 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12380 for (const Argument &Arg : F.args()) {
12381 SmallVector<SDValue, 4> ArgValues;
12382 SmallVector<EVT, 4> ValueVTs;
12383 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12384 unsigned NumValues = ValueVTs.size();
12385 if (NumValues == 0)
12386 continue;
12387
12388 bool ArgHasUses = !Arg.use_empty();
12389
12390 // Elide the copying store if the target loaded this argument from a
12391 // suitable fixed stack object.
12392 if (Ins[i].Flags.isCopyElisionCandidate()) {
12393 unsigned NumParts = 0;
12394 for (EVT VT : ValueVTs)
12395 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12396 F.getCallingConv(), VT);
12397
12398 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12399 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12400 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12401 }
12402
12403 // If this argument is unused then remember its value. It is used to generate
12404 // debugging information.
12405 bool isSwiftErrorArg =
12406 TLI->supportSwiftError() &&
12407 Arg.hasAttribute(Attribute::SwiftError);
12408 if (!ArgHasUses && !isSwiftErrorArg) {
12409 SDB->setUnusedArgValue(&Arg, InVals[i]);
12410
12411 // Also remember any frame index for use in FastISel.
12412 if (FrameIndexSDNode *FI =
12414 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12415 }
12416
12417 for (unsigned Val = 0; Val != NumValues; ++Val) {
12418 EVT VT = ValueVTs[Val];
12419 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12420 F.getCallingConv(), VT);
12421 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12422 *CurDAG->getContext(), F.getCallingConv(), VT);
12423
12424 // Even an apparent 'unused' swifterror argument needs to be returned. So
12425 // we do generate a copy for it that can be used on return from the
12426 // function.
12427 if (ArgHasUses || isSwiftErrorArg) {
12428 std::optional<ISD::NodeType> AssertOp;
12429 if (Arg.hasAttribute(Attribute::SExt))
12430 AssertOp = ISD::AssertSext;
12431 else if (Arg.hasAttribute(Attribute::ZExt))
12432 AssertOp = ISD::AssertZext;
12433
12434 SDValue OutVal =
12435 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12436 NewRoot, F.getCallingConv(), AssertOp);
12437
12438 FPClassTest NoFPClass = Arg.getNoFPClass();
12439 if (NoFPClass != fcNone) {
12440 SDValue SDNoFPClass = DAG.getTargetConstant(
12441 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12442 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12443 OutVal, SDNoFPClass);
12444 }
12445 ArgValues.push_back(OutVal);
12446 }
12447
12448 i += NumParts;
12449 }
12450
12451 // We don't need to do anything else for unused arguments.
12452 if (ArgValues.empty())
12453 continue;
12454
12455 // Note down frame index.
12456 if (FrameIndexSDNode *FI =
12457 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12458 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12459
12460 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12461 SDB->getCurSDLoc());
12462
12463 SDB->setValue(&Arg, Res);
12464 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12465 // We want to associate the argument with the frame index, among
12466 // involved operands, that correspond to the lowest address. The
12467 // getCopyFromParts function, called earlier, is swapping the order of
12468 // the operands to BUILD_PAIR depending on endianness. The result of
12469 // that swapping is that the least significant bits of the argument will
12470 // be in the first operand of the BUILD_PAIR node, and the most
12471 // significant bits will be in the second operand.
12472 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12473 if (LoadSDNode *LNode =
12474 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12475 if (FrameIndexSDNode *FI =
12476 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12477 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12478 }
12479
12480 // Analyses past this point are naive and don't expect an assertion.
12481 if (Res.getOpcode() == ISD::AssertZext)
12482 Res = Res.getOperand(0);
12483
12484 // Update the SwiftErrorVRegDefMap.
12485 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12486 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12487 if (Reg.isVirtual())
12488 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12489 Reg);
12490 }
12491
12492 // If this argument is live outside of the entry block, insert a copy from
12493 // wherever we got it to the vreg that other BB's will reference it as.
12494 if (Res.getOpcode() == ISD::CopyFromReg) {
12495 // If we can, though, try to skip creating an unnecessary vreg.
12496 // FIXME: This isn't very clean... it would be nice to make this more
12497 // general.
12498 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12499 if (Reg.isVirtual()) {
12500 FuncInfo->ValueMap[&Arg] = Reg;
12501 continue;
12502 }
12503 }
12504 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
12505 FuncInfo->InitializeRegForValue(&Arg);
12506 SDB->CopyToExportRegsIfNeeded(&Arg);
12507 }
12508 }
12509
12510 if (!Chains.empty()) {
12511 Chains.push_back(NewRoot);
12512 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12513 }
12514
12515 DAG.setRoot(NewRoot);
12516
12517 assert(i == InVals.size() && "Argument register count mismatch!");
12518
12519 // If any argument copy elisions occurred and we have debug info, update the
12520 // stale frame indices used in the dbg.declare variable info table.
12521 if (!ArgCopyElisionFrameIndexMap.empty()) {
12522 for (MachineFunction::VariableDbgInfo &VI :
12523 MF->getInStackSlotVariableDbgInfo()) {
12524 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12525 if (I != ArgCopyElisionFrameIndexMap.end())
12526 VI.updateStackSlot(I->second);
12527 }
12528 }
12529
12530 // Finally, if the target has anything special to do, allow it to do so.
12532}
12533
12534/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12535/// ensure constants are generated when needed. Remember the virtual registers
12536/// that need to be added to the Machine PHI nodes as input. We cannot just
12537/// directly add them, because expansion might result in multiple MBB's for one
12538/// BB. As such, the start of the BB might correspond to a different MBB than
12539/// the end.
12540void
12541SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12542 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12543
12544 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12545
12546 // Check PHI nodes in successors that expect a value to be available from this
12547 // block.
12548 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12549 if (!isa<PHINode>(SuccBB->begin())) continue;
12550 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12551
12552 // If this terminator has multiple identical successors (common for
12553 // switches), only handle each succ once.
12554 if (!SuccsHandled.insert(SuccMBB).second)
12555 continue;
12556
12558
12559 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12560 // nodes and Machine PHI nodes, but the incoming operands have not been
12561 // emitted yet.
12562 for (const PHINode &PN : SuccBB->phis()) {
12563 // Ignore dead phi's.
12564 if (PN.use_empty())
12565 continue;
12566
12567 // Skip empty types
12568 if (PN.getType()->isEmptyTy())
12569 continue;
12570
12571 Register Reg;
12572 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12573
12574 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12575 Register &RegOut = ConstantsOut[C];
12576 if (!RegOut) {
12577 RegOut = FuncInfo.CreateRegs(PHIOp);
12578 // We need to zero/sign extend ConstantInt phi operands to match
12579 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12580 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12581 if (auto *CI = dyn_cast<ConstantInt>(C))
12582 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12584 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12585 }
12586 Reg = RegOut;
12587 } else {
12588 auto I = FuncInfo.ValueMap.find(PHIOp);
12589 if (I != FuncInfo.ValueMap.end())
12590 Reg = I->second;
12591 else {
12592 assert(isa<AllocaInst>(PHIOp) &&
12593 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12594 "Didn't codegen value into a register!??");
12595 Reg = FuncInfo.CreateRegs(PHIOp);
12597 }
12598 }
12599
12600 // Remember that this register needs to added to the machine PHI node as
12601 // the input for this MBB.
12602 SmallVector<EVT, 4> ValueVTs;
12603 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12604 for (EVT VT : ValueVTs) {
12605 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12606 for (unsigned i = 0; i != NumRegisters; ++i)
12607 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12608 Reg += NumRegisters;
12609 }
12610 }
12611 }
12612
12613 ConstantsOut.clear();
12614}
12615
12616MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12618 if (++I == FuncInfo.MF->end())
12619 return nullptr;
12620 return &*I;
12621}
12622
12623/// During lowering new call nodes can be created (such as memset, etc.).
12624/// Those will become new roots of the current DAG, but complications arise
12625/// when they are tail calls. In such cases, the call lowering will update
12626/// the root, but the builder still needs to know that a tail call has been
12627/// lowered in order to avoid generating an additional return.
12628void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12629 // If the node is null, we do have a tail call.
12630 if (MaybeTC.getNode() != nullptr)
12631 DAG.setRoot(MaybeTC);
12632 else
12633 HasTailCall = true;
12634}
12635
12636void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12637 MachineBasicBlock *SwitchMBB,
12638 MachineBasicBlock *DefaultMBB) {
12639 MachineFunction *CurMF = FuncInfo.MF;
12640 MachineBasicBlock *NextMBB = nullptr;
12642 if (++BBI != FuncInfo.MF->end())
12643 NextMBB = &*BBI;
12644
12645 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12646
12647 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12648
12649 if (Size == 2 && W.MBB == SwitchMBB) {
12650 // If any two of the cases has the same destination, and if one value
12651 // is the same as the other, but has one bit unset that the other has set,
12652 // use bit manipulation to do two compares at once. For example:
12653 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12654 // TODO: This could be extended to merge any 2 cases in switches with 3
12655 // cases.
12656 // TODO: Handle cases where W.CaseBB != SwitchBB.
12657 CaseCluster &Small = *W.FirstCluster;
12658 CaseCluster &Big = *W.LastCluster;
12659
12660 if (Small.Low == Small.High && Big.Low == Big.High &&
12661 Small.MBB == Big.MBB) {
12662 const APInt &SmallValue = Small.Low->getValue();
12663 const APInt &BigValue = Big.Low->getValue();
12664
12665 // Check that there is only one bit different.
12666 APInt CommonBit = BigValue ^ SmallValue;
12667 if (CommonBit.isPowerOf2()) {
12668 SDValue CondLHS = getValue(Cond);
12669 EVT VT = CondLHS.getValueType();
12670 SDLoc DL = getCurSDLoc();
12671
12672 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12673 DAG.getConstant(CommonBit, DL, VT));
12674 SDValue Cond = DAG.getSetCC(
12675 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12676 ISD::SETEQ);
12677
12678 // Update successor info.
12679 // Both Small and Big will jump to Small.BB, so we sum up the
12680 // probabilities.
12681 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12682 if (BPI)
12683 addSuccessorWithProb(
12684 SwitchMBB, DefaultMBB,
12685 // The default destination is the first successor in IR.
12686 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12687 else
12688 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12689
12690 // Insert the true branch.
12691 SDValue BrCond =
12692 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12693 DAG.getBasicBlock(Small.MBB));
12694 // Insert the false branch.
12695 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12696 DAG.getBasicBlock(DefaultMBB));
12697
12698 DAG.setRoot(BrCond);
12699 return;
12700 }
12701 }
12702 }
12703
12704 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12705 // Here, we order cases by probability so the most likely case will be
12706 // checked first. However, two clusters can have the same probability in
12707 // which case their relative ordering is non-deterministic. So we use Low
12708 // as a tie-breaker as clusters are guaranteed to never overlap.
12709 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12710 [](const CaseCluster &a, const CaseCluster &b) {
12711 return a.Prob != b.Prob ?
12712 a.Prob > b.Prob :
12713 a.Low->getValue().slt(b.Low->getValue());
12714 });
12715
12716 // Rearrange the case blocks so that the last one falls through if possible
12717 // without changing the order of probabilities.
12718 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12719 --I;
12720 if (I->Prob > W.LastCluster->Prob)
12721 break;
12722 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12723 std::swap(*I, *W.LastCluster);
12724 break;
12725 }
12726 }
12727 }
12728
12729 // Compute total probability.
12730 BranchProbability DefaultProb = W.DefaultProb;
12731 BranchProbability UnhandledProbs = DefaultProb;
12732 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12733 UnhandledProbs += I->Prob;
12734
12735 MachineBasicBlock *CurMBB = W.MBB;
12736 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12737 bool FallthroughUnreachable = false;
12738 MachineBasicBlock *Fallthrough;
12739 if (I == W.LastCluster) {
12740 // For the last cluster, fall through to the default destination.
12741 Fallthrough = DefaultMBB;
12742 FallthroughUnreachable = isa<UnreachableInst>(
12743 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12744 } else {
12745 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12746 CurMF->insert(BBI, Fallthrough);
12747 // Put Cond in a virtual register to make it available from the new blocks.
12749 }
12750 UnhandledProbs -= I->Prob;
12751
12752 switch (I->Kind) {
12753 case CC_JumpTable: {
12754 // FIXME: Optimize away range check based on pivot comparisons.
12755 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12756 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12757
12758 // The jump block hasn't been inserted yet; insert it here.
12759 MachineBasicBlock *JumpMBB = JT->MBB;
12760 CurMF->insert(BBI, JumpMBB);
12761
12762 auto JumpProb = I->Prob;
12763 auto FallthroughProb = UnhandledProbs;
12764
12765 // If the default statement is a target of the jump table, we evenly
12766 // distribute the default probability to successors of CurMBB. Also
12767 // update the probability on the edge from JumpMBB to Fallthrough.
12768 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12769 SE = JumpMBB->succ_end();
12770 SI != SE; ++SI) {
12771 if (*SI == DefaultMBB) {
12772 JumpProb += DefaultProb / 2;
12773 FallthroughProb -= DefaultProb / 2;
12774 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12775 JumpMBB->normalizeSuccProbs();
12776 break;
12777 }
12778 }
12779
12780 // If the default clause is unreachable, propagate that knowledge into
12781 // JTH->FallthroughUnreachable which will use it to suppress the range
12782 // check.
12783 //
12784 // However, don't do this if we're doing branch target enforcement,
12785 // because a table branch _without_ a range check can be a tempting JOP
12786 // gadget - out-of-bounds inputs that are impossible in correct
12787 // execution become possible again if an attacker can influence the
12788 // control flow. So if an attacker doesn't already have a BTI bypass
12789 // available, we don't want them to be able to get one out of this
12790 // table branch.
12791 if (FallthroughUnreachable) {
12792 Function &CurFunc = CurMF->getFunction();
12793 if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12794 JTH->FallthroughUnreachable = true;
12795 }
12796
12797 if (!JTH->FallthroughUnreachable)
12798 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12799 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12800 CurMBB->normalizeSuccProbs();
12801
12802 // The jump table header will be inserted in our current block, do the
12803 // range check, and fall through to our fallthrough block.
12804 JTH->HeaderBB = CurMBB;
12805 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12806
12807 // If we're in the right place, emit the jump table header right now.
12808 if (CurMBB == SwitchMBB) {
12809 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12810 JTH->Emitted = true;
12811 }
12812 break;
12813 }
12814 case CC_BitTests: {
12815 // FIXME: Optimize away range check based on pivot comparisons.
12816 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12817
12818 // The bit test blocks haven't been inserted yet; insert them here.
12819 for (BitTestCase &BTC : BTB->Cases)
12820 CurMF->insert(BBI, BTC.ThisBB);
12821
12822 // Fill in fields of the BitTestBlock.
12823 BTB->Parent = CurMBB;
12824 BTB->Default = Fallthrough;
12825
12826 BTB->DefaultProb = UnhandledProbs;
12827 // If the cases in bit test don't form a contiguous range, we evenly
12828 // distribute the probability on the edge to Fallthrough to two
12829 // successors of CurMBB.
12830 if (!BTB->ContiguousRange) {
12831 BTB->Prob += DefaultProb / 2;
12832 BTB->DefaultProb -= DefaultProb / 2;
12833 }
12834
12835 if (FallthroughUnreachable)
12836 BTB->FallthroughUnreachable = true;
12837
12838 // If we're in the right place, emit the bit test header right now.
12839 if (CurMBB == SwitchMBB) {
12840 visitBitTestHeader(*BTB, SwitchMBB);
12841 BTB->Emitted = true;
12842 }
12843 break;
12844 }
12845 case CC_Range: {
12846 const Value *RHS, *LHS, *MHS;
12847 ISD::CondCode CC;
12848 if (I->Low == I->High) {
12849 // Check Cond == I->Low.
12850 CC = ISD::SETEQ;
12851 LHS = Cond;
12852 RHS=I->Low;
12853 MHS = nullptr;
12854 } else {
12855 // Check I->Low <= Cond <= I->High.
12856 CC = ISD::SETLE;
12857 LHS = I->Low;
12858 MHS = Cond;
12859 RHS = I->High;
12860 }
12861
12862 // If Fallthrough is unreachable, fold away the comparison.
12863 if (FallthroughUnreachable)
12864 CC = ISD::SETTRUE;
12865
12866 // The false probability is the sum of all unhandled cases.
12867 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12868 getCurSDLoc(), I->Prob, UnhandledProbs);
12869
12870 if (CurMBB == SwitchMBB)
12871 visitSwitchCase(CB, SwitchMBB);
12872 else
12873 SL->SwitchCases.push_back(CB);
12874
12875 break;
12876 }
12877 }
12878 CurMBB = Fallthrough;
12879 }
12880}
12881
12882void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12883 const SwitchWorkListItem &W,
12884 Value *Cond,
12885 MachineBasicBlock *SwitchMBB) {
12886 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12887 "Clusters not sorted?");
12888 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12889
12890 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12891 SL->computeSplitWorkItemInfo(W);
12892
12893 // Use the first element on the right as pivot since we will make less-than
12894 // comparisons against it.
12895 CaseClusterIt PivotCluster = FirstRight;
12896 assert(PivotCluster > W.FirstCluster);
12897 assert(PivotCluster <= W.LastCluster);
12898
12899 CaseClusterIt FirstLeft = W.FirstCluster;
12900 CaseClusterIt LastRight = W.LastCluster;
12901
12902 const ConstantInt *Pivot = PivotCluster->Low;
12903
12904 // New blocks will be inserted immediately after the current one.
12906 ++BBI;
12907
12908 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12909 // we can branch to its destination directly if it's squeezed exactly in
12910 // between the known lower bound and Pivot - 1.
12911 MachineBasicBlock *LeftMBB;
12912 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12913 FirstLeft->Low == W.GE &&
12914 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12915 LeftMBB = FirstLeft->MBB;
12916 } else {
12917 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12918 FuncInfo.MF->insert(BBI, LeftMBB);
12919 WorkList.push_back(
12920 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12921 // Put Cond in a virtual register to make it available from the new blocks.
12923 }
12924
12925 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12926 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12927 // directly if RHS.High equals the current upper bound.
12928 MachineBasicBlock *RightMBB;
12929 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12930 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12931 RightMBB = FirstRight->MBB;
12932 } else {
12933 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12934 FuncInfo.MF->insert(BBI, RightMBB);
12935 WorkList.push_back(
12936 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12937 // Put Cond in a virtual register to make it available from the new blocks.
12939 }
12940
12941 // Create the CaseBlock record that will be used to lower the branch.
12942 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12943 getCurSDLoc(), LeftProb, RightProb);
12944
12945 if (W.MBB == SwitchMBB)
12946 visitSwitchCase(CB, SwitchMBB);
12947 else
12948 SL->SwitchCases.push_back(CB);
12949}
12950
12951// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12952// from the swith statement.
12954 BranchProbability PeeledCaseProb) {
12955 if (PeeledCaseProb == BranchProbability::getOne())
12957 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12958
12959 uint32_t Numerator = CaseProb.getNumerator();
12960 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12961 return BranchProbability(Numerator, std::max(Numerator, Denominator));
12962}
12963
12964// Try to peel the top probability case if it exceeds the threshold.
12965// Return current MachineBasicBlock for the switch statement if the peeling
12966// does not occur.
12967// If the peeling is performed, return the newly created MachineBasicBlock
12968// for the peeled switch statement. Also update Clusters to remove the peeled
12969// case. PeeledCaseProb is the BranchProbability for the peeled case.
12970MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12971 const SwitchInst &SI, CaseClusterVector &Clusters,
12972 BranchProbability &PeeledCaseProb) {
12973 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12974 // Don't perform if there is only one cluster or optimizing for size.
12975 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12976 TM.getOptLevel() == CodeGenOptLevel::None ||
12977 SwitchMBB->getParent()->getFunction().hasMinSize())
12978 return SwitchMBB;
12979
12980 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12981 unsigned PeeledCaseIndex = 0;
12982 bool SwitchPeeled = false;
12983 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12984 CaseCluster &CC = Clusters[Index];
12985 if (CC.Prob < TopCaseProb)
12986 continue;
12987 TopCaseProb = CC.Prob;
12988 PeeledCaseIndex = Index;
12989 SwitchPeeled = true;
12990 }
12991 if (!SwitchPeeled)
12992 return SwitchMBB;
12993
12994 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12995 << TopCaseProb << "\n");
12996
12997 // Record the MBB for the peeled switch statement.
12998 MachineFunction::iterator BBI(SwitchMBB);
12999 ++BBI;
13000 MachineBasicBlock *PeeledSwitchMBB =
13001 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
13002 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
13003
13004 ExportFromCurrentBlock(SI.getCondition());
13005 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
13006 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
13007 nullptr, nullptr, TopCaseProb.getCompl()};
13008 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
13009
13010 Clusters.erase(PeeledCaseIt);
13011 for (CaseCluster &CC : Clusters) {
13012 LLVM_DEBUG(
13013 dbgs() << "Scale the probablity for one cluster, before scaling: "
13014 << CC.Prob << "\n");
13015 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
13016 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
13017 }
13018 PeeledCaseProb = TopCaseProb;
13019 return PeeledSwitchMBB;
13020}
13021
13022void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
13023 // Extract cases from the switch.
13024 BranchProbabilityInfo *BPI = FuncInfo.BPI;
13025 CaseClusterVector Clusters;
13026 Clusters.reserve(SI.getNumCases());
13027 for (auto I : SI.cases()) {
13028 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
13029 const ConstantInt *CaseVal = I.getCaseValue();
13030 BranchProbability Prob =
13031 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
13032 : BranchProbability(1, SI.getNumCases() + 1);
13033 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
13034 }
13035
13036 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
13037
13038 // Cluster adjacent cases with the same destination. We do this at all
13039 // optimization levels because it's cheap to do and will make codegen faster
13040 // if there are many clusters.
13041 sortAndRangeify(Clusters);
13042
13043 // The branch probablity of the peeled case.
13044 BranchProbability PeeledCaseProb = BranchProbability::getZero();
13045 MachineBasicBlock *PeeledSwitchMBB =
13046 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
13047
13048 // If there is only the default destination, jump there directly.
13049 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13050 if (Clusters.empty()) {
13051 assert(PeeledSwitchMBB == SwitchMBB);
13052 SwitchMBB->addSuccessor(DefaultMBB);
13053 if (DefaultMBB != NextBlock(SwitchMBB)) {
13054 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
13055 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
13056 }
13057 return;
13058 }
13059
13060 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
13061 DAG.getBFI());
13062 SL->findBitTestClusters(Clusters, &SI);
13063
13064 LLVM_DEBUG({
13065 dbgs() << "Case clusters: ";
13066 for (const CaseCluster &C : Clusters) {
13067 if (C.Kind == CC_JumpTable)
13068 dbgs() << "JT:";
13069 if (C.Kind == CC_BitTests)
13070 dbgs() << "BT:";
13071
13072 C.Low->getValue().print(dbgs(), true);
13073 if (C.Low != C.High) {
13074 dbgs() << '-';
13075 C.High->getValue().print(dbgs(), true);
13076 }
13077 dbgs() << ' ';
13078 }
13079 dbgs() << '\n';
13080 });
13081
13082 assert(!Clusters.empty());
13083 SwitchWorkList WorkList;
13084 CaseClusterIt First = Clusters.begin();
13085 CaseClusterIt Last = Clusters.end() - 1;
13086 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
13087 // Scale the branchprobability for DefaultMBB if the peel occurs and
13088 // DefaultMBB is not replaced.
13089 if (PeeledCaseProb != BranchProbability::getZero() &&
13090 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
13091 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
13092 WorkList.push_back(
13093 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
13094
13095 while (!WorkList.empty()) {
13096 SwitchWorkListItem W = WorkList.pop_back_val();
13097 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
13098
13099 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
13100 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
13101 // For optimized builds, lower large range as a balanced binary tree.
13102 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
13103 continue;
13104 }
13105
13106 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
13107 }
13108}
13109
13110void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
13111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13112 auto DL = getCurSDLoc();
13113 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13114 setValue(&I, DAG.getStepVector(DL, ResultVT));
13115}
13116
13117void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
13118 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13119 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13120
13121 SDLoc DL = getCurSDLoc();
13122 SDValue V = getValue(I.getOperand(0));
13123 assert(VT == V.getValueType() && "Malformed vector.reverse!");
13124
13125 if (VT.isScalableVector()) {
13126 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
13127 return;
13128 }
13129
13130 // Use VECTOR_SHUFFLE for the fixed-length vector
13131 // to maintain existing behavior.
13132 SmallVector<int, 8> Mask;
13133 unsigned NumElts = VT.getVectorMinNumElements();
13134 for (unsigned i = 0; i != NumElts; ++i)
13135 Mask.push_back(NumElts - 1 - i);
13136
13137 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
13138}
13139
13140void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
13141 unsigned Factor) {
13142 auto DL = getCurSDLoc();
13143 SDValue InVec = getValue(I.getOperand(0));
13144
13145 SmallVector<EVT, 4> ValueVTs;
13146 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13147 ValueVTs);
13148
13149 EVT OutVT = ValueVTs[0];
13150 unsigned OutNumElts = OutVT.getVectorMinNumElements();
13151
13152 SmallVector<SDValue, 4> SubVecs(Factor);
13153 for (unsigned i = 0; i != Factor; ++i) {
13154 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13155 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
13156 DAG.getVectorIdxConstant(OutNumElts * i, DL));
13157 }
13158
13159 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
13160 // from existing legalisation and combines.
13161 if (OutVT.isFixedLengthVector() && Factor == 2) {
13162 SDValue Even = DAG.getVectorShuffle(OutVT, DL, SubVecs[0], SubVecs[1],
13163 createStrideMask(0, 2, OutNumElts));
13164 SDValue Odd = DAG.getVectorShuffle(OutVT, DL, SubVecs[0], SubVecs[1],
13165 createStrideMask(1, 2, OutNumElts));
13166 SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
13167 setValue(&I, Res);
13168 return;
13169 }
13170
13171 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
13172 DAG.getVTList(ValueVTs), SubVecs);
13173 setValue(&I, Res);
13174}
13175
13176void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13177 unsigned Factor) {
13178 auto DL = getCurSDLoc();
13179 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13180 EVT InVT = getValue(I.getOperand(0)).getValueType();
13181 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13182
13183 SmallVector<SDValue, 8> InVecs(Factor);
13184 for (unsigned i = 0; i < Factor; ++i) {
13185 InVecs[i] = getValue(I.getOperand(i));
13186 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13187 "Expected VTs to be the same");
13188 }
13189
13190 // Use VECTOR_SHUFFLE for fixed-length vectors with factor of 2 to benefit
13191 // from existing legalisation and combines.
13192 if (OutVT.isFixedLengthVector() && Factor == 2) {
13193 unsigned NumElts = InVT.getVectorMinNumElements();
13194 SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVecs);
13195 setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
13196 createInterleaveMask(NumElts, 2)));
13197 return;
13198 }
13199
13200 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13201 SDValue Res =
13202 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13203
13205 for (unsigned i = 0; i < Factor; ++i)
13206 Results[i] = Res.getValue(i);
13207
13208 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13209 setValue(&I, Res);
13210}
13211
13212void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13213 SmallVector<EVT, 4> ValueVTs;
13214 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13215 ValueVTs);
13216 unsigned NumValues = ValueVTs.size();
13217 if (NumValues == 0) return;
13218
13220 SDValue Op = getValue(I.getOperand(0));
13221
13222 for (unsigned i = 0; i != NumValues; ++i)
13223 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13224 SDValue(Op.getNode(), Op.getResNo() + i));
13225
13227 DAG.getVTList(ValueVTs), Values));
13228}
13229
13230void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13231 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13232 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13233
13234 SDLoc DL = getCurSDLoc();
13235 SDValue V1 = getValue(I.getOperand(0));
13236 SDValue V2 = getValue(I.getOperand(1));
13237 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13238
13239 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13240 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13241 SDValue Offset = DAG.getZExtOrTrunc(
13242 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13243 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13245 DL, VT, V1, V2, Offset));
13246 return;
13247 }
13248 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13249
13250 unsigned NumElts = VT.getVectorNumElements();
13251
13252 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13253
13254 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13255 SmallVector<int, 8> Mask;
13256 for (unsigned i = 0; i < NumElts; ++i)
13257 Mask.push_back(Idx + i);
13258 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13259}
13260
13261// Consider the following MIR after SelectionDAG, which produces output in
13262// phyregs in the first case or virtregs in the second case.
13263//
13264// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13265// %5:gr32 = COPY $ebx
13266// %6:gr32 = COPY $edx
13267// %1:gr32 = COPY %6:gr32
13268// %0:gr32 = COPY %5:gr32
13269//
13270// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13271// %1:gr32 = COPY %6:gr32
13272// %0:gr32 = COPY %5:gr32
13273//
13274// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13275// Given %1, we'd like to return $edx in the first case and %6 in the second.
13276//
13277// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13278// to a single virtreg (such as %0). The remaining outputs monotonically
13279// increase in virtreg number from there. If a callbr has no outputs, then it
13280// should not have a corresponding callbr landingpad; in fact, the callbr
13281// landingpad would not even be able to refer to such a callbr.
13284 // There is definitely at least one copy.
13285 assert(MI->getOpcode() == TargetOpcode::COPY &&
13286 "start of copy chain MUST be COPY");
13287 Reg = MI->getOperand(1).getReg();
13288
13289 // If the copied register in the first copy must be virtual.
13290 assert(Reg.isVirtual() && "expected COPY of virtual register");
13291 MI = MRI.def_begin(Reg)->getParent();
13292
13293 // There may be an optional second copy.
13294 if (MI->getOpcode() == TargetOpcode::COPY) {
13295 assert(Reg.isVirtual() && "expected COPY of virtual register");
13296 Reg = MI->getOperand(1).getReg();
13297 assert(Reg.isPhysical() && "expected COPY of physical register");
13298 } else {
13299 // The start of the chain must be an INLINEASM_BR.
13300 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13301 "end of copy chain MUST be INLINEASM_BR");
13302 }
13303
13304 return Reg;
13305}
13306
13307// We must do this walk rather than the simpler
13308// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13309// otherwise we will end up with copies of virtregs only valid along direct
13310// edges.
13311void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13312 SmallVector<EVT, 8> ResultVTs;
13313 SmallVector<SDValue, 8> ResultValues;
13314 const auto *CBR =
13315 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13316
13317 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13318 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13319 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13320
13321 Register InitialDef = FuncInfo.ValueMap[CBR];
13322 SDValue Chain = DAG.getRoot();
13323
13324 // Re-parse the asm constraints string.
13325 TargetLowering::AsmOperandInfoVector TargetConstraints =
13326 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
13327 for (auto &T : TargetConstraints) {
13328 SDISelAsmOperandInfo OpInfo(T);
13329 if (OpInfo.Type != InlineAsm::isOutput)
13330 continue;
13331
13332 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13333 // individual constraint.
13334 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
13335
13336 switch (OpInfo.ConstraintType) {
13339 // Fill in OpInfo.AssignedRegs.Regs.
13340 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
13341
13342 // getRegistersForValue may produce 1 to many registers based on whether
13343 // the OpInfo.ConstraintVT is legal on the target or not.
13344 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13345 Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
13346 if (OriginalDef.isPhysical())
13347 FuncInfo.MBB->addLiveIn(OriginalDef);
13348 // Update the assigned registers to use the original defs.
13349 Reg = OriginalDef;
13350 }
13351
13352 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13353 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
13354 ResultValues.push_back(V);
13355 ResultVTs.push_back(OpInfo.ConstraintVT);
13356 break;
13357 }
13359 SDValue Flag;
13360 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
13361 OpInfo, DAG);
13362 ++InitialDef;
13363 ResultValues.push_back(V);
13364 ResultVTs.push_back(OpInfo.ConstraintVT);
13365 break;
13366 }
13367 default:
13368 break;
13369 }
13370 }
13371 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
13372 DAG.getVTList(ResultVTs), ResultValues);
13373 setValue(&I, V);
13374}
static unsigned getIntrinsicID(const SDNode *N)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
unsigned Imm
unsigned uint64_t
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:857
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)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
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 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.
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 const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:185
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:6155
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:336
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:410
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.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
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:43
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:732
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:782
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:695
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:737
iterator end()
Definition DenseMap.h:702
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:843
Diagnostic information for inline asm reporting.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:311
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
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:794
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:696
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
Definition Function.cpp:742
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:886
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
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:68
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() const
Returns true if the exception tables reference the per-invoke EH labels emitted around invokes.
Definition MCAsmInfo.h:683
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
LLVM_ABI MCSymbol * getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen.
const MCAsmInfo & getAsmInfo() const
Definition MCContext.h:409
unsigned getID() const
getID() - Return the register class ID number.
const MCPhysReg * iterator
iterator begin() const
begin/end - Return all of the registers in this 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:615
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.
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.
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.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
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:118
bool contains(const KeyT &Key) const
Definition MapVector.h:148
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
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.
Function * getSSPStackGuardCheck(const Module &M, const LibcallLoweringInfo &Libcalls) const
If the target has a standard stack protection check function that performs validation and error handl...
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 isLegalScaleForGatherScatter(uint64_t Scale, uint64_t ElemSize) const
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
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 bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
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.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT, unsigned Scale) const
Some fixed point operations may be natively supported by the target but only for specific scales.
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.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
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 getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const
Return the ValueType of the result of SETCC operations.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool 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...
unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Vector types are broken down into some number of legal first class types.
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 supportKCFIBundles() const
Return true if the target supports kcfi operand bundles.
virtual bool supportPtrAuthBundles() const
Return true if the target supports ptrauth operand bundles.
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.
virtual InlineAsm::ConstraintCode getInlineAsmMemConstraint(StringRef ConstraintCode) const
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 ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const
Target-specific splitting of values into parts that fit a register storing a legal type.
virtual SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const
Target-specific combining of register parts into its original value.
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 std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
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 LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
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 isInlineAsmTargetBranch(const SmallVectorImpl< StringRef > &AsmStrs, unsigned OpNo) const
On x86, return true if the operand with index OpNo is a CALL or JUMP instruction, which can use eithe...
virtual MVT getJumpTableRegTy(const DataLayout &DL) const
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:339
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:712
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:319
Base class of all SIMD vector types.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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:41
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ 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:514
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:45
@ SET_FPENV
Sets the current floating-point environment.
@ ATOMIC_LOAD_FMINIMUMNUM
@ LOOP_DEPENDENCE_RAW_MASK
@ 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:168
@ VECREDUCE_FMINIMUMNUM
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:603
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:127
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:795
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:395
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ RESET_FPENV
Set floating-point environment to default state.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:401
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:869
@ 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:521
@ 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:220
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:172
@ GlobalAddress
Definition ISDOpcodes.h:88
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:896
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:587
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:418
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:755
@ 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:531
@ FPTRUNC_ROUND
FPTRUNC_ROUND - This corresponds to the fptrunc_round intrinsic.
Definition ISDOpcodes.h:518
@ 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:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:786
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:408
@ 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:804
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:156
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ SET_ROUNDING
Set rounding mode.
Definition ISDOpcodes.h:991
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:860
@ 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:117
@ 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:353
@ 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:638
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:544
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:551
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:375
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:812
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:680
@ 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:81
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:349
@ 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 ...
Definition ISDOpcodes.h:986
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:712
@ 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:777
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:78
@ PtrAuthGlobalAddress
A ptrauth constant.
Definition ISDOpcodes.h:100
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:617
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:48
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:139
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:579
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:866
@ 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:135
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ UBSANTRAP
UBSANTRAP - Trap with an immediate describing the kind of sanitizer failure.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:387
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:357
@ 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:661
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:735
@ 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:648
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:414
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:994
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:821
@ 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:150
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:791
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:503
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:942
@ 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:747
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:743
@ 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:665
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:428
@ 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:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:568
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:803
@ 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:975
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:707
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:122
@ CLEAR_CACHE
llvm.clear_cache intrinsic Operands: Input Chain, Start Addres, End Address Outputs: Output Chain
@ 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:961
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:162
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:872
@ 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:62
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:537
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:366
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:643
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:627
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:759
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:559
@ 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
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
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
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:541
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
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
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
@ 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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
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:144
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:2304
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.
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ 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:201
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
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
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:880
#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:77
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
uint64_t getScalarStoreSize() const
Definition ValueTypes.h:425
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
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:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isRISCVVectorTuple() const
Return true if this is a vector value type.
Definition ValueTypes.h:197
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
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:121
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
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:342
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)