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"
89#include "llvm/IR/Statepoint.h"
90#include "llvm/IR/Type.h"
91#include "llvm/IR/User.h"
92#include "llvm/IR/Value.h"
93#include "llvm/MC/MCAsmInfo.h"
94#include "llvm/MC/MCContext.h"
99#include "llvm/Support/Debug.h"
107#include <cstddef>
108#include <limits>
109#include <optional>
110#include <tuple>
111
112using namespace llvm;
113using namespace PatternMatch;
114using namespace SwitchCG;
115
116#define DEBUG_TYPE "isel"
117
118/// LimitFloatPrecision - Generate low-precision inline sequences for
119/// some float libcalls (6, 8 or 12 bits).
120static unsigned LimitFloatPrecision;
121
122static cl::opt<bool>
123 InsertAssertAlign("insert-assert-align", cl::init(true),
124 cl::desc("Insert the experimental `assertalign` node."),
126
128 LimitFPPrecision("limit-float-precision",
129 cl::desc("Generate low-precision inline sequences "
130 "for some float libcalls"),
132 cl::init(0));
133
135 "switch-peel-threshold", cl::Hidden, cl::init(66),
136 cl::desc("Set the case probability threshold for peeling the case from a "
137 "switch statement. A value greater than 100 will void this "
138 "optimization"));
139
140// Limit the width of DAG chains. This is important in general to prevent
141// DAG-based analysis from blowing up. For example, alias analysis and
142// load clustering may not complete in reasonable time. It is difficult to
143// recognize and avoid this situation within each individual analysis, and
144// future analyses are likely to have the same behavior. Limiting DAG width is
145// the safe approach and will be especially important with global DAGs.
146//
147// MaxParallelChains default is arbitrarily high to avoid affecting
148// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
149// sequence over this should have been converted to llvm.memcpy by the
150// frontend. It is easy to induce this behavior with .ll code such as:
151// %buffer = alloca [4096 x i8]
152// %data = load [4096 x i8]* %argPtr
153// store [4096 x i8] %data, [4096 x i8]* %buffer
154static const unsigned MaxParallelChains = 64;
155
157 const SDValue *Parts, unsigned NumParts,
158 MVT PartVT, EVT ValueVT, const Value *V,
159 SDValue InChain,
160 std::optional<CallingConv::ID> CC);
161
162/// getCopyFromParts - Create a value that contains the specified legal parts
163/// combined into the value they represent. If the parts combine to a type
164/// larger than ValueVT then AssertOp can be used to specify whether the extra
165/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
166/// (ISD::AssertSext).
167static SDValue
168getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
169 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
170 SDValue InChain,
171 std::optional<CallingConv::ID> CC = std::nullopt,
172 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
173 // Let the target assemble the parts if it wants to
174 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
175 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
176 PartVT, ValueVT, CC))
177 return Val;
178
179 if (ValueVT.isVector())
180 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
181 InChain, CC);
182
183 assert(NumParts > 0 && "No parts to assemble!");
184 SDValue Val = Parts[0];
185
186 if (NumParts > 1) {
187 // Assemble the value from multiple parts.
188 if (ValueVT.isInteger()) {
189 unsigned PartBits = PartVT.getSizeInBits();
190 unsigned ValueBits = ValueVT.getSizeInBits();
191
192 // Assemble the power of 2 part.
193 unsigned RoundParts = llvm::bit_floor(NumParts);
194 unsigned RoundBits = PartBits * RoundParts;
195 EVT RoundVT = RoundBits == ValueBits ?
196 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
197 SDValue Lo, Hi;
198
199 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
200
201 if (RoundParts > 2) {
202 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
203 InChain);
204 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
205 PartVT, HalfVT, V, InChain);
206 } else {
207 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
208 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
209 }
210
211 if (DAG.getDataLayout().isBigEndian())
212 std::swap(Lo, Hi);
213
214 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
215
216 if (RoundParts < NumParts) {
217 // Assemble the trailing non-power-of-2 part.
218 unsigned OddParts = NumParts - RoundParts;
219 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
220 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
221 OddVT, V, InChain, CC);
222
223 // Combine the round and odd parts.
224 Lo = Val;
225 if (DAG.getDataLayout().isBigEndian())
226 std::swap(Lo, Hi);
227 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
228 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
229 Hi = DAG.getNode(
230 ISD::SHL, DL, TotalVT, Hi,
231 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
232 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
233 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
234 }
235 } else if (PartVT.isFloatingPoint()) {
236 // FP split into multiple FP parts (for ppcf128)
237 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
238 "Unexpected split");
239 SDValue Lo, Hi;
240 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
241 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
242 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
243 std::swap(Lo, Hi);
244 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
245 } else {
246 // FP split into integer parts (soft fp)
247 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
248 !PartVT.isVector() && "Unexpected split");
249 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
250 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
251 InChain, CC);
252 }
253 }
254
255 // There is now one part, held in Val. Correct it to match ValueVT.
256 // PartEVT is the type of the register class that holds the value.
257 // ValueVT is the type of the inline asm operation.
258 EVT PartEVT = Val.getValueType();
259
260 if (PartEVT == ValueVT)
261 return Val;
262
263 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
264 ValueVT.bitsLT(PartEVT)) {
265 // For an FP value in an integer part, we need to truncate to the right
266 // width first.
267 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
268 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
269 }
270
271 // Handle types that have the same size.
272 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
273 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
274
275 // Handle types with different sizes.
276 if (PartEVT.isInteger() && ValueVT.isInteger()) {
277 if (ValueVT.bitsLT(PartEVT)) {
278 // For a truncate, see if we have any information to
279 // indicate whether the truncated bits will always be
280 // zero or sign-extension.
281 if (AssertOp)
282 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
283 DAG.getValueType(ValueVT));
284 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
285 }
286 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
287 }
288
289 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
290 // FP_ROUND's are always exact here.
291 if (ValueVT.bitsLT(Val.getValueType())) {
292
293 SDValue NoChange =
295
296 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
297 llvm::Attribute::StrictFP)) {
298 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
299 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
300 NoChange);
301 }
302
303 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
304 }
305
306 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
307 }
308
309 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
310 // then truncating.
311 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
312 ValueVT.bitsLT(PartEVT)) {
313 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
314 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
315 }
316
317 report_fatal_error("Unknown mismatch in getCopyFromParts!");
318}
319
321 const Twine &ErrMsg) {
323 if (!I)
324 return Ctx.emitError(ErrMsg);
325
326 if (const CallInst *CI = dyn_cast<CallInst>(I))
327 if (CI->isInlineAsm()) {
328 return Ctx.diagnose(DiagnosticInfoInlineAsm(
329 *CI, ErrMsg + ", possible invalid constraint for vector type"));
330 }
331
332 return Ctx.emitError(I, ErrMsg);
333}
334
335/// getCopyFromPartsVector - Create a value that contains the specified legal
336/// parts combined into the value they represent. If the parts combine to a
337/// type larger than ValueVT then AssertOp can be used to specify whether the
338/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339/// ValueVT (ISD::AssertSext).
341 const SDValue *Parts, unsigned NumParts,
342 MVT PartVT, EVT ValueVT, const Value *V,
343 SDValue InChain,
344 std::optional<CallingConv::ID> CallConv) {
345 assert(ValueVT.isVector() && "Not a vector value");
346 assert(NumParts > 0 && "No parts to assemble!");
347 const bool IsABIRegCopy = CallConv.has_value();
348
349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
350 SDValue Val = Parts[0];
351
352 // Handle a multi-element vector.
353 if (NumParts > 1) {
354 EVT IntermediateVT;
355 MVT RegisterVT;
356 unsigned NumIntermediates;
357 unsigned NumRegs;
358
359 if (IsABIRegCopy) {
361 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
362 NumIntermediates, RegisterVT);
363 } else {
364 NumRegs =
365 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
366 NumIntermediates, RegisterVT);
367 }
368
369 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
370 NumParts = NumRegs; // Silence a compiler warning.
371 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
372 assert(RegisterVT.getSizeInBits() ==
373 Parts[0].getSimpleValueType().getSizeInBits() &&
374 "Part type sizes don't match!");
375
376 // Assemble the parts into intermediate operands.
377 SmallVector<SDValue, 8> Ops(NumIntermediates);
378 if (NumIntermediates == NumParts) {
379 // If the register was not expanded, truncate or copy the value,
380 // as appropriate.
381 for (unsigned i = 0; i != NumParts; ++i)
382 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
383 V, InChain, CallConv);
384 } else if (NumParts > 0) {
385 // If the intermediate type was expanded, build the intermediate
386 // operands from the parts.
387 assert(NumParts % NumIntermediates == 0 &&
388 "Must expand into a divisible number of parts!");
389 unsigned Factor = NumParts / NumIntermediates;
390 for (unsigned i = 0; i != NumIntermediates; ++i)
391 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
392 IntermediateVT, V, InChain, CallConv);
393 }
394
395 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
396 // intermediate operands.
397 EVT BuiltVectorTy =
398 IntermediateVT.isVector()
400 *DAG.getContext(), IntermediateVT.getScalarType(),
401 IntermediateVT.getVectorElementCount() * NumParts)
403 IntermediateVT.getScalarType(),
404 NumIntermediates);
405 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407 DL, BuiltVectorTy, Ops);
408 }
409
410 // There is now one part, held in Val. Correct it to match ValueVT.
411 EVT PartEVT = Val.getValueType();
412
413 if (PartEVT == ValueVT)
414 return Val;
415
416 if (PartEVT.isVector()) {
417 // Vector/Vector bitcast.
418 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420
421 // If the parts vector has more elements than the value vector, then we
422 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
423 // Extract the elements we want.
424 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
427 (PartEVT.getVectorElementCount().isScalable() ==
428 ValueVT.getVectorElementCount().isScalable()) &&
429 "Cannot narrow, it would be a lossy transformation");
430 PartEVT =
432 ValueVT.getVectorElementCount());
433 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
434 DAG.getVectorIdxConstant(0, DL));
435 if (PartEVT == ValueVT)
436 return Val;
437 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
438 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439
440 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
443 }
444
445 // Promoted vector extract
446 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
447 }
448
449 // Trivial bitcast if the types are the same size and the destination
450 // vector type is legal.
451 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
452 TLI.isTypeLegal(ValueVT))
453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454
455 if (ValueVT.getVectorNumElements() != 1) {
456 // Certain ABIs require that vectors are passed as integers. For vectors
457 // are the same size, this is an obvious bitcast.
458 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
459 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
460 } else if (ValueVT.bitsLT(PartEVT)) {
461 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
462 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
463 // Drop the extra bits.
464 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
465 return DAG.getBitcast(ValueVT, Val);
466 }
467
469 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
470 return DAG.getUNDEF(ValueVT);
471 }
472
473 // Handle cases such as i8 -> <1 x i1>
474 EVT ValueSVT = ValueVT.getVectorElementType();
475 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
476 unsigned ValueSize = ValueSVT.getSizeInBits();
477 if (ValueSize == PartEVT.getSizeInBits()) {
478 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
479 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
480 // It's possible a scalar floating point type gets softened to integer and
481 // then promoted to a larger integer. If PartEVT is the larger integer
482 // we need to truncate it and then bitcast to the FP type.
483 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
484 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
485 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
486 Val = DAG.getBitcast(ValueSVT, Val);
487 } else {
488 Val = ValueVT.isFloatingPoint()
489 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
490 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
491 }
492 }
493
494 return DAG.getBuildVector(ValueVT, DL, Val);
495}
496
497static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498 SDValue Val, SDValue *Parts, unsigned NumParts,
499 MVT PartVT, const Value *V,
500 std::optional<CallingConv::ID> CallConv);
501
502/// getCopyToParts - Create a series of nodes that contain the specified value
503/// split into legal parts. If the parts contain more bits than Val, then, for
504/// integers, ExtendKind can be used to specify how to generate the extra bits.
505static void
507 unsigned NumParts, MVT PartVT, const Value *V,
508 std::optional<CallingConv::ID> CallConv = std::nullopt,
510 // Let the target split the parts if it wants to
511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
512 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
513 CallConv))
514 return;
515 EVT ValueVT = Val.getValueType();
516
517 // Handle the vector case separately.
518 if (ValueVT.isVector())
519 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
520 CallConv);
521
522 unsigned OrigNumParts = NumParts;
524 "Copying to an illegal type!");
525
526 if (NumParts == 0)
527 return;
528
529 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
530 EVT PartEVT = PartVT;
531 if (PartEVT == ValueVT) {
532 assert(NumParts == 1 && "No-op copy with multiple parts!");
533 Parts[0] = Val;
534 return;
535 }
536
537 unsigned PartBits = PartVT.getSizeInBits();
538 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
539 // If the parts cover more bits than the value has, promote the value.
540 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
541 assert(NumParts == 1 && "Do not know what to promote to!");
542 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
543 } else {
544 if (ValueVT.isFloatingPoint()) {
545 // FP values need to be bitcast, then extended if they are being put
546 // into a larger container.
547 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
548 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
549 }
550 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
551 ValueVT.isInteger() &&
552 "Unknown mismatch!");
553 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
554 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
555 if (PartVT == MVT::x86mmx)
556 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557 }
558 } else if (PartBits == ValueVT.getSizeInBits()) {
559 // Different types of the same size.
560 assert(NumParts == 1 && PartEVT != ValueVT);
561 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
562 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
563 // If the parts cover less bits than value has, truncate the value.
564 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
565 ValueVT.isInteger() &&
566 "Unknown mismatch!");
567 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
568 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
569 if (PartVT == MVT::x86mmx)
570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
571 }
572
573 // The value may have changed - recompute ValueVT.
574 ValueVT = Val.getValueType();
575 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
576 "Failed to tile the value with PartVT!");
577
578 if (NumParts == 1) {
579 if (PartEVT != ValueVT) {
581 "scalar-to-vector conversion failed");
582 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
583 }
584
585 Parts[0] = Val;
586 return;
587 }
588
589 // Expand the value into multiple parts.
590 if (NumParts & (NumParts - 1)) {
591 // The number of parts is not a power of 2. Split off and copy the tail.
592 assert(PartVT.isInteger() && ValueVT.isInteger() &&
593 "Do not know what to expand to!");
594 unsigned RoundParts = llvm::bit_floor(NumParts);
595 unsigned RoundBits = RoundParts * PartBits;
596 unsigned OddParts = NumParts - RoundParts;
597 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
598 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
599
600 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
601 CallConv);
602
603 if (DAG.getDataLayout().isBigEndian())
604 // The odd parts were reversed by getCopyToParts - unreverse them.
605 std::reverse(Parts + RoundParts, Parts + NumParts);
606
607 NumParts = RoundParts;
608 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
609 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
610 }
611
612 // The number of parts is a power of 2. Repeatedly bisect the value using
613 // EXTRACT_ELEMENT.
614 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
616 ValueVT.getSizeInBits()),
617 Val);
618
619 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
620 for (unsigned i = 0; i < NumParts; i += StepSize) {
621 unsigned ThisBits = StepSize * PartBits / 2;
622 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
623 SDValue &Part0 = Parts[i];
624 SDValue &Part1 = Parts[i+StepSize/2];
625
626 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
628 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
629 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
630
631 if (ThisBits == PartBits && ThisVT != PartVT) {
632 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
633 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
634 }
635 }
636 }
637
638 if (DAG.getDataLayout().isBigEndian())
639 std::reverse(Parts, Parts + OrigNumParts);
640}
641
643 const SDLoc &DL, EVT PartVT) {
644 if (!PartVT.isVector())
645 return SDValue();
646
647 EVT ValueVT = Val.getValueType();
648 EVT PartEVT = PartVT.getVectorElementType();
649 EVT ValueEVT = ValueVT.getVectorElementType();
650 ElementCount PartNumElts = PartVT.getVectorElementCount();
651 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
652
653 // We only support widening vectors with equivalent element types and
654 // fixed/scalable properties. If a target needs to widen a fixed-length type
655 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
656 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
657 PartNumElts.isScalable() != ValueNumElts.isScalable())
658 return SDValue();
659
660 // Have a try for bf16 because some targets share its ABI with fp16.
661 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
663 "Cannot widen to illegal type");
664 Val = DAG.getNode(
666 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
667 } else if (PartEVT != ValueEVT) {
668 return SDValue();
669 }
670
671 // Widening a scalable vector to another scalable vector is done by inserting
672 // the vector into a larger undef one.
673 if (PartNumElts.isScalable())
674 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
675 Val, DAG.getVectorIdxConstant(0, DL));
676
677 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
678 // undef elements.
680 DAG.ExtractVectorElements(Val, Ops);
681 SDValue EltUndef = DAG.getUNDEF(PartEVT);
682 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
683
684 // FIXME: Use CONCAT for 2x -> 4x.
685 return DAG.getBuildVector(PartVT, DL, Ops);
686}
687
688/// getCopyToPartsVector - Create a series of nodes that contain the specified
689/// value split into legal parts.
690static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
691 SDValue Val, SDValue *Parts, unsigned NumParts,
692 MVT PartVT, const Value *V,
693 std::optional<CallingConv::ID> CallConv) {
694 EVT ValueVT = Val.getValueType();
695 assert(ValueVT.isVector() && "Not a vector");
696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
697 const bool IsABIRegCopy = CallConv.has_value();
698
699 if (NumParts == 1) {
700 EVT PartEVT = PartVT;
701 if (PartEVT == ValueVT) {
702 // Nothing to do.
703 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
704 // Bitconvert vector->vector case.
705 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
706 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
707 Val = Widened;
708 } else if (PartVT.isVector() &&
710 ValueVT.getVectorElementType()) &&
711 PartEVT.getVectorElementCount() ==
712 ValueVT.getVectorElementCount()) {
713
714 // Promoted vector extract
715 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716 } else if (PartEVT.isVector() &&
717 PartEVT.getVectorElementType() !=
718 ValueVT.getVectorElementType() &&
719 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
721 // Combination of widening and promotion.
722 EVT WidenVT =
724 PartVT.getVectorElementCount());
725 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
726 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
727 } else {
728 // Don't extract an integer from a float vector. This can happen if the
729 // FP type gets softened to integer and then promoted. The promotion
730 // prevents it from being picked up by the earlier bitcast case.
731 if (ValueVT.getVectorElementCount().isScalar() &&
732 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
733 // If we reach this condition and PartVT is FP, this means that
734 // ValueVT is also FP and both have a different size, otherwise we
735 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
736 // would be invalid since that would mean the smaller FP type has to
737 // be extended to the larger one.
738 if (PartVT.isFloatingPoint()) {
739 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
740 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
741 } else
742 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
743 DAG.getVectorIdxConstant(0, DL));
744 } else {
745 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
746 assert(PartVT.getFixedSizeInBits() > ValueSize &&
747 "lossy conversion of vector to scalar type");
748 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
749 Val = DAG.getBitcast(IntermediateType, Val);
750 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
751 }
752 }
753
754 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
755 Parts[0] = Val;
756 return;
757 }
758
759 // Handle a multi-element vector.
760 EVT IntermediateVT;
761 MVT RegisterVT;
762 unsigned NumIntermediates;
763 unsigned NumRegs;
764 if (IsABIRegCopy) {
766 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
767 RegisterVT);
768 } else {
769 NumRegs =
770 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
771 NumIntermediates, RegisterVT);
772 }
773
774 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
775 NumParts = NumRegs; // Silence a compiler warning.
776 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
777
778 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
779 "Mixing scalable and fixed vectors when copying in parts");
780
781 std::optional<ElementCount> DestEltCnt;
782
783 if (IntermediateVT.isVector())
784 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
785 else
786 DestEltCnt = ElementCount::getFixed(NumIntermediates);
787
788 EVT BuiltVectorTy = EVT::getVectorVT(
789 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
790
791 if (ValueVT == BuiltVectorTy) {
792 // Nothing to do.
793 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
794 // Bitconvert vector->vector case.
795 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
796 } else {
797 if (BuiltVectorTy.getVectorElementType().bitsGT(
798 ValueVT.getVectorElementType())) {
799 // Integer promotion.
800 ValueVT = EVT::getVectorVT(*DAG.getContext(),
801 BuiltVectorTy.getVectorElementType(),
802 ValueVT.getVectorElementCount());
803 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
804 }
805
806 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
807 Val = Widened;
808 }
809 }
810
811 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
812
813 // Split the vector into intermediate operands.
814 SmallVector<SDValue, 8> Ops(NumIntermediates);
815 for (unsigned i = 0; i != NumIntermediates; ++i) {
816 if (IntermediateVT.isVector()) {
817 // This does something sensible for scalable vectors - see the
818 // definition of EXTRACT_SUBVECTOR for further details.
819 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
820 Ops[i] =
821 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
822 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
823 } else {
824 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
825 DAG.getVectorIdxConstant(i, DL));
826 }
827 }
828
829 // Split the intermediate operands into legal parts.
830 if (NumParts == NumIntermediates) {
831 // If the register was not expanded, promote or copy the value,
832 // as appropriate.
833 for (unsigned i = 0; i != NumParts; ++i)
834 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
835 } else if (NumParts > 0) {
836 // If the intermediate type was expanded, split each the value into
837 // legal parts.
838 assert(NumIntermediates != 0 && "division by zero");
839 assert(NumParts % NumIntermediates == 0 &&
840 "Must expand into a divisible number of parts!");
841 unsigned Factor = NumParts / NumIntermediates;
842 for (unsigned i = 0; i != NumIntermediates; ++i)
843 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
844 CallConv);
845 }
846}
847
848static void failForInvalidBundles(const CallBase &I, StringRef Name,
849 ArrayRef<uint32_t> AllowedBundles) {
850 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
851 ListSeparator LS;
852 std::string Error;
854 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
855 OperandBundleUse U = I.getOperandBundleAt(i);
856 if (!is_contained(AllowedBundles, U.getTagID()))
857 OS << LS << U.getTagName();
858 }
860 Twine("cannot lower ", Name)
861 .concat(Twine(" with arbitrary operand bundles: ", Error)));
862 }
863}
864
866 EVT valuevt, std::optional<CallingConv::ID> CC)
867 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
868 RegCount(1, regs.size()), CallConv(CC) {}
869
871 const DataLayout &DL, Register Reg, Type *Ty,
872 std::optional<CallingConv::ID> CC) {
873 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
874
875 CallConv = CC;
876
877 for (EVT ValueVT : ValueVTs) {
878 unsigned NumRegs =
880 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
881 : TLI.getNumRegisters(Context, ValueVT);
882 MVT RegisterVT =
884 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
885 : TLI.getRegisterType(Context, ValueVT);
886 for (unsigned i = 0; i != NumRegs; ++i)
887 Regs.push_back(Reg + i);
888 RegVTs.push_back(RegisterVT);
889 RegCount.push_back(NumRegs);
890 Reg = Reg.id() + NumRegs;
891 }
892}
893
895 FunctionLoweringInfo &FuncInfo,
896 const SDLoc &dl, SDValue &Chain,
897 SDValue *Glue, const Value *V) const {
898 // A Value with type {} or [0 x %t] needs no registers.
899 if (ValueVTs.empty())
900 return SDValue();
901
902 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
903
904 // Assemble the legal parts into the final values.
907 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
908 // Copy the legal parts from the registers.
909 EVT ValueVT = ValueVTs[Value];
910 unsigned NumRegs = RegCount[Value];
911 MVT RegisterVT = isABIMangled()
913 *DAG.getContext(), *CallConv, RegVTs[Value])
914 : RegVTs[Value];
915
916 Parts.resize(NumRegs);
917 for (unsigned i = 0; i != NumRegs; ++i) {
918 SDValue P;
919 if (!Glue) {
920 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
921 } else {
922 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
923 *Glue = P.getValue(2);
924 }
925
926 Chain = P.getValue(1);
927 Parts[i] = P;
928
929 // If the source register was virtual and if we know something about it,
930 // add an assert node.
931 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
932 continue;
933
935 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
936 if (!LOI)
937 continue;
938
939 unsigned RegSize = RegisterVT.getScalarSizeInBits();
940 unsigned NumSignBits = LOI->NumSignBits;
941 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
942
943 if (NumZeroBits == RegSize) {
944 // The current value is a zero.
945 // Explicitly express that as it would be easier for
946 // optimizations to kick in.
947 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
948 continue;
949 }
950
951 // FIXME: We capture more information than the dag can represent. For
952 // now, just use the tightest assertzext/assertsext possible.
953 bool isSExt;
954 EVT FromVT(MVT::Other);
955 if (NumZeroBits) {
956 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
957 isSExt = false;
958 } else if (NumSignBits > 1) {
959 FromVT =
960 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
961 isSExt = true;
962 } else {
963 continue;
964 }
965 // Add an assertion node.
966 assert(FromVT != MVT::Other);
967 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
968 RegisterVT, P, DAG.getValueType(FromVT));
969 }
970
971 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
972 RegisterVT, ValueVT, V, Chain, CallConv);
973 Part += NumRegs;
974 Parts.clear();
975 }
976
977 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
978}
979
981 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
982 const Value *V,
983 ISD::NodeType PreferredExtendType) const {
984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
985 ISD::NodeType ExtendKind = PreferredExtendType;
986
987 // Get the list of the values's legal parts.
988 unsigned NumRegs = Regs.size();
989 SmallVector<SDValue, 8> Parts(NumRegs);
990 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
991 unsigned NumParts = RegCount[Value];
992
993 MVT RegisterVT = isABIMangled()
995 *DAG.getContext(), *CallConv, RegVTs[Value])
996 : RegVTs[Value];
997
999 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
1001
1002 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1003 NumParts, RegisterVT, V, CallConv, ExtendKind);
1004 Part += NumParts;
1005 }
1006
1007 // Copy the parts into the registers.
1008 SmallVector<SDValue, 8> Chains(NumRegs);
1009 for (unsigned i = 0; i != NumRegs; ++i) {
1010 SDValue Part;
1011 if (!Glue) {
1012 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1013 } else {
1014 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1015 *Glue = Part.getValue(1);
1016 }
1017
1018 Chains[i] = Part.getValue(0);
1019 }
1020
1021 if (NumRegs == 1 || Glue)
1022 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1023 // flagged to it. That is the CopyToReg nodes and the user are considered
1024 // a single scheduling unit. If we create a TokenFactor and return it as
1025 // chain, then the TokenFactor is both a predecessor (operand) of the
1026 // user as well as a successor (the TF operands are flagged to the user).
1027 // c1, f1 = CopyToReg
1028 // c2, f2 = CopyToReg
1029 // c3 = TokenFactor c1, c2
1030 // ...
1031 // = op c3, ..., f2
1032 Chain = Chains[NumRegs-1];
1033 else
1034 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1035}
1036
1038 unsigned MatchingIdx, const SDLoc &dl,
1039 SelectionDAG &DAG,
1040 std::vector<SDValue> &Ops) const {
1041 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1042
1043 InlineAsm::Flag Flag(Code, Regs.size());
1044 if (HasMatching)
1045 Flag.setMatchingOp(MatchingIdx);
1046 else if (!Regs.empty() && Regs.front().isVirtual()) {
1047 // Put the register class of the virtual registers in the flag word. That
1048 // way, later passes can recompute register class constraints for inline
1049 // assembly as well as normal instructions.
1050 // Don't do this for tied operands that can use the regclass information
1051 // from the def.
1053 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1054 Flag.setRegClass(RC->getID());
1055 }
1056
1057 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1058 Ops.push_back(Res);
1059
1060 if (Code == InlineAsm::Kind::Clobber) {
1061 // Clobbers should always have a 1:1 mapping with registers, and may
1062 // reference registers that have illegal (e.g. vector) types. Hence, we
1063 // shouldn't try to apply any sort of splitting logic to them.
1064 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1065 "No 1:1 mapping from clobbers to regs?");
1067 (void)SP;
1068 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1069 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1070 assert(
1071 (Regs[I] != SP ||
1073 "If we clobbered the stack pointer, MFI should know about it.");
1074 }
1075 return;
1076 }
1077
1078 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1079 MVT RegisterVT = RegVTs[Value];
1080 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1081 RegisterVT);
1082 for (unsigned i = 0; i != NumRegs; ++i) {
1083 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1084 Register TheReg = Regs[Reg++];
1085 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1086 }
1087 }
1088}
1089
1093 unsigned I = 0;
1094 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1095 unsigned RegCount = std::get<0>(CountAndVT);
1096 MVT RegisterVT = std::get<1>(CountAndVT);
1097 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1098 for (unsigned E = I + RegCount; I != E; ++I)
1099 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1100 }
1101 return OutVec;
1102}
1103
1105 AssumptionCache *ac, const TargetLibraryInfo *li,
1106 const TargetTransformInfo &TTI) {
1107 BatchAA = aa;
1108 AC = ac;
1109 GFI = gfi;
1110 LibInfo = li;
1111 Context = DAG.getContext();
1112 LPadToCallSiteMap.clear();
1113 this->TTI = &TTI;
1114 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1115 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1116 *DAG.getMachineFunction().getFunction().getParent());
1117 CanDescribeGlobalAddressInLocationList =
1118 canDescribeGlobalAddressInLocationList(DAG.getMachineFunction());
1119}
1120
1122 NodeMap.clear();
1123 UnusedArgNodeMap.clear();
1124 PendingLoads.clear();
1125 PendingExports.clear();
1126 PendingConstrainedFP.clear();
1127 PendingConstrainedFPStrict.clear();
1128 CurInst = nullptr;
1129 HasTailCall = false;
1130 SDNodeOrder = LowestSDNodeOrder;
1131 StatepointLowering.clear();
1132}
1133
1135 DanglingDebugInfoMap.clear();
1136}
1137
1138// Update DAG root to include dependencies on Pending chains.
1139SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1140 SDValue Root = DAG.getRoot();
1141
1142 if (Pending.empty())
1143 return Root;
1144
1145 // Add current root to PendingChains, unless we already indirectly
1146 // depend on it.
1147 if (Root.getOpcode() != ISD::EntryToken) {
1148 unsigned i = 0, e = Pending.size();
1149 for (; i != e; ++i) {
1150 assert(Pending[i].getNode()->getNumOperands() > 1);
1151 if (Pending[i].getNode()->getOperand(0) == Root)
1152 break; // Don't add the root if we already indirectly depend on it.
1153 }
1154
1155 if (i == e)
1156 Pending.push_back(Root);
1157 }
1158
1159 if (Pending.size() == 1)
1160 Root = Pending[0];
1161 else
1162 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1163
1164 DAG.setRoot(Root);
1165 Pending.clear();
1166 return Root;
1167}
1168
1172
1174 // If the new exception behavior differs from that of the pending
1175 // ones, chain up them and update the root.
1176 switch (EB) {
1179 // Floating-point exceptions produced by such operations are not intended
1180 // to be observed, so the sequence of these operations does not need to be
1181 // preserved.
1182 //
1183 // They however must not be mixed with the instructions that have strict
1184 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1185 // 'ebStrict' operations could distort the observed exception behavior.
1186 if (!PendingConstrainedFPStrict.empty()) {
1187 assert(PendingConstrainedFP.empty());
1188 updateRoot(PendingConstrainedFPStrict);
1189 }
1190 break;
1192 // Floating-point exception produced by these operations may be observed, so
1193 // they must be correctly chained. If trapping on FP exceptions is
1194 // disabled, the exceptions can be observed only by functions that read
1195 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1196 // the order of operations is not significant between barriers.
1197 //
1198 // If trapping is enabled, each operation becomes an implicit observation
1199 // point, so the operations must be sequenced according their original
1200 // source order.
1201 if (!PendingConstrainedFP.empty()) {
1202 assert(PendingConstrainedFPStrict.empty());
1203 updateRoot(PendingConstrainedFP);
1204 }
1205 // TODO: Add support for trapping-enabled scenarios.
1206 }
1207 return DAG.getRoot();
1208}
1209
1211 // Chain up all pending constrained intrinsics together with all
1212 // pending loads, by simply appending them to PendingLoads and
1213 // then calling getMemoryRoot().
1214 PendingLoads.reserve(PendingLoads.size() +
1215 PendingConstrainedFP.size() +
1216 PendingConstrainedFPStrict.size());
1217 PendingLoads.append(PendingConstrainedFP.begin(),
1218 PendingConstrainedFP.end());
1219 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1220 PendingConstrainedFPStrict.end());
1221 PendingConstrainedFP.clear();
1222 PendingConstrainedFPStrict.clear();
1223 return getMemoryRoot();
1224}
1225
1227 // We need to emit pending fpexcept.strict constrained intrinsics,
1228 // so append them to the PendingExports list.
1229 PendingExports.append(PendingConstrainedFPStrict.begin(),
1230 PendingConstrainedFPStrict.end());
1231 PendingConstrainedFPStrict.clear();
1232 return updateRoot(PendingExports);
1233}
1234
1236 DILocalVariable *Variable,
1238 DebugLoc DL) {
1239 assert(Variable && "Missing variable");
1240
1241 // Check if address has undef value.
1242 if (!Address || isa<UndefValue>(Address) ||
1243 (Address->use_empty() && !isa<Argument>(Address))) {
1244 LLVM_DEBUG(
1245 dbgs()
1246 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1247 return;
1248 }
1249
1250 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1251
1252 SDValue &N = NodeMap[Address];
1253 if (!N.getNode() && isa<Argument>(Address))
1254 // Check unused arguments map.
1255 N = UnusedArgNodeMap[Address];
1256 SDDbgValue *SDV;
1257 if (N.getNode()) {
1258 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1259 Address = BCI->getOperand(0);
1260 // Parameters are handled specially.
1261 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1262 if (IsParameter && FINode) {
1263 // Byval parameter. We have a frame index at this point.
1264 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1265 /*IsIndirect*/ true, DL, SDNodeOrder);
1266 } else if (isa<Argument>(Address)) {
1267 // Address is an argument, so try to emit its dbg value using
1268 // virtual register info from the FuncInfo.ValueMap.
1269 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1270 FuncArgumentDbgValueKind::Declare, N);
1271 return;
1272 } else {
1273 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1274 true, DL, SDNodeOrder);
1275 }
1276 DAG.AddDbgValue(SDV, IsParameter);
1277 } else {
1278 // If Address is an argument then try to emit its dbg value using
1279 // virtual register info from the FuncInfo.ValueMap.
1280 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1281 FuncArgumentDbgValueKind::Declare, N)) {
1282 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1283 << " (could not emit func-arg dbg_value)\n");
1284 }
1285 }
1286}
1287
1289 // Add SDDbgValue nodes for any var locs here. Do so before updating
1290 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1291 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1292 // Add SDDbgValue nodes for any var locs here. Do so before updating
1293 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1294 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1295 It != End; ++It) {
1296 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1297 dropDanglingDebugInfo(Var, It->Expr);
1298 if (It->Values.isKillLocation(It->Expr)) {
1299 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1300 continue;
1301 }
1302 SmallVector<Value *> Values(It->Values.location_ops());
1303 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1304 It->Values.hasArgList())) {
1305 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1307 FnVarLocs->getDILocalVariable(It->VariableID),
1308 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1309 }
1310 }
1311 }
1312
1313 // We must skip DbgVariableRecords if they've already been processed above as
1314 // we have just emitted the debug values resulting from assignment tracking
1315 // analysis, making any existing DbgVariableRecords redundant (and probably
1316 // less correct). We still need to process DbgLabelRecords. This does sink
1317 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1318 // be important as it does so deterministcally and ordering between
1319 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1320 // printing).
1321 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1322 // Is there is any debug-info attached to this instruction, in the form of
1323 // DbgRecord non-instruction debug-info records.
1324 for (DbgRecord &DR : I.getDbgRecordRange()) {
1325 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1326 assert(DLR->getLabel() && "Missing label");
1327 SDDbgLabel *SDV =
1328 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1329 DAG.AddDbgLabel(SDV);
1330 continue;
1331 }
1332
1333 if (SkipDbgVariableRecords)
1334 continue;
1336 DILocalVariable *Variable = DVR.getVariable();
1339
1341 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1342 continue;
1343 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1344 << "\n");
1346 DVR.getDebugLoc());
1347 continue;
1348 }
1349
1350 // A DbgVariableRecord with no locations is a kill location.
1352 if (Values.empty()) {
1354 SDNodeOrder);
1355 continue;
1356 }
1357
1358 // A DbgVariableRecord with an undef or absent location is also a kill
1359 // location.
1360 if (llvm::any_of(Values,
1361 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1363 SDNodeOrder);
1364 continue;
1365 }
1366
1367 bool IsVariadic = DVR.hasArgList();
1368 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1369 SDNodeOrder, IsVariadic)) {
1370 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1371 DVR.getDebugLoc(), SDNodeOrder);
1372 }
1373 }
1374}
1375
1377 visitDbgInfo(I);
1378
1379 // Set up outgoing PHI node register values before emitting the terminator.
1380 if (I.isTerminator()) {
1381 HandlePHINodesInSuccessorBlocks(I.getParent());
1382 }
1383
1384 ++SDNodeOrder;
1385 CurInst = &I;
1386
1387 // Set inserted listener only if required.
1388 bool NodeInserted = false;
1389 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1390 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1391 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1392 if (PCSectionsMD || MMRA) {
1393 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1394 DAG, [&](SDNode *) { NodeInserted = true; });
1395 }
1396
1397 visit(I.getOpcode(), I);
1398
1399 if (!I.isTerminator() && !HasTailCall &&
1400 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1402
1403 // Handle metadata.
1404 if (PCSectionsMD || MMRA) {
1405 auto It = NodeMap.find(&I);
1406 if (It != NodeMap.end()) {
1407 if (PCSectionsMD)
1408 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1409 if (MMRA)
1410 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1411 } else if (NodeInserted) {
1412 // This should not happen; if it does, don't let it go unnoticed so we can
1413 // fix it. Relevant visit*() function is probably missing a setValue().
1414 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1415 << I.getModule()->getName() << "]\n";
1416 LLVM_DEBUG(I.dump());
1417 assert(false);
1418 }
1419 }
1420
1421 CurInst = nullptr;
1422}
1423
1424void SelectionDAGBuilder::visitPHI(const PHINode &) {
1425 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1426}
1427
1428void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1429 // Note: this doesn't use InstVisitor, because it has to work with
1430 // ConstantExpr's in addition to instructions.
1431 switch (Opcode) {
1432 default: llvm_unreachable("Unknown instruction type encountered!");
1433 // Build the switch statement using the Instruction.def file.
1434#define HANDLE_INST(NUM, OPCODE, CLASS) \
1435 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1436#include "llvm/IR/Instruction.def"
1437 }
1438}
1439
1441 DILocalVariable *Variable,
1442 DebugLoc DL, unsigned Order,
1445 // For variadic dbg_values we will now insert poison.
1446 // FIXME: We can potentially recover these!
1448 for (const Value *V : Values) {
1449 auto *Poison = PoisonValue::get(V->getType());
1450 Locs.push_back(SDDbgOperand::fromConst(Poison));
1451 }
1452 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1453 /*IsIndirect=*/false, DL, Order,
1454 /*IsVariadic=*/true);
1455 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1456 return true;
1457}
1458
1460 DILocalVariable *Var,
1461 DIExpression *Expr,
1462 bool IsVariadic, DebugLoc DL,
1463 unsigned Order) {
1464 if (IsVariadic) {
1465 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1466 return;
1467 }
1468 // TODO: Dangling debug info will eventually either be resolved or produce
1469 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1470 // between the original dbg.value location and its resolved DBG_VALUE,
1471 // which we should ideally fill with an extra poison DBG_VALUE.
1472 assert(Values.size() == 1);
1473 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1474}
1475
1477 const DIExpression *Expr) {
1478 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1479 DIVariable *DanglingVariable = DDI.getVariable();
1480 DIExpression *DanglingExpr = DDI.getExpression();
1481 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1482 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1483 << printDDI(nullptr, DDI) << "\n");
1484 return true;
1485 }
1486 return false;
1487 };
1488
1489 for (auto &DDIMI : DanglingDebugInfoMap) {
1490 DanglingDebugInfoVector &DDIV = DDIMI.second;
1491
1492 // If debug info is to be dropped, run it through final checks to see
1493 // whether it can be salvaged.
1494 for (auto &DDI : DDIV)
1495 if (isMatchingDbgValue(DDI))
1496 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1497
1498 erase_if(DDIV, isMatchingDbgValue);
1499 }
1500}
1501
1502// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1503// generate the debug data structures now that we've seen its definition.
1505 SDValue Val) {
1506 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1507 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1508 return;
1509
1510 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1511 for (auto &DDI : DDIV) {
1512 DebugLoc DL = DDI.getDebugLoc();
1513 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1514 DILocalVariable *Variable = DDI.getVariable();
1515 DIExpression *Expr = DDI.getExpression();
1516 assert(Variable->isValidLocationForIntrinsic(DL) &&
1517 "Expected inlined-at fields to agree");
1518 SDDbgValue *SDV;
1519 if (Val.getNode()) {
1520 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1521 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1522 // we couldn't resolve it directly when examining the DbgValue intrinsic
1523 // in the first place we should not be more successful here). Unless we
1524 // have some test case that prove this to be correct we should avoid
1525 // calling EmitFuncArgumentDbgValue here.
1526 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1527 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1528 FuncArgumentDbgValueKind::Value, Val)) {
1529 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1530 << printDDI(V, DDI) << "\n");
1531 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1532 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1533 // inserted after the definition of Val when emitting the instructions
1534 // after ISel. An alternative could be to teach
1535 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1536 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1537 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1538 << ValSDNodeOrder << "\n");
1539 SDV = getDbgValue(Val, Variable, Expr, DL,
1540 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1541 DAG.AddDbgValue(SDV, false);
1542 } else
1543 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1544 << printDDI(V, DDI)
1545 << " in EmitFuncArgumentDbgValue\n");
1546 } else {
1547 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1548 << "\n");
1549 auto Poison = PoisonValue::get(V->getType());
1550 auto SDV =
1551 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1552 DAG.AddDbgValue(SDV, false);
1553 }
1554 }
1555 DDIV.clear();
1556}
1557
1558/// If \p V is the address of a describable global, possibly displaced by a
1559/// constant, return the global and fold the displacement into location operand
1560/// \p OpIdx of \p Expr. The displacement rides along in the expression rather
1561/// than in the operand, so that it survives into a DBG_INSTR_REF.
1562static const GlobalValue *
1563getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx,
1564 const MachineFunction &MF) {
1565 const auto *C = dyn_cast<Constant>(V);
1566 if (!C)
1567 return nullptr;
1568 int64_t Offset;
1570 if (GV && Offset) {
1573 Expr = DIExpression::appendOpsToArg(Expr, Ops, OpIdx, /*StackValue=*/false);
1574 }
1575 return GV;
1576}
1577
1579 DanglingDebugInfo &DDI) {
1580 // TODO: For the variadic implementation, instead of only checking the fail
1581 // state of `handleDebugValue`, we need know specifically which values were
1582 // invalid, so that we attempt to salvage only those values when processing
1583 // a DIArgList.
1584 const Value *OrigV = V;
1585 DILocalVariable *Var = DDI.getVariable();
1586 DIExpression *Expr = DDI.getExpression();
1587 DebugLoc DL = DDI.getDebugLoc();
1588 unsigned SDOrder = DDI.getSDNodeOrder();
1589
1590 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1591 // that DW_OP_stack_value is desired.
1592 bool StackValue = true;
1593
1594 // handleDebugValue holds out for a register with the address of a global
1595 // that a location list could not name. With no such register forthcoming,
1596 // naming the global still beats dropping the location.
1597 auto HandleGlobalAddress = [&] {
1598 DIExpression *GVExpr = Expr;
1599 const GlobalValue *GV =
1600 getGlobalAddressDbgOperand(V, GVExpr, 0, DAG.getMachineFunction());
1601 if (!GV)
1602 return false;
1603 SDDbgValue *SDV = DAG.getDbgValueList(
1604 Var, GVExpr, SDDbgOperand::fromGlobalAddr(GV), /*Dependencies=*/{},
1605 /*IsIndirect=*/false, DL, SDOrder, /*IsVariadic=*/false);
1606 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1607 return true;
1608 };
1609
1610 // Can this Value can be encoded without any further work?
1611 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1612 HandleGlobalAddress())
1613 return;
1614
1615 // Attempt to salvage back through as many instructions as possible. Bail if
1616 // a non-instruction is seen, such as a constant expression or global
1617 // variable. FIXME: Further work could recover those too.
1618 while (isa<Instruction>(V)) {
1619 const Instruction &VAsInst = *cast<const Instruction>(V);
1620 // Temporary "0", awaiting real implementation.
1622 SmallVector<Value *, 4> AdditionalValues;
1623 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1624 Expr->getNumLocationOperands(), Ops,
1625 AdditionalValues);
1626 // If we cannot salvage any further, and haven't yet found a suitable debug
1627 // expression, bail out.
1628 if (!V)
1629 break;
1630
1631 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1632 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1633 // here for variadic dbg_values, remove that condition.
1634 if (!AdditionalValues.empty())
1635 break;
1636
1637 // New value and expr now represent this debuginfo.
1639
1640 // Some kind of simplification occurred: check whether the operand of the
1641 // salvaged debug expression can be encoded in this DAG.
1642 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false) ||
1643 HandleGlobalAddress()) {
1644 LLVM_DEBUG(
1645 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1646 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1647 return;
1648 }
1649 }
1650
1651 // This was the final opportunity to salvage this debug information, and it
1652 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1653 // any earlier variable location.
1654 assert(OrigV && "V shouldn't be null");
1655 auto *Poison = PoisonValue::get(OrigV->getType());
1656 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDNodeOrder);
1657 DAG.AddDbgValue(SDV, false);
1658 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1659 << printDDI(OrigV, DDI) << "\n");
1660}
1661
1663 DIExpression *Expr,
1664 DebugLoc DbgLoc,
1665 unsigned Order) {
1666 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1669 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1670 /*IsVariadic*/ false);
1671}
1672
1674 DILocalVariable *Var,
1675 DIExpression *Expr, DebugLoc DbgLoc,
1676 unsigned Order, bool IsVariadic) {
1677 if (Values.empty())
1678 return true;
1679
1680 // Filter EntryValue locations out early.
1681 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1682 return true;
1683
1684 SmallVector<SDDbgOperand> LocationOps;
1685 SmallVector<SDNode *> Dependencies;
1686 for (const auto &[OpIdx, V] : enumerate(Values)) {
1687 // Constant value.
1690 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1691 continue;
1692 }
1693
1694 // Look through IntToPtr constants.
1695 if (auto *CE = dyn_cast<ConstantExpr>(V))
1696 if (CE->getOpcode() == Instruction::IntToPtr) {
1697 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1698 continue;
1699 }
1700
1701 // The address of a global is a link-time constant, and so is a constant
1702 // displacement from one. A global whose address cannot be described this
1703 // way falls through to be described by whatever materializes it instead.
1704 // So does one that a location list could not name, should the variable
1705 // need one; salvageUnresolvedDbgValue names it if nothing materializes it.
1706 if (CanDescribeGlobalAddressInLocationList)
1708 V, Expr, OpIdx, DAG.getMachineFunction())) {
1710 continue;
1711 }
1712
1713 // If the Value is a frame index, we can create a FrameIndex debug value
1714 // without relying on the DAG at all.
1715 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1716 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1717 if (SI != FuncInfo.StaticAllocaMap.end()) {
1718 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1719 continue;
1720 }
1721 }
1722
1723 // Do not use getValue() in here; we don't want to generate code at
1724 // this point if it hasn't been done yet.
1725 SDValue N = NodeMap[V];
1726 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1727 N = UnusedArgNodeMap[V];
1728
1729 if (N.getNode()) {
1730 // Only emit func arg dbg value for non-variadic dbg.values for now.
1731 if (!IsVariadic &&
1732 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1733 FuncArgumentDbgValueKind::Value, N))
1734 return true;
1735 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1736 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1737 // describe stack slot locations.
1738 //
1739 // Consider "int x = 0; int *px = &x;". There are two kinds of
1740 // interesting debug values here after optimization:
1741 //
1742 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1743 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1744 //
1745 // Both describe the direct values of their associated variables.
1746 Dependencies.push_back(N.getNode());
1747 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1748 continue;
1749 }
1750 LocationOps.emplace_back(
1751 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1752 continue;
1753 }
1754
1755 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1756 // Special rules apply for the first dbg.values of parameter variables in a
1757 // function. Identify them by the fact they reference Argument Values, that
1758 // they're parameters, and they are parameters of the current function. We
1759 // need to let them dangle until they get an SDNode.
1760 bool IsParamOfFunc =
1761 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1762 if (IsParamOfFunc)
1763 return false;
1764
1765 // The value is not used in this block yet (or it would have an SDNode).
1766 // We still want the value to appear for the user if possible -- if it has
1767 // an associated VReg, we can refer to that instead.
1768 auto VMI = FuncInfo.ValueMap.find(V);
1769 if (VMI != FuncInfo.ValueMap.end()) {
1770 Register Reg = VMI->second;
1771 // If this is a PHI node, it may be split up into several MI PHI nodes
1772 // (in FunctionLoweringInfo::set).
1773 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1774 V->getType(), std::nullopt);
1775 if (RFV.occupiesMultipleRegs()) {
1776 // FIXME: We could potentially support variadic dbg_values here.
1777 if (IsVariadic)
1778 return false;
1779 unsigned Offset = 0;
1780 unsigned BitsToDescribe = 0;
1781 if (auto VarSize = Var->getSizeInBits())
1782 BitsToDescribe = *VarSize;
1783 if (auto Fragment = Expr->getFragmentInfo())
1784 BitsToDescribe = Fragment->SizeInBits;
1785 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1786 // Bail out if all bits are described already.
1787 if (Offset >= BitsToDescribe)
1788 break;
1789 // TODO: handle scalable vectors.
1790 unsigned RegisterSize = RegAndSize.second;
1791 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1792 ? BitsToDescribe - Offset
1793 : RegisterSize;
1794 auto FragmentExpr = DIExpression::createFragmentExpression(
1795 Expr, Offset, FragmentSize);
1796 if (!FragmentExpr)
1797 continue;
1798 SDDbgValue *SDV = DAG.getVRegDbgValue(
1799 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1800 DAG.AddDbgValue(SDV, false);
1801 Offset += RegisterSize;
1802 }
1803 return true;
1804 }
1805 // We can use simple vreg locations for variadic dbg_values as well.
1806 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1807 continue;
1808 }
1809 // We failed to create a SDDbgOperand for V.
1810 return false;
1811 }
1812
1813 // We have created a SDDbgOperand for each Value in Values.
1814 assert(!LocationOps.empty());
1815 SDDbgValue *SDV =
1816 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1817 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1818 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1819 return true;
1820}
1821
1823 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1824 for (auto &Pair : DanglingDebugInfoMap)
1825 for (auto &DDI : Pair.second)
1826 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1828}
1829
1830/// getCopyFromRegs - If there was virtual register allocated for the value V
1831/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1833 auto It = FuncInfo.ValueMap.find(V);
1834 SDValue Result;
1835
1836 if (It != FuncInfo.ValueMap.end()) {
1837 Register InReg = It->second;
1838
1839 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1840 DAG.getDataLayout(), InReg, Ty,
1841 std::nullopt); // This is not an ABI copy.
1842 SDValue Chain = DAG.getEntryNode();
1843 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1844 V);
1845 resolveDanglingDebugInfo(V, Result);
1846 }
1847
1848 return Result;
1849}
1850
1851/// getValue - Return an SDValue for the given Value.
1853 // If we already have an SDValue for this value, use it. It's important
1854 // to do this first, so that we don't create a CopyFromReg if we already
1855 // have a regular SDValue.
1856 SDValue &N = NodeMap[V];
1857 if (N.getNode()) return N;
1858
1859 // If there's a virtual register allocated and initialized for this
1860 // value, use it.
1861 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1862 return copyFromReg;
1863
1864 // Otherwise create a new SDValue and remember it.
1865 SDValue Val = getValueImpl(V);
1866 NodeMap[V] = Val;
1868 return Val;
1869}
1870
1871void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1872 if (V->getType()->isVoidTy())
1873 return;
1874
1875 SmallVector<EVT, 4> ValueVTs;
1876 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1877 V->getType(), ValueVTs);
1878 if (ValueVTs.empty())
1879 return;
1880 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1881}
1882
1883/// getNonRegisterValue - Return an SDValue for the given Value, but
1884/// don't look in FuncInfo.ValueMap for a virtual register.
1886 // If we already have an SDValue for this value, use it.
1887 SDValue &N = NodeMap[V];
1888 if (N.getNode()) {
1889 if (isIntOrFPConstant(N)) {
1890 // Remove the debug location from the node as the node is about to be used
1891 // in a location which may differ from the original debug location. This
1892 // is relevant to Constant and ConstantFP nodes because they can appear
1893 // as constant expressions inside PHI nodes.
1894 N->setDebugLoc(DebugLoc());
1895 }
1896 return N;
1897 }
1898
1899 // Otherwise create a new SDValue and remember it.
1900 SDValue Val = getValueImpl(V);
1901 NodeMap[V] = Val;
1903 return Val;
1904}
1905
1906/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1907/// Create an SDValue for the given value.
1909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1910
1911 if (const Constant *C = dyn_cast<Constant>(V)) {
1912 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1913
1914 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1915 SDLoc DL = getCurSDLoc();
1916
1917 // DAG.getConstant() may attempt to legalise the vector constant which can
1918 // significantly change the combines applied to the DAG. To reduce the
1919 // divergence when enabling ConstantInt based vectors we try to construct
1920 // the DAG in the same way as shufflevector based splats. TODO: The
1921 // divergence sometimes leads to better optimisations. Ideally we should
1922 // prevent DAG.getConstant() from legalising too early but there are some
1923 // degradations preventing this.
1924 if (VT.isScalableVector())
1925 return DAG.getNode(
1926 ISD::SPLAT_VECTOR, DL, VT,
1927 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1928 if (VT.isFixedLengthVector())
1929 return DAG.getSplatBuildVector(
1930 VT, DL,
1931 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1932 return DAG.getConstant(*CI, DL, VT);
1933 }
1934
1935 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1936 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1937
1938 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1939 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1940
1941 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1942 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1943 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1944 getValue(CPA->getAddrDiscriminator()),
1945 getValue(CPA->getDiscriminator()));
1946 }
1947
1949 return DAG.getConstant(0, getCurSDLoc(), VT);
1950
1951 if (match(C, m_VScale()))
1952 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1953
1954 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1955 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1956
1957 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1958 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1959
1960 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1961 visit(CE->getOpcode(), *CE);
1962 SDValue N1 = NodeMap[V];
1963 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1964 return N1;
1965 }
1966
1968 SmallVector<SDValue, 4> Constants;
1969 for (const Use &U : C->operands()) {
1970 SDNode *Val = getValue(U).getNode();
1971 // If the operand is an empty aggregate, there are no values.
1972 if (!Val) continue;
1973 // Add each leaf value from the operand to the Constants list
1974 // to form a flattened list of all the values.
1975 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1976 Constants.push_back(SDValue(Val, i));
1977 }
1978
1979 return DAG.getMergeValues(Constants, getCurSDLoc());
1980 }
1981
1982 if (const ConstantDataSequential *CDS =
1985 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1986 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1987 // Add each leaf value from the operand to the Constants list
1988 // to form a flattened list of all the values.
1989 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1990 Ops.push_back(SDValue(Val, i));
1991 }
1992
1993 if (isa<ArrayType>(CDS->getType()))
1994 return DAG.getMergeValues(Ops, getCurSDLoc());
1995 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1996 }
1997
1998 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
2000 "Unknown struct or array constant!");
2001
2002 SmallVector<EVT, 4> ValueVTs;
2003 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
2004 unsigned NumElts = ValueVTs.size();
2005 if (NumElts == 0)
2006 return SDValue(); // empty struct
2007 SmallVector<SDValue, 4> Constants(NumElts);
2008 for (unsigned i = 0; i != NumElts; ++i) {
2009 EVT EltVT = ValueVTs[i];
2010 if (isa<UndefValue>(C))
2011 Constants[i] = DAG.getUNDEF(EltVT);
2012 else if (EltVT.isFloatingPoint())
2013 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2014 else
2015 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
2016 }
2017
2018 return DAG.getMergeValues(Constants, getCurSDLoc());
2019 }
2020
2021 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
2022 return DAG.getBlockAddress(BA, VT);
2023
2024 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
2025 return getValue(Equiv->getGlobalValue());
2026
2027 if (const auto *NC = dyn_cast<NoCFIValue>(C))
2028 return getValue(NC->getGlobalValue());
2029
2030 if (VT == MVT::aarch64svcount) {
2031 assert(C->isNullValue() && "Can only zero this target type!");
2032 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
2033 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
2034 }
2035
2036 if (VT.isRISCVVectorTuple()) {
2037 assert(C->isNullValue() && "Can only zero this target type!");
2038 return DAG.getNode(
2040 DAG.getNode(
2042 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
2043 VT.getSizeInBits().getKnownMinValue() / 8, true),
2044 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
2045 }
2046
2047 if (VT == MVT::externref || VT == MVT::funcref) {
2048 assert(C->isNullValue() && "Can only zero this target type!");
2049 // The zero value of a WebAssembly reference type is the null reference,
2050 // materialized with ref.null.
2051 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
2052 : Intrinsic::wasm_ref_null_func;
2053 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
2054 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
2055 }
2056
2057 VectorType *VecTy = cast<VectorType>(V->getType());
2058
2059 // Now that we know the number and type of the elements, get that number of
2060 // elements into the Ops array based on what kind of constant it is.
2061 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2063 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2064 for (unsigned i = 0; i != NumElements; ++i)
2065 Ops.push_back(getValue(CV->getOperand(i)));
2066
2067 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2068 }
2069
2071 EVT EltVT =
2072 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2073
2074 SDValue Op;
2075 if (EltVT.isFloatingPoint())
2076 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2077 else
2078 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2079
2080 return DAG.getSplat(VT, getCurSDLoc(), Op);
2081 }
2082
2083 llvm_unreachable("Unknown vector constant");
2084 }
2085
2086 // If this is a static alloca, generate it as the frameindex instead of
2087 // computation.
2088 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2089 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2090 if (SI != FuncInfo.StaticAllocaMap.end())
2091 return DAG.getFrameIndex(
2092 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2093 }
2094
2095 // If this is an instruction which fast-isel has deferred, select it now.
2096 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2097 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2098 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2099 Inst->getType(), std::nullopt);
2100 SDValue Chain = DAG.getEntryNode();
2101 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2102 }
2103
2104 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2105 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2106
2107 if (const auto *BB = dyn_cast<BasicBlock>(V))
2108 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2109
2110 llvm_unreachable("Can't get register for value!");
2111}
2112
2113void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2115 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2116 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2117 bool IsSEH = isAsynchronousEHPersonality(Pers);
2118 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2119 if (IsSEH) {
2120 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2121 CatchPadMBB->setIsEHContTarget(true);
2123 } else
2124 CatchPadMBB->setIsEHScopeEntry();
2125 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2126 if (IsMSVCCXX || IsCoreCLR)
2127 CatchPadMBB->setIsEHFuncletEntry();
2128}
2129
2130void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2131 // Update machine-CFG edge.
2132 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2133 FuncInfo.MBB->addSuccessor(TargetMBB);
2134
2135 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2136 bool IsSEH = isAsynchronousEHPersonality(Pers);
2137 if (IsSEH) {
2138 // If this is not a fall-through branch or optimizations are switched off,
2139 // emit the branch.
2140 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2141 TM.getOptLevel() == CodeGenOptLevel::None)
2142 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2143 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2144 return;
2145 }
2146
2147 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2148 TargetMBB->setIsEHContTarget(true);
2149 DAG.getMachineFunction().setHasEHContTarget(true);
2150
2151 // Figure out the funclet membership for the catchret's successor.
2152 // This will be used by the FuncletLayout pass to determine how to order the
2153 // BB's.
2154 // A 'catchret' returns to the outer scope's color.
2155 Value *ParentPad = I.getCatchSwitchParentPad();
2156 const BasicBlock *SuccessorColor;
2157 if (isa<ConstantTokenNone>(ParentPad))
2158 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2159 else
2160 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2161 assert(SuccessorColor && "No parent funclet for catchret!");
2162 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2163 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2164
2165 // Create the terminator node.
2166 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2167 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2168 DAG.getBasicBlock(SuccessorColorMBB));
2169 DAG.setRoot(Ret);
2170}
2171
2172void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2173 // Don't emit any special code for the cleanuppad instruction. It just marks
2174 // the start of an EH scope/funclet.
2175 FuncInfo.MBB->setIsEHScopeEntry();
2176 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2177 if (Pers != EHPersonality::Wasm_CXX && Pers != EHPersonality::Wasm_D) {
2178 FuncInfo.MBB->setIsEHFuncletEntry();
2179 FuncInfo.MBB->setIsCleanupFuncletEntry();
2180 }
2181}
2182
2183/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2184/// many places it could ultimately go. In the IR, we have a single unwind
2185/// destination, but in the machine CFG, we enumerate all the possible blocks.
2186/// This function skips over imaginary basic blocks that hold catchswitch
2187/// instructions, and finds all the "real" machine
2188/// basic block destinations. As those destinations may not be successors of
2189/// EHPadBB, here we also calculate the edge probability to those destinations.
2190/// The passed-in Prob is the edge probability to EHPadBB.
2192 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2193 BranchProbability Prob,
2194 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2195 &UnwindDests) {
2196 EHPersonality Personality =
2198 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2199 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2200 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2201 bool IsWasmD = Personality == EHPersonality::Wasm_D;
2202 bool IsSEH = isAsynchronousEHPersonality(Personality);
2203
2204 while (EHPadBB) {
2206 BasicBlock *NewEHPadBB = nullptr;
2207 if (isa<LandingPadInst>(Pad)) {
2208 // Stop on landingpads. They are not funclets.
2209 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2210 break;
2211 } else if (isa<CleanupPadInst>(Pad)) {
2212 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2213 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2214 // which always catches an exception.
2215 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2216 UnwindDests.back().first->setIsEHScopeEntry();
2217 // In Wasm, EH scopes are not funclets
2218 if (!IsWasmCXX && !IsWasmD)
2219 UnwindDests.back().first->setIsEHFuncletEntry();
2220 break;
2221 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2222 // Add the catchpad handlers to the possible destinations.
2223 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2224 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2225 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2226 if (IsMSVCCXX || IsCoreCLR)
2227 UnwindDests.back().first->setIsEHFuncletEntry();
2228 if (!IsSEH)
2229 UnwindDests.back().first->setIsEHScopeEntry();
2230 }
2231 NewEHPadBB = CatchSwitch->getUnwindDest();
2232 } else {
2233 continue;
2234 }
2235
2236 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2237 if (BPI && NewEHPadBB)
2238 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2239 EHPadBB = NewEHPadBB;
2240 }
2241}
2242
2243void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2244 // Update successor info.
2246 auto UnwindDest = I.getUnwindDest();
2247 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2248 BranchProbability UnwindDestProb =
2249 (BPI && UnwindDest)
2250 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2252 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2253 for (auto &UnwindDest : UnwindDests) {
2254 UnwindDest.first->setIsEHPad();
2255 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2256 }
2257 FuncInfo.MBB->normalizeSuccProbs();
2258
2259 // Create the terminator node.
2260 MachineBasicBlock *CleanupPadMBB =
2261 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2262 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2263 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2264 DAG.setRoot(Ret);
2265}
2266
2267void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2268 report_fatal_error("visitCatchSwitch not yet implemented!");
2269}
2270
2271void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2272 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2273 auto &DL = DAG.getDataLayout();
2274 SDValue Chain = getControlRoot();
2277
2278 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2279 // lower
2280 //
2281 // %val = call <ty> @llvm.experimental.deoptimize()
2282 // ret <ty> %val
2283 //
2284 // differently.
2285 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2287 return;
2288 }
2289
2290 if (!FuncInfo.CanLowerReturn) {
2291 Register DemoteReg = FuncInfo.DemoteRegister;
2292
2293 // Emit a store of the return value through the virtual register.
2294 // Leave Outs empty so that LowerReturn won't try to load return
2295 // registers the usual way.
2296 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2297 SDValue RetPtr =
2298 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2299 Type *RetTy = I.getOperand(0)->getType();
2300 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2301 RetPtr =
2302 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2303 SDValue RetOp = getValue(I.getOperand(0));
2304
2305 SmallVector<EVT, 4> ValueVTs, MemVTs;
2306 SmallVector<uint64_t, 4> Offsets;
2307 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2308 unsigned NumValues = ValueVTs.size();
2309
2310 SmallVector<SDValue, 4> Chains(NumValues);
2311 for (unsigned i = 0; i != NumValues; ++i) {
2312 // An aggregate return value cannot wrap around the address space, so
2313 // offsets to its parts don't wrap either.
2314 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2315 TypeSize::getFixed(Offsets[i]));
2316
2317 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2318 if (MemVTs[i] != ValueVTs[i])
2319 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2320 Chains[i] = DAG.getStore(
2321 Chain, getCurSDLoc(), Val,
2322 // FIXME: better loc info would be nice.
2323 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2324 commonAlignment(BaseAlign, Offsets[i]));
2325 }
2326
2327 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2328 MVT::Other, Chains);
2329 } else if (I.getNumOperands() != 0) {
2331 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2332 unsigned NumValues = Types.size();
2333 if (NumValues) {
2334 SDValue RetOp = getValue(I.getOperand(0));
2335
2336 const Function *F = I.getParent()->getParent();
2337
2338 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2339 I.getOperand(0)->getType(), F->getCallingConv(),
2340 /*IsVarArg*/ false, DL);
2341
2343 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2345 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2347
2348 LLVMContext &Context = F->getContext();
2349 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2350
2351 for (unsigned j = 0; j != NumValues; ++j) {
2352 EVT VT = TLI.getValueType(DL, Types[j]);
2353
2354 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2355 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2356
2357 CallingConv::ID CC = F->getCallingConv();
2358
2359 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2360 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2361 SmallVector<SDValue, 4> Parts(NumParts);
2363 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2364 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2365
2366 // 'inreg' on function refers to return value
2367 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2368 if (RetInReg)
2369 Flags.setInReg();
2370
2371 if (I.getOperand(0)->getType()->isPointerTy()) {
2372 Flags.setPointer();
2373 Flags.setPointerAddrSpace(
2374 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2375 }
2376
2377 if (NeedsRegBlock) {
2378 Flags.setInConsecutiveRegs();
2379 if (j == NumValues - 1)
2380 Flags.setInConsecutiveRegsLast();
2381 }
2382
2383 // Propagate extension type if any
2385 Flags.setSExt();
2386 else if (ExtendKind == ISD::ZERO_EXTEND)
2387 Flags.setZExt();
2388 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2389 Flags.setNoExt();
2390
2391 for (unsigned i = 0; i < NumParts; ++i) {
2392 Outs.push_back(ISD::OutputArg(Flags,
2393 Parts[i].getValueType().getSimpleVT(),
2394 VT, Types[j], 0, 0));
2395 OutVals.push_back(Parts[i]);
2396 }
2397 }
2398 }
2399 }
2400
2401 // Push in swifterror virtual register as the last element of Outs. This makes
2402 // sure swifterror virtual register will be returned in the swifterror
2403 // physical register.
2404 const Function *F = I.getParent()->getParent();
2405 if (TLI.supportSwiftError() &&
2406 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2407 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2408 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2409 Flags.setSwiftError();
2410 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2411 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2412 PointerType::getUnqual(*DAG.getContext()),
2413 /*origidx=*/1, /*partOffs=*/0));
2414 // Create SDNode for the swifterror virtual register.
2415 OutVals.push_back(
2416 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2417 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2418 EVT(TLI.getPointerTy(DL))));
2419 }
2420
2421 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2422 CallingConv::ID CallConv =
2423 DAG.getMachineFunction().getFunction().getCallingConv();
2424 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2425 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2426
2427 // Verify that the target's LowerReturn behaved as expected.
2428 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2429 "LowerReturn didn't return a valid chain!");
2430
2431 // Update the DAG with the new chain value resulting from return lowering.
2432 DAG.setRoot(Chain);
2433}
2434
2435/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2436/// created for it, emit nodes to copy the value into the virtual
2437/// registers.
2439 // Skip empty types
2440 if (V->getType()->isEmptyTy())
2441 return;
2442
2443 auto VMI = FuncInfo.ValueMap.find(V);
2444 if (VMI != FuncInfo.ValueMap.end()) {
2445 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2446 "Unused value assigned virtual registers!");
2447 CopyValueToVirtualRegister(V, VMI->second);
2448 }
2449}
2450
2451/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2452/// the current basic block, add it to ValueMap now so that we'll get a
2453/// CopyTo/FromReg.
2455 // No need to export constants.
2456 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2457
2458 // Already exported?
2459 if (FuncInfo.isExportedInst(V)) return;
2460
2461 Register Reg = FuncInfo.InitializeRegForValue(V);
2463}
2464
2466 const BasicBlock *FromBB) {
2467 // The operands of the setcc have to be in this block. We don't know
2468 // how to export them from some other block.
2469 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2470 // Can export from current BB.
2471 if (VI->getParent() == FromBB)
2472 return true;
2473
2474 // Is already exported, noop.
2475 return FuncInfo.isExportedInst(V);
2476 }
2477
2478 // If this is an argument, we can export it if the BB is the entry block or
2479 // if it is already exported.
2480 if (isa<Argument>(V)) {
2481 if (FromBB->isEntryBlock())
2482 return true;
2483
2484 // Otherwise, can only export this if it is already exported.
2485 return FuncInfo.isExportedInst(V);
2486 }
2487
2488 // Otherwise, constants can always be exported.
2489 return true;
2490}
2491
2492/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2494SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2495 const MachineBasicBlock *Dst) const {
2497 const BasicBlock *SrcBB = Src->getBasicBlock();
2498 const BasicBlock *DstBB = Dst->getBasicBlock();
2499 if (!BPI) {
2500 // If BPI is not available, set the default probability as 1 / N, where N is
2501 // the number of successors.
2502 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2503 return BranchProbability(1, SuccSize);
2504 }
2505 return BPI->getEdgeProbability(SrcBB, DstBB);
2506}
2507
2508void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2509 MachineBasicBlock *Dst,
2510 BranchProbability Prob) {
2511 if (!FuncInfo.BPI)
2512 Src->addSuccessorWithoutProb(Dst);
2513 else {
2514 if (Prob.isUnknown())
2515 Prob = getEdgeProbability(Src, Dst);
2516 Src->addSuccessor(Dst, Prob);
2517 }
2518}
2519
2520static bool InBlock(const Value *V, const BasicBlock *BB) {
2521 if (const Instruction *I = dyn_cast<Instruction>(V))
2522 return I->getParent() == BB;
2523 return true;
2524}
2525
2526/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2527/// This function emits a branch and is used at the leaves of an OR or an
2528/// AND operator tree.
2529void
2532 MachineBasicBlock *FBB,
2533 MachineBasicBlock *CurBB,
2534 MachineBasicBlock *SwitchBB,
2535 BranchProbability TProb,
2536 BranchProbability FProb,
2537 bool InvertCond) {
2538 const BasicBlock *BB = CurBB->getBasicBlock();
2539
2540 // If the leaf of the tree is a comparison, merge the condition into
2541 // the caseblock.
2542 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2543 // The operands of the cmp have to be in this block. We don't know
2544 // how to export them from some other block. If this is the first block
2545 // of the sequence, no exporting is needed.
2546 if (CurBB == SwitchBB ||
2547 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2548 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2549 ISD::CondCode Condition;
2550 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2551 ICmpInst::Predicate Pred =
2552 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2553 Condition = getICmpCondCode(Pred);
2554 } else {
2555 const FCmpInst *FC = cast<FCmpInst>(Cond);
2556 FCmpInst::Predicate Pred =
2557 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2558 Condition = getFCmpCondCode(Pred);
2559 if (FC->hasNoNaNs() ||
2560 (isKnownNeverNaN(FC->getOperand(0),
2561 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2562 isKnownNeverNaN(FC->getOperand(1),
2563 SimplifyQuery(DAG.getDataLayout(), FC))))
2564 Condition = getFCmpCodeWithoutNaN(Condition);
2565 }
2566
2567 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2568 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2569 SL->SwitchCases.push_back(CB);
2570 return;
2571 }
2572 }
2573
2574 // Create a CaseBlock record representing this branch.
2575 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2576 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2577 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2578 SL->SwitchCases.push_back(CB);
2579}
2580
2581// Collect dependencies on V recursively. This is used for the cost analysis in
2582// `shouldKeepJumpConditionsTogether`.
2586 unsigned Depth = 0) {
2587 // Return false if we have an incomplete count.
2589 return false;
2590
2591 auto *I = dyn_cast<Instruction>(V);
2592 if (I == nullptr)
2593 return true;
2594
2595 if (Necessary != nullptr) {
2596 // This instruction is necessary for the other side of the condition so
2597 // don't count it.
2598 if (Necessary->contains(I))
2599 return true;
2600 }
2601
2602 // Already added this dep.
2603 if (!Deps->try_emplace(I, false).second)
2604 return true;
2605
2606 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2607 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2608 Depth + 1))
2609 return false;
2610 return true;
2611}
2612
2615 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2617 if (Params.BaseCost < 0)
2618 return false;
2619
2620 // Baseline cost.
2621 InstructionCost CostThresh = Params.BaseCost;
2622
2623 BranchProbabilityInfo *BPI = nullptr;
2624 if (Params.LikelyBias || Params.UnlikelyBias)
2625 BPI = FuncInfo.BPI;
2626 if (BPI != nullptr) {
2627 // See if we are either likely to get an early out or compute both lhs/rhs
2628 // of the condition.
2629 BasicBlock *IfTrue = I.getSuccessor(0);
2630 BasicBlock *IfFalse = I.getSuccessor(1);
2632 std::swap(IfTrue, IfFalse);
2633
2634 std::optional<bool> Likely;
2635 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2636 Likely = true;
2637 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2638 Likely = false;
2639
2640 if (Likely) {
2641 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2642 // Its likely we will have to compute both lhs and rhs of condition
2643 CostThresh += Params.LikelyBias;
2644 else {
2645 if (Params.UnlikelyBias < 0)
2646 return false;
2647 // Its likely we will get an early out.
2648 CostThresh -= Params.UnlikelyBias;
2649 }
2650 }
2651 }
2652
2653 if (CostThresh <= 0)
2654 return false;
2655
2656 // Collect "all" instructions that lhs condition is dependent on.
2657 // Use map for stable iteration (to avoid non-determanism of iteration of
2658 // SmallPtrSet). The `bool` value is just a dummy.
2660 collectInstructionDeps(&LhsDeps, Lhs);
2661 // Collect "all" instructions that rhs condition is dependent on AND are
2662 // dependencies of lhs. This gives us an estimate on which instructions we
2663 // stand to save by splitting the condition.
2664 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2665 return false;
2666 // Add the compare instruction itself unless its a dependency on the LHS.
2667 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2668 if (!LhsDeps.contains(RhsI))
2669 RhsDeps.try_emplace(RhsI, false);
2670
2671 InstructionCost CostOfIncluding = 0;
2672 // See if this instruction will need to computed independently of whether RHS
2673 // is.
2674 Value *BrCond = I.getCondition();
2675 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2676 for (const auto *U : Ins->users()) {
2677 // If user is independent of RHS calculation we don't need to count it.
2678 if (auto *UIns = dyn_cast<Instruction>(U))
2679 if (UIns != BrCond && !RhsDeps.contains(UIns))
2680 return false;
2681 }
2682 return true;
2683 };
2684
2685 // Prune instructions from RHS Deps that are dependencies of unrelated
2686 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2687 // arbitrary and just meant to cap the how much time we spend in the pruning
2688 // loop. Its highly unlikely to come into affect.
2689 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2690 // Stop after a certain point. No incorrectness from including too many
2691 // instructions.
2692 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2693 const Instruction *ToDrop = nullptr;
2694 for (const auto &InsPair : RhsDeps) {
2695 if (!ShouldCountInsn(InsPair.first)) {
2696 ToDrop = InsPair.first;
2697 break;
2698 }
2699 }
2700 if (ToDrop == nullptr)
2701 break;
2702 RhsDeps.erase(ToDrop);
2703 }
2704
2705 for (const auto &InsPair : RhsDeps) {
2706 // Finally accumulate latency that we can only attribute to computing the
2707 // RHS condition. Use latency because we are essentially trying to calculate
2708 // the cost of the dependency chain.
2709 // Possible TODO: We could try to estimate ILP and make this more precise.
2710 CostOfIncluding += TTI->getInstructionCost(
2711 InsPair.first, TargetTransformInfo::TCK_Latency);
2712
2713 if (CostOfIncluding > CostThresh)
2714 return false;
2715 }
2716 return true;
2717}
2718
2721 MachineBasicBlock *FBB,
2722 MachineBasicBlock *CurBB,
2723 MachineBasicBlock *SwitchBB,
2725 BranchProbability TProb,
2726 BranchProbability FProb,
2727 bool InvertCond) {
2728 // Skip over not part of the tree and remember to invert op and operands at
2729 // next level.
2730 Value *NotCond;
2731 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2732 InBlock(NotCond, CurBB->getBasicBlock())) {
2733 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2734 !InvertCond);
2735 return;
2736 }
2737
2739 const Value *BOpOp0, *BOpOp1;
2740 // Compute the effective opcode for Cond, taking into account whether it needs
2741 // to be inverted, e.g.
2742 // and (not (or A, B)), C
2743 // gets lowered as
2744 // and (and (not A, not B), C)
2746 if (BOp) {
2747 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2748 ? Instruction::And
2749 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2750 ? Instruction::Or
2752 if (InvertCond) {
2753 if (BOpc == Instruction::And)
2754 BOpc = Instruction::Or;
2755 else if (BOpc == Instruction::Or)
2756 BOpc = Instruction::And;
2757 }
2758 }
2759
2760 // If this node is not part of the or/and tree, emit it as a branch.
2761 // Note that all nodes in the tree should have same opcode.
2762 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2763 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2764 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2765 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2766 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2767 TProb, FProb, InvertCond);
2768 return;
2769 }
2770
2771 // Create TmpBB after CurBB.
2772 MachineFunction::iterator BBI(CurBB);
2773 MachineFunction &MF = DAG.getMachineFunction();
2775 CurBB->getParent()->insert(++BBI, TmpBB);
2776
2777 if (Opc == Instruction::Or) {
2778 // Codegen X | Y as:
2779 // BB1:
2780 // jmp_if_X TBB
2781 // jmp TmpBB
2782 // TmpBB:
2783 // jmp_if_Y TBB
2784 // jmp FBB
2785 //
2786
2787 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2788 // The requirement is that
2789 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2790 // = TrueProb for original BB.
2791 // Assuming the original probabilities are A and B, one choice is to set
2792 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2793 // A/(1+B) and 2B/(1+B). This choice assumes that
2794 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2795 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2796 // TmpBB, but the math is more complicated.
2797
2798 auto NewTrueProb = TProb / 2;
2799 auto NewFalseProb = TProb / 2 + FProb;
2800 // Emit the LHS condition.
2801 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2802 NewFalseProb, InvertCond);
2803
2804 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2805 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2807 // Emit the RHS condition into TmpBB.
2808 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2809 Probs[1], InvertCond);
2810 } else {
2811 assert(Opc == Instruction::And && "Unknown merge op!");
2812 // Codegen X & Y as:
2813 // BB1:
2814 // jmp_if_X TmpBB
2815 // jmp FBB
2816 // TmpBB:
2817 // jmp_if_Y TBB
2818 // jmp FBB
2819 //
2820 // This requires creation of TmpBB after CurBB.
2821
2822 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2823 // The requirement is that
2824 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2825 // = FalseProb for original BB.
2826 // Assuming the original probabilities are A and B, one choice is to set
2827 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2828 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2829 // TrueProb for BB1 * FalseProb for TmpBB.
2830
2831 auto NewTrueProb = TProb + FProb / 2;
2832 auto NewFalseProb = FProb / 2;
2833 // Emit the LHS condition.
2834 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2835 NewFalseProb, InvertCond);
2836
2837 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2838 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2840 // Emit the RHS condition into TmpBB.
2841 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2842 Probs[1], InvertCond);
2843 }
2844}
2845
2846/// If the set of cases should be emitted as a series of branches, return true.
2847/// If we should emit this as a bunch of and/or'd together conditions, return
2848/// false.
2849bool
2850SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2851 if (Cases.size() != 2) return true;
2852
2853 // If this is two comparisons of the same values or'd or and'd together, they
2854 // will get folded into a single comparison, so don't emit two blocks.
2855 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2856 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2857 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2858 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2859 return false;
2860 }
2861
2862 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2863 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2864 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2865 Cases[0].CC == Cases[1].CC &&
2866 isa<Constant>(Cases[0].CmpRHS) &&
2867 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2868 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2869 return false;
2870 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2871 return false;
2872 }
2873
2874 return true;
2875}
2876
2877void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2879
2880 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2881
2882 // Update machine-CFG edges.
2883 BrMBB->addSuccessor(Succ0MBB);
2884
2885 // If this is not a fall-through branch or optimizations are switched off,
2886 // emit the branch.
2887 if (Succ0MBB != NextBlock(BrMBB) ||
2889 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2890 DAG.getBasicBlock(Succ0MBB));
2891 setValue(&I, Br);
2892 DAG.setRoot(Br);
2893 }
2894}
2895
2896void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2897 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2898
2899 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2900
2901 // If this condition is one of the special cases we handle, do special stuff
2902 // now.
2903 const Value *CondVal = I.getCondition();
2904 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2905
2906 // If this is a series of conditions that are or'd or and'd together, emit
2907 // this as a sequence of branches instead of setcc's with and/or operations.
2908 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2909 // unpredictable branches, and vector extracts because those jumps are likely
2910 // expensive for any target), this should improve performance.
2911 // For example, instead of something like:
2912 // cmp A, B
2913 // C = seteq
2914 // cmp D, E
2915 // F = setle
2916 // or C, F
2917 // jnz foo
2918 // Emit:
2919 // cmp A, B
2920 // je foo
2921 // cmp D, E
2922 // jle foo
2923 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2924 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2925 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2926 BOp->hasOneUse() && !IsUnpredictable) {
2927 Value *Vec;
2928 const Value *BOp0, *BOp1;
2930 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2931 Opcode = Instruction::And;
2932 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2933 Opcode = Instruction::Or;
2934
2935 if (Opcode &&
2936 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2937 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2939 FuncInfo, I, Opcode, BOp0, BOp1,
2940 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2941 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2942 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2943 getEdgeProbability(BrMBB, Succ0MBB),
2944 getEdgeProbability(BrMBB, Succ1MBB),
2945 /*InvertCond=*/false);
2946 // If the compares in later blocks need to use values not currently
2947 // exported from this block, export them now. This block should always
2948 // be the first entry.
2949 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2950
2951 // Allow some cases to be rejected.
2952 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2953 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2954 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2955 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2956 }
2957
2958 // Emit the branch for this block.
2959 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2960 SL->SwitchCases.erase(SL->SwitchCases.begin());
2961 return;
2962 }
2963
2964 // Okay, we decided not to do this, remove any inserted MBB's and clear
2965 // SwitchCases.
2966 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2967 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2968
2969 SL->SwitchCases.clear();
2970 }
2971 }
2972
2973 // Create a CaseBlock record representing this branch.
2974 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2975 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2977 IsUnpredictable);
2978
2979 // Use visitSwitchCase to actually insert the fast branch sequence for this
2980 // cond branch.
2981 visitSwitchCase(CB, BrMBB);
2982}
2983
2984/// visitSwitchCase - Emits the necessary code to represent a single node in
2985/// the binary search tree resulting from lowering a switch instruction.
2987 MachineBasicBlock *SwitchBB) {
2988 SDValue Cond;
2989 SDValue CondLHS = getValue(CB.CmpLHS);
2990 SDLoc dl = CB.DL;
2991
2992 if (CB.CC == ISD::SETTRUE) {
2993 // Branch or fall through to TrueBB.
2994 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2995 SwitchBB->normalizeSuccProbs();
2996 if (CB.TrueBB != NextBlock(SwitchBB)) {
2997 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2998 DAG.getBasicBlock(CB.TrueBB)));
2999 }
3000 return;
3001 }
3002
3003 auto &TLI = DAG.getTargetLoweringInfo();
3004 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
3005
3006 // Build the setcc now.
3007 if (!CB.CmpMHS) {
3008 // Fold "(X == true)" to X and "(X == false)" to !X to
3009 // handle common cases produced by branch lowering.
3010 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
3011 CB.CC == ISD::SETEQ)
3012 Cond = CondLHS;
3013 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
3014 CB.CC == ISD::SETEQ) {
3015 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
3016 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
3017 } else {
3018 SDValue CondRHS = getValue(CB.CmpRHS);
3019
3020 // If a pointer's DAG type is larger than its memory type then the DAG
3021 // values are zero-extended. This breaks signed comparisons so truncate
3022 // back to the underlying type before doing the compare.
3023 if (CondLHS.getValueType() != MemVT) {
3024 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
3025 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
3026 }
3027 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
3028 }
3029 } else {
3030 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
3031
3032 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
3033 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
3034
3035 SDValue CmpOp = getValue(CB.CmpMHS);
3036 EVT VT = CmpOp.getValueType();
3037
3038 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
3039 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
3040 ISD::SETLE);
3041 } else {
3042 SDValue SUB = DAG.getNode(ISD::SUB, dl,
3043 VT, CmpOp, DAG.getConstant(Low, dl, VT));
3044 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
3045 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
3046 }
3047 }
3048
3049 // Update successor info
3050 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
3051 // TrueBB and FalseBB are always different unless the incoming IR is
3052 // degenerate. This only happens when running llc on weird IR.
3053 if (CB.TrueBB != CB.FalseBB)
3054 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
3055 SwitchBB->normalizeSuccProbs();
3056
3057 // If the lhs block is the next block, invert the condition so that we can
3058 // fall through to the lhs instead of the rhs block.
3059 if (CB.TrueBB == NextBlock(SwitchBB)) {
3060 std::swap(CB.TrueBB, CB.FalseBB);
3061 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3062 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3063 }
3064
3065 SDNodeFlags Flags;
3067 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3068 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3069
3070 setValue(CurInst, BrCond);
3071
3072 // Insert the false branch. Do this even if it's a fall through branch,
3073 // this makes it easier to do DAG optimizations which require inverting
3074 // the branch condition.
3075 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3076 DAG.getBasicBlock(CB.FalseBB));
3077
3078 DAG.setRoot(BrCond);
3079}
3080
3081/// visitJumpTable - Emit JumpTable node in the current MBB
3083 // Emit the code for the jump table
3084 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3085 assert(JT.Reg && "Should lower JT Header first!");
3086 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3087 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3088 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3089 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3090 Index.getValue(1), Table, Index);
3091 DAG.setRoot(BrJumpTable);
3092}
3093
3094/// visitJumpTableHeader - This function emits necessary code to produce index
3095/// in the JumpTable from switch case.
3097 JumpTableHeader &JTH,
3098 MachineBasicBlock *SwitchBB) {
3099 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3100 const SDLoc &dl = *JT.SL;
3101
3102 // Subtract the lowest switch case value from the value being switched on.
3103 SDValue SwitchOp = getValue(JTH.SValue);
3104 EVT VT = SwitchOp.getValueType();
3105 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3106 DAG.getConstant(JTH.First, dl, VT));
3107
3108 // The SDNode we just created, which holds the value being switched on minus
3109 // the smallest case value, needs to be copied to a virtual register so it
3110 // can be used as an index into the jump table in a subsequent basic block.
3111 // This value may be smaller or larger than the target's pointer type, and
3112 // therefore require extension or truncating.
3113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3114 SwitchOp =
3115 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3116
3117 Register JumpTableReg =
3118 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3119 SDValue CopyTo =
3120 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3121 JT.Reg = JumpTableReg;
3122
3123 if (!JTH.FallthroughUnreachable) {
3124 // Emit the range check for the jump table, and branch to the default block
3125 // for the switch statement if the value being switched on exceeds the
3126 // largest case in the switch.
3127 SDValue CMP = DAG.getSetCC(
3128 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3129 Sub.getValueType()),
3130 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3131
3132 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3133 MVT::Other, CopyTo, CMP,
3134 DAG.getBasicBlock(JT.Default));
3135
3136 // Avoid emitting unnecessary branches to the next block.
3137 if (JT.MBB != NextBlock(SwitchBB))
3138 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3139 DAG.getBasicBlock(JT.MBB));
3140
3141 DAG.setRoot(BrCond);
3142 } else {
3143 // Avoid emitting unnecessary branches to the next block.
3144 if (JT.MBB != NextBlock(SwitchBB))
3145 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3146 DAG.getBasicBlock(JT.MBB)));
3147 else
3148 DAG.setRoot(CopyTo);
3149 }
3150}
3151
3152/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3153/// variable if there exists one.
3155 SDValue &Chain) {
3156 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3157 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3158 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3160 Value *Global =
3163 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3164 if (Global) {
3165 MachinePointerInfo MPInfo(Global);
3169 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3170 DAG.setNodeMemRefs(Node, {MemRef});
3171 }
3172 if (PtrTy != PtrMemTy)
3173 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3174 return SDValue(Node, 0);
3175}
3176
3177/// Codegen a new tail for a stack protector check ParentMBB which has had its
3178/// tail spliced into a stack protector check success bb.
3179///
3180/// For a high level explanation of how this fits into the stack protector
3181/// generation see the comment on the declaration of class
3182/// StackProtectorDescriptor.
3184 MachineBasicBlock *ParentBB) {
3185
3186 // First create the loads to the guard/stack slot for the comparison.
3187 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3188 auto &DL = DAG.getDataLayout();
3189 EVT PtrTy = TLI.getFrameIndexTy(DL);
3190 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3191
3192 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3193 int FI = MFI.getStackProtectorIndex();
3194
3195 SDValue Guard;
3196 SDLoc dl = getCurSDLoc();
3197 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3198 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3199 Align Align = DL.getPrefTypeAlign(
3200 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3201
3202 // Generate code to load the content of the guard slot.
3203 SDValue GuardVal = DAG.getLoad(
3204 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3205 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3207
3208 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3209 // original cookie for comparison. The prologue stored (FP - Cookie) or
3210 // (FP XOR Cookie), so we apply the same operation again to unmix:
3211 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3212 if (TLI.useStackGuardMixFP())
3213 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3214
3215 // If we're using function-based instrumentation, call the guard check
3216 // function
3218 // Get the guard check function from the target and verify it exists since
3219 // we're using function-based instrumentation
3220 const Function *GuardCheckFn =
3221 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3222 assert(GuardCheckFn && "Guard check function is null");
3223
3224 // The target provides a guard check function to validate the guard value.
3225 // Generate a call to that function with the content of the guard slot as
3226 // argument.
3227 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3228 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3229
3231 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3232 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3233 Entry.IsInReg = true;
3234 Args.push_back(Entry);
3235
3238 .setChain(DAG.getEntryNode())
3239 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3240 getValue(GuardCheckFn), std::move(Args));
3241
3242 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3243 DAG.setRoot(Result.second);
3244 return;
3245 }
3246
3247 // Load the fresh guard value for comparison.
3248 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3249 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3250 SDValue Chain = DAG.getEntryNode();
3251 if (TLI.useStackGuardMixFP()) {
3252 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3253 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3254 SDValue GuardPtr = getValue(IRGuard);
3255 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3256 MachinePointerInfo(IRGuard, 0), Align,
3258 } else {
3259 LLVMContext &Ctx = *DAG.getContext();
3260 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3261 Guard = DAG.getPOISON(PtrMemTy);
3262 }
3263 } else {
3264 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3265 if (TLI.useLoadStackGuardNode(M)) {
3266 Guard = getLoadStackGuard(DAG, dl, Chain);
3267 } else {
3268 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3269 SDValue GuardPtr = getValue(IRGuard);
3270 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3271 MachinePointerInfo(IRGuard, 0), Align,
3273 } else {
3274 LLVMContext &Ctx = *DAG.getContext();
3275 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3276 Guard = DAG.getPOISON(PtrMemTy);
3277 }
3278 }
3279 }
3280
3281 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3282 // contain unmixed cookie values that can be compared directly.
3283
3284 // Perform the comparison via a getsetcc.
3285 SDValue Cmp = DAG.getSetCC(
3286 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3287 Guard, GuardVal, ISD::SETNE);
3288
3289 // If the guard/stackslot do not equal, branch to failure MBB.
3290 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3291 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3292 // Otherwise branch to success MBB.
3293 SDValue Br = DAG.getNode(ISD::BR, dl,
3294 MVT::Other, BrCond,
3295 DAG.getBasicBlock(SPD.getSuccessMBB()));
3296
3297 DAG.setRoot(Br);
3298}
3299
3300/// Codegen the failure basic block for a stack protector check.
3301///
3302/// A failure stack protector machine basic block consists simply of a call to
3303/// __stack_chk_fail().
3304///
3305/// For a high level explanation of how this fits into the stack protector
3306/// generation see the comment on the declaration of class
3307/// StackProtectorDescriptor.
3310
3311 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3312 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3313 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3314 SDValue Chain;
3315
3316 // For -Oz builds with a guard check function, we use function-based
3317 // instrumentation. Otherwise, if we have a guard check function, we call it
3318 // in the failure block.
3319 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3320 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3321 // First create the loads to the guard/stack slot for the comparison.
3322 auto &DL = DAG.getDataLayout();
3323 EVT PtrTy = TLI.getFrameIndexTy(DL);
3324 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3325
3326 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3327 int FI = MFI.getStackProtectorIndex();
3328
3329 SDLoc dl = getCurSDLoc();
3330 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3331 Align Align = DL.getPrefTypeAlign(
3332 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3333
3334 // Generate code to load the content of the guard slot.
3335 SDValue GuardVal = DAG.getLoad(
3336 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3337 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3339
3340 if (TLI.useStackGuardMixFP())
3341 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3342
3343 // The target provides a guard check function to validate the guard value.
3344 // Generate a call to that function with the content of the guard slot as
3345 // argument.
3346 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3347 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3348
3350 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3351 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3352 Entry.IsInReg = true;
3353 Args.push_back(Entry);
3354
3357 .setChain(DAG.getEntryNode())
3358 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3359 getValue(GuardCheckFn), std::move(Args));
3360
3361 Chain = TLI.LowerCallTo(CLI).second;
3362 } else {
3364 CallOptions.setDiscardResult(true);
3365 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3366 {}, CallOptions, getCurSDLoc())
3367 .second;
3368 }
3369
3370 // Emit a trap instruction if we are required to do so.
3371 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3372 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3373 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3374
3375 DAG.setRoot(Chain);
3376}
3377
3378/// visitBitTestHeader - This function emits necessary code to produce value
3379/// suitable for "bit tests"
3381 MachineBasicBlock *SwitchBB) {
3382 SDLoc dl = getCurSDLoc();
3383
3384 // Subtract the minimum value.
3385 SDValue SwitchOp = getValue(B.SValue);
3386 EVT VT = SwitchOp.getValueType();
3387 SDValue RangeSub =
3388 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3389
3390 // Determine the type of the test operands.
3391 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3392 bool UsePtrType = false;
3393 if (!TLI.isTypeLegal(VT)) {
3394 UsePtrType = true;
3395 } else {
3396 for (const BitTestCase &Case : B.Cases)
3397 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3398 // Switch table case range are encoded into series of masks.
3399 // Just use pointer type, it's guaranteed to fit.
3400 UsePtrType = true;
3401 break;
3402 }
3403 }
3404 SDValue Sub = RangeSub;
3405 if (UsePtrType) {
3406 VT = TLI.getPointerTy(DAG.getDataLayout());
3407 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3408 }
3409
3410 B.RegVT = VT.getSimpleVT();
3411 B.Reg = FuncInfo.CreateReg(B.RegVT);
3412 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3413
3414 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3415
3416 if (!B.FallthroughUnreachable)
3417 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3418 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3419 SwitchBB->normalizeSuccProbs();
3420
3421 SDValue Root = CopyTo;
3422 if (!B.FallthroughUnreachable) {
3423 // Conditional branch to the default block.
3424 SDValue RangeCmp = DAG.getSetCC(dl,
3425 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3426 RangeSub.getValueType()),
3427 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3428 ISD::SETUGT);
3429
3430 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3431 DAG.getBasicBlock(B.Default));
3432 }
3433
3434 // Avoid emitting unnecessary branches to the next block.
3435 if (MBB != NextBlock(SwitchBB))
3436 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3437
3438 DAG.setRoot(Root);
3439}
3440
3441/// visitBitTestCase - this function produces one "bit test"
3443 MachineBasicBlock *NextMBB,
3444 BranchProbability BranchProbToNext,
3445 Register Reg, BitTestCase &B,
3446 MachineBasicBlock *SwitchBB) {
3447 SDLoc dl = getCurSDLoc();
3448 MVT VT = BB.RegVT;
3449 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3450 SDValue Cmp;
3451 unsigned PopCount = llvm::popcount(B.Mask);
3452 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3453 if (PopCount == 1) {
3454 // Testing for a single bit; just compare the shift count with what it
3455 // would need to be to shift a 1 bit in that position.
3456 Cmp = DAG.getSetCC(
3457 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3458 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3459 ISD::SETEQ);
3460 } else if (PopCount == BB.Range) {
3461 // There is only one zero bit in the range, test for it directly.
3462 Cmp = DAG.getSetCC(
3463 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3464 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3465 } else {
3466 // Make desired shift
3467 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3468 DAG.getConstant(1, dl, VT), ShiftOp);
3469
3470 // Emit bit tests and jumps
3471 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3472 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3473 Cmp = DAG.getSetCC(
3474 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3475 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3476 }
3477
3478 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3479 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3480 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3481 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3482 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3483 // one as they are relative probabilities (and thus work more like weights),
3484 // and hence we need to normalize them to let the sum of them become one.
3485 SwitchBB->normalizeSuccProbs();
3486
3487 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3488 MVT::Other, getControlRoot(),
3489 Cmp, DAG.getBasicBlock(B.TargetBB));
3490
3491 // Avoid emitting unnecessary branches to the next block.
3492 if (NextMBB != NextBlock(SwitchBB))
3493 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3494 DAG.getBasicBlock(NextMBB));
3495
3496 DAG.setRoot(BrAnd);
3497}
3498
3499void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3500 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3501
3502 // Retrieve successors. Look through artificial IR level blocks like
3503 // catchswitch for successors.
3504 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3505 const BasicBlock *EHPadBB = I.getSuccessor(1);
3506 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3507
3508 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3509 // have to do anything here to lower funclet bundles.
3510 failForInvalidBundles(I, "invokes",
3516
3517 const Value *Callee(I.getCalledOperand());
3518 const Function *Fn = dyn_cast<Function>(Callee);
3519 if (isa<InlineAsm>(Callee))
3520 visitInlineAsm(I, EHPadBB);
3521 else if (Fn && Fn->isIntrinsic()) {
3522 switch (Fn->getIntrinsicID()) {
3523 default:
3524 llvm_unreachable("Cannot invoke this intrinsic");
3525 case Intrinsic::donothing:
3526 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3527 case Intrinsic::seh_try_begin:
3528 case Intrinsic::seh_scope_begin:
3529 case Intrinsic::seh_try_end:
3530 case Intrinsic::seh_scope_end:
3531 if (EHPadMBB)
3532 // a block referenced by EH table
3533 // so dtor-funclet not removed by opts
3534 EHPadMBB->setMachineBlockAddressTaken();
3535 break;
3536 case Intrinsic::experimental_patchpoint_void:
3537 case Intrinsic::experimental_patchpoint:
3538 visitPatchpoint(I, EHPadBB);
3539 break;
3540 case Intrinsic::experimental_gc_statepoint:
3542 break;
3543 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3544 // but these intrinsics are special because they can be invoked, so we
3545 // manually lower it to a DAG node here.
3546 case Intrinsic::wasm_throw: {
3548 std::array<SDValue, 4> Ops = {
3549 getControlRoot(), // inchain for the terminator node
3550 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3552 getValue(I.getArgOperand(0)), // tag
3553 getValue(I.getArgOperand(1)) // thrown value
3554 };
3555 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3556 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3557 break;
3558 }
3559 case Intrinsic::wasm_rethrow: {
3560 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3561 std::array<SDValue, 2> Ops = {
3562 getControlRoot(), // inchain for the terminator node
3563 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3564 TLI.getPointerTy(DAG.getDataLayout()))};
3565 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3566 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3567 break;
3568 }
3569 }
3570 } else if (I.hasDeoptState()) {
3571 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3572 // Eventually we will support lowering the @llvm.experimental.deoptimize
3573 // intrinsic, and right now there are no plans to support other intrinsics
3574 // with deopt state.
3575 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3576 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3578 } else {
3579 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3580 }
3581
3582 // If the value of the invoke is used outside of its defining block, make it
3583 // available as a virtual register.
3584 // We already took care of the exported value for the statepoint instruction
3585 // during call to the LowerStatepoint.
3586 if (!isa<GCStatepointInst>(I)) {
3588 }
3589
3591 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3592 BranchProbability EHPadBBProb =
3593 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3595 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3596
3597 // Update successor info.
3598 addSuccessorWithProb(InvokeMBB, Return);
3599 for (auto &UnwindDest : UnwindDests) {
3600 UnwindDest.first->setIsEHPad();
3601 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3602 }
3603 InvokeMBB->normalizeSuccProbs();
3604
3605 // Drop into normal successor.
3606 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3607 DAG.getBasicBlock(Return)));
3608}
3609
3610/// The intrinsics currently supported by callbr are implicit control flow
3611/// intrinsics such as amdgcn.kill.
3612/// - they should be called (no "dontcall-" attributes)
3613/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3614/// - they do not need custom argument handling (no
3615/// TLI.CollectTargetIntrinsicOperands())
3616void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3617#ifndef NDEBUG
3619 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3620 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3621 assert(Infos.empty() && "Intrinsic touches memory");
3622#endif
3623
3624 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3625
3627 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3628 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3629
3630 // Create the node.
3631 SDValue Result =
3632 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3633 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3634
3635 setValue(&I, Result);
3636}
3637
3638void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3639 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3640
3641 if (I.isInlineAsm()) {
3642 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3643 // have to do anything here to lower funclet bundles.
3644 failForInvalidBundles(I, "callbrs",
3646 visitInlineAsm(I);
3647 } else {
3648 assert(!I.hasOperandBundles() &&
3649 "Can't have operand bundles for intrinsics");
3650 visitCallBrIntrinsic(I);
3651 }
3653
3654 // Retrieve successors.
3655 SmallPtrSet<BasicBlock *, 8> Dests;
3656 Dests.insert(I.getDefaultDest());
3657 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3658
3659 // Update successor info.
3660 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3661 // TODO: For most of the cases where there is an intrinsic callbr, we're
3662 // having exactly one indirect target, which will be unreachable. As soon as
3663 // this changes, we might need to enhance
3664 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3665 // intrinsic indirect branches.
3666 if (I.isInlineAsm()) {
3667 for (BasicBlock *Dest : I.getIndirectDests()) {
3668 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3669 Target->setIsInlineAsmBrIndirectTarget();
3670 // If we introduce a type of asm goto statement that is permitted to use
3671 // an indirect call instruction to jump to its labels, then we should add
3672 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3673 // target block as requiring a BTI.
3674
3675 Target->setLabelMustBeEmitted();
3676 // Don't add duplicate machine successors.
3677 if (Dests.insert(Dest).second)
3678 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3679 }
3680 }
3681 CallBrMBB->normalizeSuccProbs();
3682
3683 // Drop into default successor.
3684 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3685 MVT::Other, getControlRoot(),
3686 DAG.getBasicBlock(Return)));
3687}
3688
3689void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3690 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3691}
3692
3693void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3694 assert(FuncInfo.MBB->isEHPad() &&
3695 "Call to landingpad not in landing pad!");
3696
3697 // If there aren't registers to copy the values into (e.g., during SjLj
3698 // exceptions), then don't bother to create these DAG nodes.
3699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3700 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3701 if (TLI.getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn) ==
3702 0 &&
3703 TLI.getExceptionSelectorRegister(FuncInfo.ExceptionModel,
3704 PersonalityFn) == 0)
3705 return;
3706
3707 // If landingpad's return type is token type, we don't create DAG nodes
3708 // for its exception pointer and selector value. The extraction of exception
3709 // pointer or selector value from token type landingpads is not currently
3710 // supported.
3711 if (LP.getType()->isTokenTy())
3712 return;
3713
3714 // LangRef leaves the result type target-specific, so diagnose types this
3715 // lowering cannot represent instead of asserting.
3716 SDLoc dl = getCurSDLoc();
3718 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
3719 *LP.getFunction(),
3720 "landingpad result type must be a struct of an exception pointer and "
3721 "an integer selector",
3722 dl.getDebugLoc()));
3723 setValueToPoison(&LP, dl);
3724 return;
3725 }
3726
3727 SmallVector<EVT, 2> ValueVTs;
3728 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3729 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3730
3731 // Get the two live-in registers as SDValues. The physregs have already been
3732 // copied into virtual registers.
3733 SDValue Ops[2];
3734 if (FuncInfo.ExceptionPointerVirtReg) {
3735 Ops[0] = DAG.getZExtOrTrunc(
3736 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3737 FuncInfo.ExceptionPointerVirtReg,
3738 TLI.getPointerTy(DAG.getDataLayout())),
3739 dl, ValueVTs[0]);
3740 } else {
3741 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3742 }
3743 Ops[1] = DAG.getZExtOrTrunc(
3744 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3745 FuncInfo.ExceptionSelectorVirtReg,
3746 TLI.getPointerTy(DAG.getDataLayout())),
3747 dl, ValueVTs[1]);
3748
3749 // Merge into one.
3750 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3751 DAG.getVTList(ValueVTs), Ops);
3752 setValue(&LP, Res);
3753}
3754
3757 // Update JTCases.
3758 for (JumpTableBlock &JTB : SL->JTCases)
3759 if (JTB.first.HeaderBB == First)
3760 JTB.first.HeaderBB = Last;
3761
3762 // Update BitTestCases.
3763 for (BitTestBlock &BTB : SL->BitTestCases)
3764 if (BTB.Parent == First)
3765 BTB.Parent = Last;
3766}
3767
3768void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3769 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3770
3771 // Update machine-CFG edges with unique successors.
3773 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3774 BasicBlock *BB = I.getSuccessor(i);
3775 bool Inserted = Done.insert(BB).second;
3776 if (!Inserted)
3777 continue;
3778
3779 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3780 addSuccessorWithProb(IndirectBrMBB, Succ);
3781 }
3782 IndirectBrMBB->normalizeSuccProbs();
3783
3785 MVT::Other, getControlRoot(),
3786 getValue(I.getAddress())));
3787}
3788
3789void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3790 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3791 DAG.getTarget().Options.NoTrapAfterNoreturn))
3792 return;
3793
3794 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3795}
3796
3797void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3798 SDNodeFlags Flags;
3799 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3800 Flags.copyFMF(*FPOp);
3801
3802 SDValue Op = getValue(I.getOperand(0));
3803 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3804 Op, Flags);
3805 setValue(&I, UnNodeValue);
3806}
3807
3808void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3809 SDNodeFlags Flags;
3810 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3811 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3812 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3813 }
3814 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3815 Flags.setExact(ExactOp->isExact());
3816 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3817 Flags.setDisjoint(DisjointOp->isDisjoint());
3818 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3819 Flags.copyFMF(*FPOp);
3820
3821 SDValue Op1 = getValue(I.getOperand(0));
3822 SDValue Op2 = getValue(I.getOperand(1));
3823 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3824 Op1, Op2, Flags);
3825 setValue(&I, BinNodeValue);
3826}
3827
3828void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3829 SDValue Op1 = getValue(I.getOperand(0));
3830 SDValue Op2 = getValue(I.getOperand(1));
3831
3832 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3833 Op1.getValueType(), DAG.getDataLayout());
3834
3835 // Coerce the shift amount to the right type if we can. This exposes the
3836 // truncate or zext to optimization early.
3837 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3839 "Unexpected shift type");
3840 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3841 }
3842
3843 bool nuw = false;
3844 bool nsw = false;
3845 bool exact = false;
3846
3847 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3848
3849 if (const OverflowingBinaryOperator *OFBinOp =
3851 nuw = OFBinOp->hasNoUnsignedWrap();
3852 nsw = OFBinOp->hasNoSignedWrap();
3853 }
3854 if (const PossiblyExactOperator *ExactOp =
3856 exact = ExactOp->isExact();
3857 }
3858 SDNodeFlags Flags;
3859 Flags.setExact(exact);
3860 Flags.setNoSignedWrap(nsw);
3861 Flags.setNoUnsignedWrap(nuw);
3862 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3863 Flags);
3864 setValue(&I, Res);
3865}
3866
3867void SelectionDAGBuilder::visitSDiv(const User &I) {
3868 SDValue Op1 = getValue(I.getOperand(0));
3869 SDValue Op2 = getValue(I.getOperand(1));
3870
3871 SDNodeFlags Flags;
3872 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3873 cast<PossiblyExactOperator>(&I)->isExact());
3874 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3875 Op2, Flags));
3876}
3877
3878void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3879 ICmpInst::Predicate predicate = I.getPredicate();
3880 SDValue Op1 = getValue(I.getOperand(0));
3881 SDValue Op2 = getValue(I.getOperand(1));
3882 ISD::CondCode Opcode = getICmpCondCode(predicate);
3883
3884 auto &TLI = DAG.getTargetLoweringInfo();
3885 EVT MemVT =
3886 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3887
3888 // If a pointer's DAG type is larger than its memory type then the DAG values
3889 // are zero-extended. This breaks signed comparisons so truncate back to the
3890 // underlying type before doing the compare.
3891 if (Op1.getValueType() != MemVT) {
3892 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3893 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3894 }
3895
3896 SDNodeFlags Flags;
3897 Flags.setSameSign(I.hasSameSign());
3898
3899 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3900 I.getType());
3901 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3902 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3903}
3904
3905void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3906 FCmpInst::Predicate predicate = I.getPredicate();
3907 SDValue Op1 = getValue(I.getOperand(0));
3908 SDValue Op2 = getValue(I.getOperand(1));
3909
3910 ISD::CondCode Condition = getFCmpCondCode(predicate);
3911 auto *FPMO = cast<FPMathOperator>(&I);
3912 if (FPMO->hasNoNaNs() ||
3913 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3914 Condition = getFCmpCodeWithoutNaN(Condition);
3915
3916 SDNodeFlags Flags;
3917 Flags.copyFMF(*FPMO);
3918
3919 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3920 I.getType());
3921 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3922 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3923}
3924
3925// Check if the condition of the select has one use or two users that are both
3926// selects with the same condition.
3927static bool hasOnlySelectUsers(const Value *Cond) {
3928 return llvm::all_of(Cond->users(), [](const Value *V) {
3929 return isa<SelectInst>(V);
3930 });
3931}
3932
3933void SelectionDAGBuilder::visitSelect(const User &I) {
3934 SmallVector<EVT, 4> ValueVTs;
3935 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3936 ValueVTs);
3937 unsigned NumValues = ValueVTs.size();
3938 if (NumValues == 0) return;
3939
3941 SDValue Cond = getValue(I.getOperand(0));
3942 SDValue LHSVal = getValue(I.getOperand(1));
3943 SDValue RHSVal = getValue(I.getOperand(2));
3944 SmallVector<SDValue, 1> BaseOps(1, Cond);
3946 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3947
3948 bool IsUnaryAbs = false;
3949 bool Negate = false;
3950
3951 SDNodeFlags Flags;
3952 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3953 Flags.copyFMF(*FPOp);
3954
3955 Flags.setUnpredictable(
3956 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3957
3958 // Min/max matching is only viable if all output VTs are the same.
3959 if (all_equal(ValueVTs)) {
3960 EVT VT = ValueVTs[0];
3961 LLVMContext &Ctx = *DAG.getContext();
3962 auto &TLI = DAG.getTargetLoweringInfo();
3963
3964 // We care about the legality of the operation after it has been type
3965 // legalized.
3966 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3967 VT = TLI.getTypeToTransformTo(Ctx, VT);
3968
3969 // If the vselect is legal, assume we want to leave this as a vector setcc +
3970 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3971 // min/max is legal on the scalar type.
3972 bool UseScalarMinMax = VT.isVector() &&
3974
3975 // ValueTracking's select pattern matching does not account for -0.0,
3976 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3977 // -0.0 is less than +0.0.
3978 const Value *LHS, *RHS;
3979 auto SPR = matchSelectPattern(&I, LHS, RHS);
3981 switch (SPR.Flavor) {
3982 case SPF_UMAX: Opc = ISD::UMAX; break;
3983 case SPF_UMIN: Opc = ISD::UMIN; break;
3984 case SPF_SMAX: Opc = ISD::SMAX; break;
3985 case SPF_SMIN: Opc = ISD::SMIN; break;
3986 case SPF_FMINNUM:
3988 break;
3989
3990 switch (SPR.NaNBehavior) {
3991 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3992 case SPNB_RETURNS_ANY:
3993 case SPNB_RETURNS_NAN:
3994 break;
3995 case SPNB_RETURNS_OTHER:
3997 Flags.setNoSignedZeros(true);
3998 break;
3999 }
4000 break;
4001 case SPF_FMAXNUM:
4003 break;
4004
4005 switch (SPR.NaNBehavior) {
4006 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
4007 case SPNB_RETURNS_NAN:
4008 case SPNB_RETURNS_ANY:
4009 break;
4010 case SPNB_RETURNS_OTHER:
4012 Flags.setNoSignedZeros(true);
4013 break;
4014 }
4015 break;
4016 case SPF_NABS:
4017 Negate = true;
4018 [[fallthrough]];
4019 case SPF_ABS:
4020 IsUnaryAbs = true;
4021 Opc = ISD::ABS;
4022 break;
4023 default: break;
4024 }
4025
4026 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
4027 (TLI.isOperationLegalOrCustom(Opc, VT) ||
4028 (UseScalarMinMax &&
4030 // If the underlying comparison instruction is used by any other
4031 // instruction, the consumed instructions won't be destroyed, so it is
4032 // not profitable to convert to a min/max.
4034 OpCode = Opc;
4035 LHSVal = getValue(LHS);
4036 RHSVal = getValue(RHS);
4037 BaseOps.clear();
4038 }
4039
4040 if (IsUnaryAbs) {
4041 OpCode = Opc;
4042 LHSVal = getValue(LHS);
4043 BaseOps.clear();
4044 }
4045 }
4046
4047 if (IsUnaryAbs) {
4048 for (unsigned i = 0; i != NumValues; ++i) {
4049 SDLoc dl = getCurSDLoc();
4050 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
4051 Values[i] =
4052 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
4053 if (Negate)
4054 Values[i] = DAG.getNegative(Values[i], dl, VT);
4055 }
4056 } else {
4057 for (unsigned i = 0; i != NumValues; ++i) {
4058 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
4059 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
4060 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
4061 Values[i] = DAG.getNode(
4062 OpCode, getCurSDLoc(),
4063 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
4064 }
4065 }
4066
4068 DAG.getVTList(ValueVTs), Values));
4069}
4070
4071void SelectionDAGBuilder::visitTrunc(const User &I) {
4072 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4073 SDValue N = getValue(I.getOperand(0));
4074 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4075 I.getType());
4076 SDNodeFlags Flags;
4077 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4078 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4079 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4080 }
4081
4082 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4083}
4084
4085void SelectionDAGBuilder::visitZExt(const User &I) {
4086 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4087 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4088 SDValue N = getValue(I.getOperand(0));
4089 auto &TLI = DAG.getTargetLoweringInfo();
4090 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4091
4092 SDNodeFlags Flags;
4093 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4094 Flags.setNonNeg(PNI->hasNonNeg());
4095
4096 // Eagerly use nonneg information to canonicalize towards sign_extend if
4097 // that is the target's preference.
4098 // TODO: Let the target do this later.
4099 if (Flags.hasNonNeg() &&
4100 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4101 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4102 return;
4103 }
4104
4105 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4106}
4107
4108void SelectionDAGBuilder::visitSExt(const User &I) {
4109 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4110 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4111 SDValue N = getValue(I.getOperand(0));
4112 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4113 I.getType());
4114 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4115}
4116
4117void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4118 // FPTrunc is never a no-op cast, no need to check
4119 SDValue N = getValue(I.getOperand(0));
4120 SDLoc dl = getCurSDLoc();
4121 SDNodeFlags Flags;
4122 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4123 Flags.copyFMF(*FPOp);
4124 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4125 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4126 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4127 DAG.getTargetConstant(
4128 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4129 Flags));
4130}
4131
4132void SelectionDAGBuilder::visitFPExt(const User &I) {
4133 // FPExt is never a no-op cast, no need to check
4134 SDValue N = getValue(I.getOperand(0));
4135 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4136 I.getType());
4137 SDNodeFlags Flags;
4138 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4139 Flags.copyFMF(*FPOp);
4140 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4141}
4142
4143void SelectionDAGBuilder::visitFPToUI(const User &I) {
4144 // FPToUI is never a no-op cast, no need to check
4145 SDValue N = getValue(I.getOperand(0));
4146 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4147 I.getType());
4148 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4149}
4150
4151void SelectionDAGBuilder::visitFPToSI(const User &I) {
4152 // FPToSI is never a no-op cast, no need to check
4153 SDValue N = getValue(I.getOperand(0));
4154 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4155 I.getType());
4156 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4157}
4158
4159void SelectionDAGBuilder::visitUIToFP(const User &I) {
4160 // UIToFP is never a no-op cast, no need to check
4161 SDValue N = getValue(I.getOperand(0));
4162 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4163 I.getType());
4164 SDNodeFlags Flags;
4165 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4166 Flags.copyFMF(*cast<FPMathOperator>(&I));
4167
4168 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4169}
4170
4171void SelectionDAGBuilder::visitSIToFP(const User &I) {
4172 // SIToFP is never a no-op cast, no need to check
4173 SDValue N = getValue(I.getOperand(0));
4174 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4175 I.getType());
4176 SDNodeFlags Flags;
4177 Flags.copyFMF(*cast<FPMathOperator>(&I));
4178
4179 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4180}
4181
4182void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4183 SDValue N = getValue(I.getOperand(0));
4184 // By definition the type of the ptrtoaddr must be equal to the address type.
4185 const auto &TLI = DAG.getTargetLoweringInfo();
4186 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4187 // The address width must be smaller or equal to the pointer representation
4188 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4189 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4190 setValue(&I, N);
4191}
4192
4193void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4194 // What to do depends on the size of the integer and the size of the pointer.
4195 // We can either truncate, zero extend, or no-op, accordingly.
4196 SDValue N = getValue(I.getOperand(0));
4197 auto &TLI = DAG.getTargetLoweringInfo();
4198 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4199 I.getType());
4200 EVT PtrMemVT =
4201 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4202 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4203 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4204 setValue(&I, N);
4205}
4206
4207void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4208 // What to do depends on the size of the integer and the size of the pointer.
4209 // We can either truncate, zero extend, or no-op, accordingly.
4210 SDValue N = getValue(I.getOperand(0));
4211 auto &TLI = DAG.getTargetLoweringInfo();
4212 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4213 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4214 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4215 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4216 setValue(&I, N);
4217}
4218
4219void SelectionDAGBuilder::visitBitCast(const User &I) {
4220 SDValue N = getValue(I.getOperand(0));
4221 SDLoc dl = getCurSDLoc();
4222 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4223 I.getType());
4224
4225 // BitCast assures us that source and destination are the same size so this is
4226 // either a BITCAST or a no-op.
4227 if (DestVT != N.getValueType())
4228 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4229 DestVT, N)); // convert types.
4230 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4231 // might fold any kind of constant expression to an integer constant and that
4232 // is not what we are looking for. Only recognize a bitcast of a genuine
4233 // constant integer as an opaque constant.
4234 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4235 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4236 /*isOpaque*/true));
4237 else
4238 setValue(&I, N); // noop cast.
4239}
4240
4241void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4242 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4243 const Value *SV = I.getOperand(0);
4244 SDValue N = getValue(SV);
4245 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4246
4247 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4248 unsigned DestAS = I.getType()->getPointerAddressSpace();
4249
4250 if (!TM.isNoopAddrSpaceCast(DAG.getDataLayout(), SrcAS, DestAS)) {
4251 SDNodeFlags Flags;
4252 if (const auto *ASC = dyn_cast<AddrSpaceCastInst>(&I))
4253 Flags.setNonNull(ASC->hasNonNull());
4254 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS, Flags);
4255 }
4256
4257 setValue(&I, N);
4258}
4259
4260void SelectionDAGBuilder::visitInsertElement(const User &I) {
4261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4262 SDValue InVec = getValue(I.getOperand(0));
4263 SDValue InVal = getValue(I.getOperand(1));
4264 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4265 TLI.getVectorIdxTy(DAG.getDataLayout()));
4267 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4268 InVec, InVal, InIdx));
4269}
4270
4271void SelectionDAGBuilder::visitBitInsert(const User &I) {
4272 SDValue Base = getValue(I.getOperand(0));
4273 SDValue Val = getValue(I.getOperand(1));
4274 SDValue Offset = getValue(I.getOperand(2));
4275 EVT BaseVT = Base.getValueType();
4276 EVT ValVT = Val.getValueType();
4277 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4278 SDLoc dl = getCurSDLoc();
4279
4280 assert(BaseVT.getSizeInBits() >= ValVT.getSizeInBits() &&
4281 "bitinsert val wider than base should be rejected by verifier");
4282
4283 // If Val is a float, cast it to an integer of the same bitwidth
4284 // so DAG.getZExtOrTrunc can process it safely.
4285 if (!ValVT.isInteger()) {
4286 ValVT = ValVT.changeTypeToInteger();
4287 Val = DAG.getBitcast(ValVT, Val);
4288 }
4289
4290 // Legalize shift amount to the target's shift amount type.
4291 EVT ShiftAmtTy = TLI.getShiftAmountTy(BaseVT, DAG.getDataLayout());
4292 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4293
4294 unsigned BaseBitWidth = BaseVT.getScalarSizeInBits();
4295 unsigned ValBitWidth = ValVT.getScalarSizeInBits();
4296 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4297 SDValue ShiftedMask =
4298 DAG.getNode(ISD::SHL, dl, BaseVT, DAG.getConstant(InsertMask, dl, BaseVT),
4299 LegalShiftAmount);
4300 SDValue ClearMask = DAG.getNOT(dl, ShiftedMask, BaseVT);
4301 SDValue ClearedBase = DAG.getNode(ISD::AND, dl, BaseVT, Base, ClearMask);
4302
4303 SDValue ExtVal = DAG.getZExtOrTrunc(Val, dl, BaseVT);
4304 SDValue ShiftedVal =
4305 DAG.getNode(ISD::SHL, dl, BaseVT, ExtVal, LegalShiftAmount);
4306 SDValue Result = DAG.getNode(ISD::OR, dl, BaseVT, ClearedBase, ShiftedVal);
4307 setValue(&I, Result);
4308}
4309
4310void SelectionDAGBuilder::visitBitExtract(const User &I) {
4311 SDValue Src = getValue(I.getOperand(0));
4312 SDValue Offset = getValue(I.getOperand(1));
4313 EVT SrcVT = Src.getValueType();
4314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4315 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4316 SDLoc dl = getCurSDLoc();
4317
4318 assert(ResultVT.getSizeInBits() <= SrcVT.getSizeInBits() &&
4319 "bitextract result wider than source should be rejected by verifier");
4320
4321 // Legalize shift amount to the target's shift amount type.
4322 EVT ShiftAmtTy = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
4323 SDValue LegalShiftAmount = DAG.getZExtOrTrunc(Offset, dl, ShiftAmtTy);
4324
4325 // Shift right by Offset - brings target field to bit 0
4326 SDValue Shifted = DAG.getNode(ISD::SRL, dl, SrcVT, Src, LegalShiftAmount);
4327
4328 SDValue Result;
4329 if (!ResultVT.isInteger()) {
4330 // Drop into the integer domain to safely truncate the shifted bits
4331 EVT IntResultVT = ResultVT.changeTypeToInteger();
4332 Result = DAG.getNode(ISD::TRUNCATE, dl, IntResultVT, Shifted);
4333 Result = DAG.getBitcast(ResultVT, Result);
4334 } else {
4335 // Normal integer path
4336 Result = DAG.getNode(ISD::TRUNCATE, dl, ResultVT, Shifted);
4337 }
4338
4339 setValue(&I, Result);
4340}
4341
4342void SelectionDAGBuilder::visitExtractElement(const User &I) {
4343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4344 SDValue InVec = getValue(I.getOperand(0));
4345 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4346 TLI.getVectorIdxTy(DAG.getDataLayout()));
4348 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4349 InVec, InIdx));
4350}
4351
4352void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4353 SDValue Src1 = getValue(I.getOperand(0));
4354 SDValue Src2 = getValue(I.getOperand(1));
4355 ArrayRef<int> Mask;
4356 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4357 Mask = SVI->getShuffleMask();
4358 else
4359 Mask = cast<ConstantExpr>(I).getShuffleMask();
4360 SDLoc DL = getCurSDLoc();
4361 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4362 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4363 EVT SrcVT = Src1.getValueType();
4364
4365 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4366 // Canonical splat form of first element of first input vector.
4367 SDValue FirstElt =
4368 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4369 DAG.getVectorIdxConstant(0, DL));
4370 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4371 return;
4372 }
4373
4374 // For now, we only handle splats for scalable vectors.
4375 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4376 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4377 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4378
4379 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4380 unsigned MaskNumElts = Mask.size();
4381
4382 if (SrcNumElts == MaskNumElts) {
4383 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4384 return;
4385 }
4386
4387 // Normalize the shuffle vector since mask and vector length don't match.
4388 if (SrcNumElts < MaskNumElts) {
4389 // Mask is longer than the source vectors. We can use concatenate vector to
4390 // make the mask and vectors lengths match.
4391
4392 if (MaskNumElts % SrcNumElts == 0) {
4393 // Mask length is a multiple of the source vector length.
4394 // Check if the shuffle is some kind of concatenation of the input
4395 // vectors.
4396 unsigned NumConcat = MaskNumElts / SrcNumElts;
4397 bool IsConcat = true;
4398 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4399 for (unsigned i = 0; i != MaskNumElts; ++i) {
4400 int Idx = Mask[i];
4401 if (Idx < 0)
4402 continue;
4403 // Ensure the indices in each SrcVT sized piece are sequential and that
4404 // the same source is used for the whole piece.
4405 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4406 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4407 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4408 IsConcat = false;
4409 break;
4410 }
4411 // Remember which source this index came from.
4412 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4413 }
4414
4415 // The shuffle is concatenating multiple vectors together. Just emit
4416 // a CONCAT_VECTORS operation.
4417 if (IsConcat) {
4418 SmallVector<SDValue, 8> ConcatOps;
4419 for (auto Src : ConcatSrcs) {
4420 if (Src < 0)
4421 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4422 else if (Src == 0)
4423 ConcatOps.push_back(Src1);
4424 else
4425 ConcatOps.push_back(Src2);
4426 }
4427 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4428 return;
4429 }
4430 }
4431
4432 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4433 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4434 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4435 PaddedMaskNumElts);
4436
4437 // Pad both vectors with undefs to make them the same length as the mask.
4438 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4439
4440 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4441 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4442 MOps1[0] = Src1;
4443 MOps2[0] = Src2;
4444
4445 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4446 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4447
4448 // Readjust mask for new input vector length.
4449 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4450 for (unsigned i = 0; i != MaskNumElts; ++i) {
4451 int Idx = Mask[i];
4452 if (Idx >= (int)SrcNumElts)
4453 Idx -= SrcNumElts - PaddedMaskNumElts;
4454 MappedOps[i] = Idx;
4455 }
4456
4457 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4458
4459 // If the concatenated vector was padded, extract a subvector with the
4460 // correct number of elements.
4461 if (MaskNumElts != PaddedMaskNumElts)
4462 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4463 DAG.getVectorIdxConstant(0, DL));
4464
4465 setValue(&I, Result);
4466 return;
4467 }
4468
4469 assert(SrcNumElts > MaskNumElts);
4470
4471 // Analyze the access pattern of the vector to see if we can extract
4472 // two subvectors and do the shuffle.
4473 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4474 bool CanExtract = true;
4475 for (int Idx : Mask) {
4476 unsigned Input = 0;
4477 if (Idx < 0)
4478 continue;
4479
4480 if (Idx >= (int)SrcNumElts) {
4481 Input = 1;
4482 Idx -= SrcNumElts;
4483 }
4484
4485 // If all the indices come from the same MaskNumElts sized portion of
4486 // the sources we can use extract. Also make sure the extract wouldn't
4487 // extract past the end of the source.
4488 int NewStartIdx = alignDown(Idx, MaskNumElts);
4489 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4490 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4491 CanExtract = false;
4492 // Make sure we always update StartIdx as we use it to track if all
4493 // elements are undef.
4494 StartIdx[Input] = NewStartIdx;
4495 }
4496
4497 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4498 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4499 return;
4500 }
4501 if (CanExtract) {
4502 // Extract appropriate subvector and generate a vector shuffle
4503 for (unsigned Input = 0; Input < 2; ++Input) {
4504 SDValue &Src = Input == 0 ? Src1 : Src2;
4505 if (StartIdx[Input] < 0)
4506 Src = DAG.getUNDEF(VT);
4507 else {
4508 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4509 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4510 }
4511 }
4512
4513 // Calculate new mask.
4514 SmallVector<int, 8> MappedOps(Mask);
4515 for (int &Idx : MappedOps) {
4516 if (Idx >= (int)SrcNumElts)
4517 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4518 else if (Idx >= 0)
4519 Idx -= StartIdx[0];
4520 }
4521
4522 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4523 return;
4524 }
4525
4526 // We can't use either concat vectors or extract subvectors so fall back to
4527 // replacing the shuffle with extract and build vector.
4528 // to insert and build vector.
4529 EVT EltVT = VT.getVectorElementType();
4531 for (int Idx : Mask) {
4532 SDValue Res;
4533
4534 if (Idx < 0) {
4535 Res = DAG.getUNDEF(EltVT);
4536 } else {
4537 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4538 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4539
4540 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4541 DAG.getVectorIdxConstant(Idx, DL));
4542 }
4543
4544 Ops.push_back(Res);
4545 }
4546
4547 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4548}
4549
4550void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4551 ArrayRef<unsigned> Indices = I.getIndices();
4552 const Value *Op0 = I.getOperand(0);
4553 const Value *Op1 = I.getOperand(1);
4554 Type *AggTy = I.getType();
4555 Type *ValTy = Op1->getType();
4556 bool IntoUndef = isa<UndefValue>(Op0);
4557 bool FromUndef = isa<UndefValue>(Op1);
4558
4559 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4560
4561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4562 SmallVector<EVT, 4> AggValueVTs;
4563 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4564 SmallVector<EVT, 4> ValValueVTs;
4565 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4566
4567 unsigned NumAggValues = AggValueVTs.size();
4568 unsigned NumValValues = ValValueVTs.size();
4569 SmallVector<SDValue, 4> Values(NumAggValues);
4570
4571 // Ignore an insertvalue that produces an empty object
4572 if (!NumAggValues) {
4573 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4574 return;
4575 }
4576
4577 SDValue Agg = getValue(Op0);
4578 unsigned i = 0;
4579 // Copy the beginning value(s) from the original aggregate.
4580 for (; i != LinearIndex; ++i)
4581 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4582 SDValue(Agg.getNode(), Agg.getResNo() + i);
4583 // Copy values from the inserted value(s).
4584 if (NumValValues) {
4585 SDValue Val = getValue(Op1);
4586 for (; i != LinearIndex + NumValValues; ++i)
4587 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4588 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4589 }
4590 // Copy remaining value(s) from the original aggregate.
4591 for (; i != NumAggValues; ++i)
4592 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4593 SDValue(Agg.getNode(), Agg.getResNo() + i);
4594
4596 DAG.getVTList(AggValueVTs), Values));
4597}
4598
4599void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4600 ArrayRef<unsigned> Indices = I.getIndices();
4601 const Value *Op0 = I.getOperand(0);
4602 Type *AggTy = Op0->getType();
4603 Type *ValTy = I.getType();
4604 bool OutOfUndef = isa<UndefValue>(Op0);
4605
4606 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4607
4608 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4609 SmallVector<EVT, 4> ValValueVTs;
4610 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4611
4612 unsigned NumValValues = ValValueVTs.size();
4613
4614 // Ignore a extractvalue that produces an empty object
4615 if (!NumValValues) {
4616 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4617 return;
4618 }
4619
4620 SmallVector<SDValue, 4> Values(NumValValues);
4621
4622 SDValue Agg = getValue(Op0);
4623 // Copy out the selected value(s).
4624 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4625 Values[i - LinearIndex] =
4626 OutOfUndef ?
4627 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4628 SDValue(Agg.getNode(), Agg.getResNo() + i);
4629
4631 DAG.getVTList(ValValueVTs), Values));
4632}
4633
4634void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4635 Value *Op0 = I.getOperand(0);
4636 // Note that the pointer operand may be a vector of pointers. Take the scalar
4637 // element which holds a pointer.
4638 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4639 SDValue N = getValue(Op0);
4640 SDLoc dl = getCurSDLoc();
4641 auto &TLI = DAG.getTargetLoweringInfo();
4642 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4643
4644 // For a vector GEP, keep the prefix scalar as long as possible, then
4645 // convert any scalars encountered after the first vector operand to vectors.
4646 bool IsVectorGEP = I.getType()->isVectorTy();
4647 ElementCount VectorElementCount =
4648 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4650
4652 GTI != E; ++GTI) {
4653 const Value *Idx = GTI.getOperand();
4654 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4655 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4656 if (Field) {
4657 // N = N + Offset
4659 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4660
4661 // In an inbounds GEP with an offset that is nonnegative even when
4662 // interpreted as signed, assume there is no unsigned overflow.
4663 SDNodeFlags Flags;
4664 if (NW.hasNoUnsignedWrap() ||
4665 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4667 Flags.setInBounds(NW.isInBounds());
4668
4669 N = DAG.getMemBasePlusOffset(
4670 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4671 }
4672 } else {
4673 // IdxSize is the width of the arithmetic according to IR semantics.
4674 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4675 // (and fix up the result later).
4676 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4677 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4678 TypeSize ElementSize =
4679 GTI.getSequentialElementStride(DAG.getDataLayout());
4680 // We intentionally mask away the high bits here; ElementSize may not
4681 // fit in IdxTy.
4682 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4683 /*isSigned=*/false, /*implicitTrunc=*/true);
4684 bool ElementScalable = ElementSize.isScalable();
4685
4686 // If this is a scalar constant or a splat vector of constants,
4687 // handle it quickly.
4688 const auto *C = dyn_cast<Constant>(Idx);
4689 if (C && isa<VectorType>(C->getType()))
4690 C = C->getSplatValue();
4691
4692 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4693 if (CI && CI->isZero())
4694 continue;
4695 if (CI && !ElementScalable) {
4696 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4697 LLVMContext &Context = *DAG.getContext();
4698 SDValue OffsVal;
4699 if (N.getValueType().isVector())
4700 OffsVal = DAG.getConstant(
4701 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4702 else
4703 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4704
4705 // In an inbounds GEP with an offset that is nonnegative even when
4706 // interpreted as signed, assume there is no unsigned overflow.
4707 SDNodeFlags Flags;
4708 if (NW.hasNoUnsignedWrap() ||
4709 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4710 Flags.setNoUnsignedWrap(true);
4711 Flags.setInBounds(NW.isInBounds());
4712
4713 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4714
4715 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4716 continue;
4717 }
4718
4719 // N = N + Idx * ElementMul;
4720 SDValue IdxN = getValue(Idx);
4721
4722 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4723 if (N.getValueType().isVector()) {
4724 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4725 VectorElementCount);
4726 IdxN = DAG.getSplat(VT, dl, IdxN);
4727 } else {
4728 EVT VT =
4729 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4730 N = DAG.getSplat(VT, dl, N);
4731 }
4732 }
4733
4734 // If the index is smaller or larger than intptr_t, truncate or extend
4735 // it.
4736 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4737
4738 SDNodeFlags ScaleFlags;
4739 // The multiplication of an index by the type size does not wrap the
4740 // pointer index type in a signed sense (mul nsw).
4742
4743 // The multiplication of an index by the type size does not wrap the
4744 // pointer index type in an unsigned sense (mul nuw).
4745 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4746
4747 if (ElementScalable) {
4748 EVT VScaleTy = N.getValueType().getScalarType();
4749 SDValue VScale = DAG.getNode(
4750 ISD::VSCALE, dl, VScaleTy,
4751 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4752 if (N.getValueType().isVector())
4753 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4754 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4755 ScaleFlags);
4756 } else {
4757 // If this is a multiply by a power of two, turn it into a shl
4758 // immediately. This is a very common case.
4759 if (ElementMul != 1) {
4760 if (ElementMul.isPowerOf2()) {
4761 unsigned Amt = ElementMul.logBase2();
4762 IdxN = DAG.getNode(
4763 ISD::SHL, dl, N.getValueType(), IdxN,
4764 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4765 ScaleFlags);
4766 } else {
4767 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4768 IdxN.getValueType());
4769 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4770 ScaleFlags);
4771 }
4772 }
4773 }
4774
4775 // The successive addition of the current address, truncated to the
4776 // pointer index type and interpreted as an unsigned number, and each
4777 // offset, also interpreted as an unsigned number, does not wrap the
4778 // pointer index type (add nuw).
4779 SDNodeFlags AddFlags;
4780 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4781 AddFlags.setInBounds(NW.isInBounds());
4782
4783 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4784 }
4785 }
4786
4787 if (IsVectorGEP && !N.getValueType().isVector()) {
4788 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4789 N = DAG.getSplat(VT, dl, N);
4790 }
4791
4792 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4793 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4794 if (IsVectorGEP) {
4795 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4796 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4797 }
4798
4799 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4800 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4801
4802 setValue(&I, N);
4803}
4804
4805void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4806 // If this is a fixed sized alloca in the entry block of the function,
4807 // allocate it statically on the stack.
4808 if (FuncInfo.StaticAllocaMap.count(&I))
4809 return; // getValue will auto-populate this.
4810
4811 SDLoc dl = getCurSDLoc();
4812 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4813 auto &DL = DAG.getDataLayout();
4814 TypeSize TySize = I.getAllocationBaseSize(DL);
4815 MaybeAlign Alignment = I.getAlign();
4816
4817 SDValue AllocSize = getValue(I.getArraySize());
4818
4819 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4820 if (AllocSize.getValueType() != IntPtr)
4821 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4822
4823 AllocSize = DAG.getNode(
4824 ISD::MUL, dl, IntPtr, AllocSize,
4825 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4826
4827 // Handle alignment. If the requested alignment is less than or equal to
4828 // the stack alignment, ignore it. If the size is greater than or equal to
4829 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4830 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4831 if (*Alignment <= StackAlign)
4832 Alignment = std::nullopt;
4833
4834 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4835 // Round the size of the allocation up to the stack alignment size
4836 // by add SA-1 to the size. This doesn't overflow because we're computing
4837 // an address inside an alloca.
4838 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4839 DAG.getConstant(StackAlignMask, dl, IntPtr),
4841
4842 // Mask out the low bits for alignment purposes.
4843 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4844 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4845
4846 SDValue Ops[] = {
4847 getRoot(), AllocSize,
4848 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4849 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4850 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4851 setValue(&I, DSA);
4852 DAG.setRoot(DSA.getValue(1));
4853
4854 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4855}
4856
4857static const MDNode *getRangeMetadata(const Instruction &I) {
4858 return I.getMetadata(LLVMContext::MD_range);
4859}
4860
4861static std::optional<ConstantRange> getRange(const Instruction &I) {
4862 if (const auto *CB = dyn_cast<CallBase>(&I))
4863 if (std::optional<ConstantRange> CR = CB->getRange())
4864 return CR;
4865 if (const MDNode *Range = getRangeMetadata(I))
4867 return std::nullopt;
4868}
4869
4871 if (const auto *CB = dyn_cast<CallBase>(&I))
4872 return CB->getRetNoFPClass();
4873 return fcNone;
4874}
4875
4876void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4877 if (I.isAtomic())
4878 return visitAtomicLoad(I);
4879
4880 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4881 const Value *SV = I.getOperand(0);
4882 if (TLI.supportSwiftError()) {
4883 // Swifterror values can come from either a function parameter with
4884 // swifterror attribute or an alloca with swifterror attribute.
4885 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4886 if (Arg->hasSwiftErrorAttr())
4887 return visitLoadFromSwiftError(I);
4888 }
4889
4890 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4891 if (Alloca->isSwiftError())
4892 return visitLoadFromSwiftError(I);
4893 }
4894 }
4895
4896 SDValue Ptr = getValue(SV);
4897
4898 Type *Ty = I.getType();
4899 SmallVector<EVT, 4> ValueVTs, MemVTs;
4901 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4902 unsigned NumValues = ValueVTs.size();
4903 if (NumValues == 0)
4904 return;
4905
4906 Align Alignment = I.getAlign();
4907 AAMDNodes AAInfo = I.getAAMetadata();
4908 const MDNode *Ranges = getRangeMetadata(I);
4909 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4910 bool isVolatile = I.isVolatile();
4911 MachineMemOperand::Flags MMOFlags =
4912 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4913
4914 SDValue Root;
4915 bool ConstantMemory = false;
4916 if (isVolatile)
4917 // Serialize volatile loads with other side effects.
4918 Root = getRoot();
4919 else if (NumValues > MaxParallelChains)
4920 Root = getMemoryRoot();
4921 else if (BatchAA &&
4922 BatchAA->pointsToConstantMemory(MemoryLocation(
4923 SV,
4924 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4925 AAInfo))) {
4926 // Do not serialize (non-volatile) loads of constant memory with anything.
4927 Root = DAG.getEntryNode();
4928 ConstantMemory = true;
4930 } else {
4931 // Do not serialize non-volatile loads against each other.
4932 Root = DAG.getRoot();
4933 }
4934
4935 SDLoc dl = getCurSDLoc();
4936
4937 if (isVolatile)
4938 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4939
4941 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4942
4943 unsigned ChainI = 0;
4944 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4945 // Serializing loads here may result in excessive register pressure, and
4946 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4947 // could recover a bit by hoisting nodes upward in the chain by recognizing
4948 // they are side-effect free or do not alias. The optimizer should really
4949 // avoid this case by converting large object/array copies to llvm.memcpy
4950 // (MaxParallelChains should always remain as failsafe).
4951 if (ChainI == MaxParallelChains) {
4952 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4953 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4954 ArrayRef(Chains.data(), ChainI));
4955 Root = Chain;
4956 ChainI = 0;
4957 }
4958
4959 // TODO: MachinePointerInfo only supports a fixed length offset.
4960 MachinePointerInfo PtrInfo =
4961 !Offsets[i].isScalable() || Offsets[i].isZero()
4962 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4963 : MachinePointerInfo();
4964
4965 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4966 SDValue L =
4967 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4968 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4969 Chains[ChainI] = L.getValue(1);
4970
4971 if (MemVTs[i] != ValueVTs[i])
4972 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4973
4974 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4975 uint64_t FPTestInt =
4976 cast<ConstantInt>(
4977 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
4978 ->getZExtValue();
4979 if (FPTestInt != fcNone) {
4980 SDValue FPTestConst =
4981 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
4982 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
4983 FPTestConst);
4984 }
4985 }
4986 Values[i] = L;
4987 }
4988
4989 if (!ConstantMemory) {
4990 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4991 ArrayRef(Chains.data(), ChainI));
4992 if (isVolatile)
4993 DAG.setRoot(Chain);
4994 else
4995 PendingLoads.push_back(Chain);
4996 }
4997
4998 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4999 DAG.getVTList(ValueVTs), Values));
5000}
5001
5002void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
5003 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5004 "call visitStoreToSwiftError when backend supports swifterror");
5005
5006 SmallVector<EVT, 4> ValueVTs;
5007 SmallVector<uint64_t, 4> Offsets;
5008 const Value *SrcV = I.getOperand(0);
5009 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5010 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5011 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5012 "expect a single EVT for swifterror");
5013
5014 SDValue Src = getValue(SrcV);
5015 // Create a virtual register, then update the virtual register.
5016 Register VReg =
5017 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
5018 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
5019 // Chain can be getRoot or getControlRoot.
5020 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
5021 SDValue(Src.getNode(), Src.getResNo()));
5022 DAG.setRoot(CopyNode);
5023}
5024
5025void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
5026 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
5027 "call visitLoadFromSwiftError when backend supports swifterror");
5028
5029 assert(!I.isVolatile() &&
5030 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
5031 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
5032 "Support volatile, non temporal, invariant for load_from_swift_error");
5033
5034 const Value *SV = I.getOperand(0);
5035 Type *Ty = I.getType();
5036 assert(
5037 (!BatchAA ||
5038 !BatchAA->pointsToConstantMemory(MemoryLocation(
5039 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
5040 I.getAAMetadata()))) &&
5041 "load_from_swift_error should not be constant memory");
5042
5043 SmallVector<EVT, 4> ValueVTs;
5044 SmallVector<uint64_t, 4> Offsets;
5045 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
5046 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
5047 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
5048 "expect a single EVT for swifterror");
5049
5050 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
5051 SDValue L = DAG.getCopyFromReg(
5052 getRoot(), getCurSDLoc(),
5053 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
5054
5055 setValue(&I, L);
5056}
5057
5058void SelectionDAGBuilder::visitStore(const StoreInst &I) {
5059 if (I.isAtomic())
5060 return visitAtomicStore(I);
5061
5062 const Value *SrcV = I.getOperand(0);
5063 const Value *PtrV = I.getOperand(1);
5064
5065 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5066 if (TLI.supportSwiftError()) {
5067 // Swifterror values can come from either a function parameter with
5068 // swifterror attribute or an alloca with swifterror attribute.
5069 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
5070 if (Arg->hasSwiftErrorAttr())
5071 return visitStoreToSwiftError(I);
5072 }
5073
5074 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
5075 if (Alloca->isSwiftError())
5076 return visitStoreToSwiftError(I);
5077 }
5078 }
5079
5080 SmallVector<EVT, 4> ValueVTs, MemVTs;
5082 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
5083 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
5084 unsigned NumValues = ValueVTs.size();
5085 if (NumValues == 0)
5086 return;
5087
5088 // Get the lowered operands. Note that we do this after
5089 // checking if NumResults is zero, because with zero results
5090 // the operands won't have values in the map.
5091 SDValue Src = getValue(SrcV);
5092 SDValue Ptr = getValue(PtrV);
5093
5094 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
5095 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
5096 SDLoc dl = getCurSDLoc();
5097 Align Alignment = I.getAlign();
5098 AAMDNodes AAInfo = I.getAAMetadata();
5099 const MDNode *MemCacheHint =
5100 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5101
5102 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5103
5104 unsigned ChainI = 0;
5105 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
5106 // See visitLoad comments.
5107 if (ChainI == MaxParallelChains) {
5108 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5109 ArrayRef(Chains.data(), ChainI));
5110 Root = Chain;
5111 ChainI = 0;
5112 }
5113
5114 // TODO: MachinePointerInfo only supports a fixed length offset.
5115 MachinePointerInfo PtrInfo =
5116 !Offsets[i].isScalable() || Offsets[i].isZero()
5117 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
5118 : MachinePointerInfo();
5119
5120 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
5121 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
5122 if (MemVTs[i] != ValueVTs[i])
5123 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
5124 SDValue St =
5125 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
5126 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
5127 Chains[ChainI] = St;
5128 }
5129
5130 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5131 ArrayRef(Chains.data(), ChainI));
5132 setValue(&I, StoreNode);
5133 DAG.setRoot(StoreNode);
5134}
5135
5136void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
5137 bool IsCompressing) {
5138 SDLoc sdl = getCurSDLoc();
5139
5140 Value *Src0Operand = I.getArgOperand(0);
5141 Value *PtrOperand = I.getArgOperand(1);
5142 Value *MaskOperand = I.getArgOperand(2);
5143 Align Alignment = I.getParamAlign(1).valueOrOne();
5144
5145 SDValue Ptr = getValue(PtrOperand);
5146 SDValue Src0 = getValue(Src0Operand);
5147 SDValue Mask = getValue(MaskOperand);
5148 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5149
5150 EVT VT = Src0.getValueType();
5151
5152 const auto &TLI = DAG.getTargetLoweringInfo();
5153
5154 auto MMOFlags = MachineMemOperand::MOStore;
5155 MMOFlags |= TLI.getTargetMMOFlags(I);
5156 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5158
5159 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/1);
5160
5161 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5162 MachinePointerInfo(PtrOperand), MMOFlags,
5163 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5164 MMOMetadata(I.getAAMetadata(), /*Ranges=*/nullptr, MemCacheHint));
5165
5166 SDValue StoreNode =
5167 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5168 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5169 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5170 Mask)
5171 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5172 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5173 IsCompressing);
5174 DAG.setRoot(StoreNode);
5175 setValue(&I, StoreNode);
5176}
5177
5178// Get a uniform base for the Gather/Scatter intrinsic.
5179// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5180// We try to represent it as a base pointer + vector of indices.
5181// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5182// The first operand of the GEP may be a single pointer or a vector of pointers
5183// Example:
5184// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5185// or
5186// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5187// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5188//
5189// When the first GEP operand is a single pointer - it is the uniform base we
5190// are looking for. If first operand of the GEP is a splat vector - we
5191// extract the splat value and use it as a uniform base.
5192// In all other cases the function returns 'false'.
5193static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5194 SDValue &Scale, SelectionDAGBuilder *SDB,
5195 const BasicBlock *CurBB, uint64_t ElemSize) {
5196 SelectionDAG& DAG = SDB->DAG;
5197 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5198 const DataLayout &DL = DAG.getDataLayout();
5199
5200 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5201
5202 // Handle splat constant pointer.
5203 if (auto *C = dyn_cast<Constant>(Ptr)) {
5204 C = C->getSplatValue();
5205 if (!C)
5206 return false;
5207
5208 Base = SDB->getValue(C);
5209
5210 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5211 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5212 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5213 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5214 return true;
5215 }
5216
5218 if (!GEP || GEP->getParent() != CurBB)
5219 return false;
5220
5221 if (GEP->getNumOperands() != 2)
5222 return false;
5223
5224 const Value *BasePtr = GEP->getPointerOperand();
5225 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5226
5227 // Make sure the base is scalar and the index is a vector.
5228 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5229 return false;
5230
5231 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5232 if (ScaleVal.isScalable())
5233 return false;
5234
5235 // Target may not support the required addressing mode.
5236 if (ScaleVal != 1 &&
5237 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5238 return false;
5239
5240 Base = SDB->getValue(BasePtr);
5241 Index = SDB->getValue(IndexVal);
5242
5243 Scale =
5244 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5245 return true;
5246}
5247
5248void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5249 SDLoc sdl = getCurSDLoc();
5250
5251 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5252 const Value *Ptr = I.getArgOperand(1);
5253 SDValue Src0 = getValue(I.getArgOperand(0));
5254 SDValue Mask = getValue(I.getArgOperand(2));
5255 EVT VT = Src0.getValueType();
5256 Align Alignment = I.getParamAlign(1).valueOrOne();
5257 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5258
5259 SDValue Base;
5260 SDValue Index;
5261 SDValue Scale;
5262 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5263 I.getParent(), VT.getScalarStoreSize());
5264
5265 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5266 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5267 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5268 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5269 if (!UniformBase) {
5270 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5271 Index = getValue(Ptr);
5272 Scale =
5273 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5274 }
5275
5276 EVT IdxVT = Index.getValueType();
5277 EVT EltTy = IdxVT.getVectorElementType();
5278 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5279 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5280 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5281 }
5282
5283 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5284 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5285 Ops, MMO, ISD::SIGNED_SCALED, false);
5286 DAG.setRoot(Scatter);
5287 setValue(&I, Scatter);
5288}
5289
5290void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5291 SDLoc sdl = getCurSDLoc();
5292
5293 Value *PtrOperand = I.getArgOperand(0);
5294 Value *MaskOperand = I.getArgOperand(1);
5295 Value *Src0Operand = I.getArgOperand(2);
5296 Align Alignment = I.getParamAlign(0).valueOrOne();
5297
5298 SDValue Ptr = getValue(PtrOperand);
5299 SDValue Src0 = getValue(Src0Operand);
5300 SDValue Mask = getValue(MaskOperand);
5301 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5302
5303 EVT VT = Src0.getValueType();
5304 AAMDNodes AAInfo = I.getAAMetadata();
5305 const MDNode *Ranges = getRangeMetadata(I);
5306 const MDNode *MemCacheHint = getMemCacheHintMetadata(I, /*OperandNo=*/0);
5307
5308 // Do not serialize masked loads of constant memory with anything.
5309 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5310 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5311
5312 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5313
5314 const auto &TLI = DAG.getTargetLoweringInfo();
5315
5316 auto MMOFlags = MachineMemOperand::MOLoad;
5317 MMOFlags |= TLI.getTargetMMOFlags(I);
5318 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5320 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5322
5323 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5324 MachinePointerInfo(PtrOperand), MMOFlags,
5325 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5326 MMOMetadata(AAInfo, Ranges, MemCacheHint));
5327
5328 // The Load/Res may point to different values and both of them are output
5329 // variables.
5330 SDValue Load;
5331 SDValue Res;
5332 if (!IsExpanding &&
5333 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5334 /*IsStore=*/false))
5335 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5336 else
5337 Res = Load =
5338 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5339 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5340 if (AddToChain)
5341 PendingLoads.push_back(Load.getValue(1));
5342 setValue(&I, Res);
5343}
5344
5345void SelectionDAGBuilder::visitSpeculativeLoad(const CallInst &I) {
5346 SDLoc sdl = getCurSDLoc();
5347 Value *PtrOperand = I.getArgOperand(0);
5348 // The remaining arguments (num_accessible_bytes or oracle function + args)
5349 // are IR-level semantics only; they are not needed at codegen.
5350 SDValue Ptr = getValue(PtrOperand);
5351
5352 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5353 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5354 Align Alignment = I.getParamAlign(0).valueOrOne();
5355 AAMDNodes AAInfo = I.getAAMetadata();
5356
5357 SDValue InChain = DAG.getRoot();
5358
5359 // Use MOLoad but NOT MODereferenceable - the memory may not be
5360 // fully dereferenceable.
5361 auto MMOFlags = MachineMemOperand::MOLoad;
5362 MMOFlags |= TLI.getTargetMMOFlags(I);
5363 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5365 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5367
5368 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5369 MachinePointerInfo(PtrOperand), MMOFlags,
5370 LocationSize::precise(VT.getStoreSize()), Alignment, AAInfo);
5371
5372 SDValue Load = DAG.getLoad(VT, sdl, InChain, Ptr, MMO);
5373 PendingLoads.push_back(Load.getValue(1));
5374 setValue(&I, Load);
5375}
5376
5377void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5378 SDLoc sdl = getCurSDLoc();
5379
5380 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5381 const Value *Ptr = I.getArgOperand(0);
5382 SDValue Src0 = getValue(I.getArgOperand(2));
5383 SDValue Mask = getValue(I.getArgOperand(1));
5384
5385 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5386 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5387 Align Alignment = I.getParamAlign(0).valueOrOne();
5388
5389 const MDNode *Ranges = getRangeMetadata(I);
5390
5391 SDValue Root = DAG.getRoot();
5392 SDValue Base;
5393 SDValue Index;
5394 SDValue Scale;
5395 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5396 I.getParent(), VT.getScalarStoreSize());
5397 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5398 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5399 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5401 MMOMetadata(I.getAAMetadata(), Ranges));
5402
5403 if (!UniformBase) {
5404 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5405 Index = getValue(Ptr);
5406 Scale =
5407 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5408 }
5409
5410 EVT IdxVT = Index.getValueType();
5411 EVT EltTy = IdxVT.getVectorElementType();
5412 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5413 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5414 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5415 }
5416
5417 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5418 SDValue Gather =
5419 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5421
5422 PendingLoads.push_back(Gather.getValue(1));
5423 setValue(&I, Gather);
5424}
5425
5426void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5427 SDLoc dl = getCurSDLoc();
5428 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5429 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5430 SyncScope::ID SSID = I.getSyncScopeID();
5431
5432 SDValue InChain = getRoot();
5433
5434 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5435 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5436
5437 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5438 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5439
5440 MachineFunction &MF = DAG.getMachineFunction();
5441 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5442 MachineMemOperand *MMO = MF.getMachineMemOperand(
5443 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5444 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5445 SSID, SuccessOrdering, FailureOrdering);
5446
5447 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5448 dl, MemVT, VTs, InChain,
5449 getValue(I.getPointerOperand()),
5450 getValue(I.getCompareOperand()),
5451 getValue(I.getNewValOperand()), MMO);
5452
5453 SDValue OutChain = L.getValue(2);
5454
5455 setValue(&I, L);
5456 DAG.setRoot(OutChain);
5457}
5458
5459void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5460 SDLoc dl = getCurSDLoc();
5462 switch (I.getOperation()) {
5463 default: llvm_unreachable("Unknown atomicrmw operation");
5481 break;
5484 break;
5487 break;
5490 break;
5493 break;
5496 break;
5499 break;
5502 break;
5503 }
5504 AtomicOrdering Ordering = I.getOrdering();
5505 SyncScope::ID SSID = I.getSyncScopeID();
5506
5507 SDValue InChain = getRoot();
5508
5509 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5510 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5511 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5512
5513 MachineFunction &MF = DAG.getMachineFunction();
5514 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5515 MachineMemOperand *MMO = MF.getMachineMemOperand(
5516 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5517 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5518 SSID, Ordering);
5519
5520 SDValue L =
5521 DAG.getAtomic(NT, dl, MemVT, InChain,
5522 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5523 MMO);
5524
5525 SDValue OutChain = L.getValue(1);
5526
5527 setValue(&I, L);
5528 DAG.setRoot(OutChain);
5529}
5530
5531void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5532 SDLoc dl = getCurSDLoc();
5533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5534 SDValue Ops[3];
5535 Ops[0] = getRoot();
5536 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5537 TLI.getFenceOperandTy(DAG.getDataLayout()));
5538 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5539 TLI.getFenceOperandTy(DAG.getDataLayout()));
5540 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5541 setValue(&I, N);
5542 DAG.setRoot(N);
5543}
5544
5545void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5546 SDLoc dl = getCurSDLoc();
5547 AtomicOrdering Order = I.getOrdering();
5548 SyncScope::ID SSID = I.getSyncScopeID();
5549
5550 SDValue InChain = getRoot();
5551
5552 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5553 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5554 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5555
5556 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5557 report_fatal_error("Cannot generate unaligned atomic load");
5558
5559 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5560
5561 const MDNode *Ranges = getRangeMetadata(I);
5562 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
5563 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5564 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5565 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges, MemCacheHint), SSID,
5566 Order);
5567
5568 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5569
5570 SDValue Ptr = getValue(I.getPointerOperand());
5571 SDValue L =
5572 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5573
5574 SDValue OutChain = L.getValue(1);
5575 if (MemVT != VT)
5576 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5577
5578 setValue(&I, L);
5579 DAG.setRoot(OutChain);
5580}
5581
5582void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5583 SDLoc dl = getCurSDLoc();
5584
5585 AtomicOrdering Ordering = I.getOrdering();
5586 SyncScope::ID SSID = I.getSyncScopeID();
5587
5588 SDValue InChain = getRoot();
5589
5590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5591 EVT MemVT =
5592 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5593
5594 if (!TLI.isAtomicAlignmentSupported(I.getAlign(), MemVT.getSizeInBits() / 8))
5595 report_fatal_error("Cannot generate unaligned atomic store");
5596
5597 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5598
5599 MachineFunction &MF = DAG.getMachineFunction();
5600 const MDNode *MemCacheHint =
5601 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
5602 MachineMemOperand *MMO = MF.getMachineMemOperand(
5603 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5604 I.getAlign(), MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MemCacheHint),
5605 SSID, Ordering);
5606
5607 SDValue Val = getValue(I.getValueOperand());
5608 if (Val.getValueType() != MemVT)
5609 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5610 SDValue Ptr = getValue(I.getPointerOperand());
5611
5612 SDValue OutChain =
5613 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5614
5615 setValue(&I, OutChain);
5616 DAG.setRoot(OutChain);
5617}
5618
5619/// Check if this intrinsic call depends on the chain (1st return value)
5620/// and if it only *loads* memory.
5621/// Ignore the callsite's attributes. A specific call site may be marked with
5622/// readnone, but the lowering code will expect the chain based on the
5623/// definition.
5624std::pair<bool, bool>
5625SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5626 const Function *F = I.getCalledFunction();
5627 bool HasChain = !F->doesNotAccessMemory();
5628 bool OnlyLoad =
5629 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5630
5631 return {HasChain, OnlyLoad};
5632}
5633
5634SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5635 const CallBase &I, bool HasChain, bool OnlyLoad,
5636 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5637 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5638
5639 // Build the operand list.
5641 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5642 if (OnlyLoad) {
5643 // We don't need to serialize loads against other loads.
5644 Ops.push_back(DAG.getRoot());
5645 } else {
5646 Ops.push_back(getRoot());
5647 }
5648 }
5649
5650 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5651 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5652 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5653 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5654 TLI.getPointerTy(DAG.getDataLayout())));
5655
5656 // Add all operands of the call to the operand list.
5657 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5658 const Value *Arg = I.getArgOperand(i);
5659 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5660 Ops.push_back(getValue(Arg));
5661 continue;
5662 }
5663
5664 // Use TargetConstant instead of a regular constant for immarg.
5665 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5666 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5667 assert(CI->getBitWidth() <= 64 &&
5668 "large intrinsic immediates not handled");
5669 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5670 } else {
5671 Ops.push_back(
5672 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5673 }
5674 }
5675
5676 if (std::optional<OperandBundleUse> Bundle =
5677 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5678 auto *Sym = Bundle->Inputs[0].get();
5679 SDValue SDSym = getValue(Sym);
5680 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5681 Ops.push_back(SDSym);
5682 }
5683
5684 if (std::optional<OperandBundleUse> Bundle =
5685 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5686 Value *Token = Bundle->Inputs[0].get();
5687 SDValue ConvControlToken = getValue(Token);
5688 assert(Ops.back().getValueType() != MVT::Glue &&
5689 "Did not expect another glue node here.");
5690 ConvControlToken =
5691 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5692 Ops.push_back(ConvControlToken);
5693 }
5694
5695 return Ops;
5696}
5697
5698SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5699 bool HasChain) {
5700 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5701
5702 SmallVector<EVT, 4> ValueVTs;
5703 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5704
5705 if (HasChain)
5706 ValueVTs.push_back(MVT::Other);
5707
5708 return DAG.getVTList(ValueVTs);
5709}
5710
5711/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5712SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5713 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5714 const SDVTList &VTs) {
5715 if (!HasChain)
5716 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5717 if (!IntrinsicVT.isVoidTy())
5718 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5719 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5720}
5721
5722/// Set root, convert return type if necessary and check alignment.
5723SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5724 bool HasChain,
5725 bool OnlyLoad,
5726 SDValue Result) {
5727 if (HasChain) {
5728 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5729 if (OnlyLoad)
5730 PendingLoads.push_back(Chain);
5731 else
5732 DAG.setRoot(Chain);
5733 }
5734
5735 if (I.getType()->isVoidTy())
5736 return Result;
5737
5738 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5739 // Insert `assertalign` node if there's an alignment.
5740 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5741 } else if (!isa<VectorType>(I.getType())) {
5742 Result = lowerRangeToAssertZExt(DAG, I, Result);
5743 }
5744
5745 return Result;
5746}
5747
5748/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5749/// node.
5750void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5751 unsigned Intrinsic) {
5752 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5753 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5754
5755 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5756 Intrinsic)) {
5757 SDLoc DL = getCurSDLoc();
5758 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5759 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5760
5761 // The intrinsic is not available on this subtarget. Preserve the chain for
5762 // side-effecting intrinsics and lower any result to poison so that
5763 // compilation can continue and collect further diagnostics.
5764 if (HasChain && !OnlyLoad)
5765 DAG.setRoot(getRoot());
5766
5768 return;
5769 }
5770
5771 // Infos is set by getTgtMemIntrinsic.
5773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5774 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5775 // Use the first (primary) info determines the node opcode.
5776 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5777
5779 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5780 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5781
5782 // Propagate fast-math-flags from IR to node(s).
5783 SDNodeFlags Flags;
5784 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5785 Flags.copyFMF(*FPMO);
5786 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5787
5788 // Create the node.
5789 SDValue Result;
5790
5791 // In some cases, custom collection of operands from CallInst I may be needed.
5793 if (!Infos.empty()) {
5794 // This is target intrinsic that touches memory
5795 // Create MachineMemOperands for each memory access described by the target.
5796 MachineFunction &MF = DAG.getMachineFunction();
5798 for (const auto &Info : Infos) {
5799 // TODO: We currently just fallback to address space 0 if
5800 // getTgtMemIntrinsic didn't yield anything useful.
5801 MachinePointerInfo MPI;
5802 if (Info.ptrVal)
5803 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5804 else if (Info.fallbackAddressSpace)
5805 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5806 EVT MemVT = Info.memVT;
5807 LocationSize Size = LocationSize::precise(Info.size);
5808 if (Size.hasValue() && !Size.getValue())
5810 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5811 MachineMemOperand *MMO = MF.getMachineMemOperand(
5812 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5813 Info.order, Info.failureOrder);
5814 MMOs.push_back(MMO);
5815 }
5816
5817 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5818 Info->memVT, MMOs);
5819 } else {
5820 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5821 }
5822
5823 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5824
5825 setValue(&I, Result);
5826}
5827
5828/// GetSignificand - Get the significand and build it into a floating-point
5829/// number with exponent of 1:
5830///
5831/// Op = (Op & 0x007fffff) | 0x3f800000;
5832///
5833/// where Op is the hexadecimal representation of floating point value.
5835 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5836 DAG.getConstant(0x007fffff, dl, MVT::i32));
5837 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5838 DAG.getConstant(0x3f800000, dl, MVT::i32));
5839 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5840}
5841
5842/// GetExponent - Get the exponent:
5843///
5844/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5845///
5846/// where Op is the hexadecimal representation of floating point value.
5848 const TargetLowering &TLI, const SDLoc &dl) {
5849 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5850 DAG.getConstant(0x7f800000, dl, MVT::i32));
5851 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5852 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5853 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5854 DAG.getConstant(127, dl, MVT::i32));
5855 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5856}
5857
5858/// getF32Constant - Get 32-bit floating point constant.
5859static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5860 const SDLoc &dl) {
5861 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5862 MVT::f32);
5863}
5864
5866 SelectionDAG &DAG) {
5867 // TODO: What fast-math-flags should be set on the floating-point nodes?
5868
5869 // IntegerPartOfX = ((int32_t)(t0);
5870 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5871
5872 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5873 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5874 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5875
5876 // IntegerPartOfX <<= 23;
5877 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5878 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5879
5880 SDValue TwoToFractionalPartOfX;
5881 if (LimitFloatPrecision <= 6) {
5882 // For floating-point precision of 6:
5883 //
5884 // TwoToFractionalPartOfX =
5885 // 0.997535578f +
5886 // (0.735607626f + 0.252464424f * x) * x;
5887 //
5888 // error 0.0144103317, which is 6 bits
5889 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5890 getF32Constant(DAG, 0x3e814304, dl));
5891 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5892 getF32Constant(DAG, 0x3f3c50c8, dl));
5893 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5894 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5895 getF32Constant(DAG, 0x3f7f5e7e, dl));
5896 } else if (LimitFloatPrecision <= 12) {
5897 // For floating-point precision of 12:
5898 //
5899 // TwoToFractionalPartOfX =
5900 // 0.999892986f +
5901 // (0.696457318f +
5902 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5903 //
5904 // error 0.000107046256, which is 13 to 14 bits
5905 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5906 getF32Constant(DAG, 0x3da235e3, dl));
5907 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5908 getF32Constant(DAG, 0x3e65b8f3, dl));
5909 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5910 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5911 getF32Constant(DAG, 0x3f324b07, dl));
5912 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5913 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5914 getF32Constant(DAG, 0x3f7ff8fd, dl));
5915 } else { // LimitFloatPrecision <= 18
5916 // For floating-point precision of 18:
5917 //
5918 // TwoToFractionalPartOfX =
5919 // 0.999999982f +
5920 // (0.693148872f +
5921 // (0.240227044f +
5922 // (0.554906021e-1f +
5923 // (0.961591928e-2f +
5924 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5925 // error 2.47208000*10^(-7), which is better than 18 bits
5926 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5927 getF32Constant(DAG, 0x3924b03e, dl));
5928 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5929 getF32Constant(DAG, 0x3ab24b87, dl));
5930 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5931 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5932 getF32Constant(DAG, 0x3c1d8c17, dl));
5933 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5934 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5935 getF32Constant(DAG, 0x3d634a1d, dl));
5936 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5937 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5938 getF32Constant(DAG, 0x3e75fe14, dl));
5939 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5940 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5941 getF32Constant(DAG, 0x3f317234, dl));
5942 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5943 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5944 getF32Constant(DAG, 0x3f800000, dl));
5945 }
5946
5947 // Add the exponent into the result in integer domain.
5948 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5949 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5950 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5951}
5952
5953/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5954/// limited-precision mode.
5956 const TargetLowering &TLI, SDNodeFlags Flags) {
5957 if (Op.getValueType() == MVT::f32 &&
5959
5960 // Put the exponent in the right bit position for later addition to the
5961 // final result:
5962 //
5963 // t0 = Op * log2(e)
5964
5965 // TODO: What fast-math-flags should be set here?
5966 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5967 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5968 return getLimitedPrecisionExp2(t0, dl, DAG);
5969 }
5970
5971 // No special expansion.
5972 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5973}
5974
5975/// expandLog - Lower a log intrinsic. Handles the special sequences for
5976/// limited-precision mode.
5978 const TargetLowering &TLI, SDNodeFlags Flags) {
5979 // TODO: What fast-math-flags should be set on the floating-point nodes?
5980
5981 if (Op.getValueType() == MVT::f32 &&
5983 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5984
5985 // Scale the exponent by log(2).
5986 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5987 SDValue LogOfExponent =
5988 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5989 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5990
5991 // Get the significand and build it into a floating-point number with
5992 // exponent of 1.
5993 SDValue X = GetSignificand(DAG, Op1, dl);
5994
5995 SDValue LogOfMantissa;
5996 if (LimitFloatPrecision <= 6) {
5997 // For floating-point precision of 6:
5998 //
5999 // LogofMantissa =
6000 // -1.1609546f +
6001 // (1.4034025f - 0.23903021f * x) * x;
6002 //
6003 // error 0.0034276066, which is better than 8 bits
6004 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6005 getF32Constant(DAG, 0xbe74c456, dl));
6006 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6007 getF32Constant(DAG, 0x3fb3a2b1, dl));
6008 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6009 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6010 getF32Constant(DAG, 0x3f949a29, dl));
6011 } else if (LimitFloatPrecision <= 12) {
6012 // For floating-point precision of 12:
6013 //
6014 // LogOfMantissa =
6015 // -1.7417939f +
6016 // (2.8212026f +
6017 // (-1.4699568f +
6018 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
6019 //
6020 // error 0.000061011436, which is 14 bits
6021 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6022 getF32Constant(DAG, 0xbd67b6d6, dl));
6023 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6024 getF32Constant(DAG, 0x3ee4f4b8, dl));
6025 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6026 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6027 getF32Constant(DAG, 0x3fbc278b, dl));
6028 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6029 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6030 getF32Constant(DAG, 0x40348e95, dl));
6031 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6032 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6033 getF32Constant(DAG, 0x3fdef31a, dl));
6034 } else { // LimitFloatPrecision <= 18
6035 // For floating-point precision of 18:
6036 //
6037 // LogOfMantissa =
6038 // -2.1072184f +
6039 // (4.2372794f +
6040 // (-3.7029485f +
6041 // (2.2781945f +
6042 // (-0.87823314f +
6043 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
6044 //
6045 // error 0.0000023660568, which is better than 18 bits
6046 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6047 getF32Constant(DAG, 0xbc91e5ac, dl));
6048 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6049 getF32Constant(DAG, 0x3e4350aa, dl));
6050 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6051 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6052 getF32Constant(DAG, 0x3f60d3e3, dl));
6053 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6054 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6055 getF32Constant(DAG, 0x4011cdf0, dl));
6056 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6057 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6058 getF32Constant(DAG, 0x406cfd1c, dl));
6059 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6060 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6061 getF32Constant(DAG, 0x408797cb, dl));
6062 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6063 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6064 getF32Constant(DAG, 0x4006dcab, dl));
6065 }
6066
6067 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
6068 }
6069
6070 // No special expansion.
6071 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
6072}
6073
6074/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
6075/// limited-precision mode.
6077 const TargetLowering &TLI, SDNodeFlags Flags) {
6078 // TODO: What fast-math-flags should be set on the floating-point nodes?
6079
6080 if (Op.getValueType() == MVT::f32 &&
6082 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6083
6084 // Get the exponent.
6085 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
6086
6087 // Get the significand and build it into a floating-point number with
6088 // exponent of 1.
6089 SDValue X = GetSignificand(DAG, Op1, dl);
6090
6091 // Different possible minimax approximations of significand in
6092 // floating-point for various degrees of accuracy over [1,2].
6093 SDValue Log2ofMantissa;
6094 if (LimitFloatPrecision <= 6) {
6095 // For floating-point precision of 6:
6096 //
6097 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
6098 //
6099 // error 0.0049451742, which is more than 7 bits
6100 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6101 getF32Constant(DAG, 0xbeb08fe0, dl));
6102 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6103 getF32Constant(DAG, 0x40019463, dl));
6104 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6105 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6106 getF32Constant(DAG, 0x3fd6633d, dl));
6107 } else if (LimitFloatPrecision <= 12) {
6108 // For floating-point precision of 12:
6109 //
6110 // Log2ofMantissa =
6111 // -2.51285454f +
6112 // (4.07009056f +
6113 // (-2.12067489f +
6114 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
6115 //
6116 // error 0.0000876136000, which is better than 13 bits
6117 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6118 getF32Constant(DAG, 0xbda7262e, dl));
6119 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6120 getF32Constant(DAG, 0x3f25280b, dl));
6121 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6122 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6123 getF32Constant(DAG, 0x4007b923, dl));
6124 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6125 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6126 getF32Constant(DAG, 0x40823e2f, dl));
6127 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6128 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6129 getF32Constant(DAG, 0x4020d29c, dl));
6130 } else { // LimitFloatPrecision <= 18
6131 // For floating-point precision of 18:
6132 //
6133 // Log2ofMantissa =
6134 // -3.0400495f +
6135 // (6.1129976f +
6136 // (-5.3420409f +
6137 // (3.2865683f +
6138 // (-1.2669343f +
6139 // (0.27515199f -
6140 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
6141 //
6142 // error 0.0000018516, which is better than 18 bits
6143 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6144 getF32Constant(DAG, 0xbcd2769e, dl));
6145 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6146 getF32Constant(DAG, 0x3e8ce0b9, dl));
6147 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6148 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6149 getF32Constant(DAG, 0x3fa22ae7, dl));
6150 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6151 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
6152 getF32Constant(DAG, 0x40525723, dl));
6153 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6154 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
6155 getF32Constant(DAG, 0x40aaf200, dl));
6156 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6157 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
6158 getF32Constant(DAG, 0x40c39dad, dl));
6159 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
6160 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
6161 getF32Constant(DAG, 0x4042902c, dl));
6162 }
6163
6164 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
6165 }
6166
6167 // No special expansion.
6168 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
6169}
6170
6171/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
6172/// limited-precision mode.
6174 const TargetLowering &TLI, SDNodeFlags Flags) {
6175 // TODO: What fast-math-flags should be set on the floating-point nodes?
6176
6177 if (Op.getValueType() == MVT::f32 &&
6179 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
6180
6181 // Scale the exponent by log10(2) [0.30102999f].
6182 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
6183 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
6184 getF32Constant(DAG, 0x3e9a209a, dl));
6185
6186 // Get the significand and build it into a floating-point number with
6187 // exponent of 1.
6188 SDValue X = GetSignificand(DAG, Op1, dl);
6189
6190 SDValue Log10ofMantissa;
6191 if (LimitFloatPrecision <= 6) {
6192 // For floating-point precision of 6:
6193 //
6194 // Log10ofMantissa =
6195 // -0.50419619f +
6196 // (0.60948995f - 0.10380950f * x) * x;
6197 //
6198 // error 0.0014886165, which is 6 bits
6199 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6200 getF32Constant(DAG, 0xbdd49a13, dl));
6201 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6202 getF32Constant(DAG, 0x3f1c0789, dl));
6203 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6204 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6205 getF32Constant(DAG, 0x3f011300, dl));
6206 } else if (LimitFloatPrecision <= 12) {
6207 // For floating-point precision of 12:
6208 //
6209 // Log10ofMantissa =
6210 // -0.64831180f +
6211 // (0.91751397f +
6212 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6213 //
6214 // error 0.00019228036, which is better than 12 bits
6215 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6216 getF32Constant(DAG, 0x3d431f31, dl));
6217 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6218 getF32Constant(DAG, 0x3ea21fb2, dl));
6219 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6220 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6221 getF32Constant(DAG, 0x3f6ae232, dl));
6222 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6223 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6224 getF32Constant(DAG, 0x3f25f7c3, dl));
6225 } else { // LimitFloatPrecision <= 18
6226 // For floating-point precision of 18:
6227 //
6228 // Log10ofMantissa =
6229 // -0.84299375f +
6230 // (1.5327582f +
6231 // (-1.0688956f +
6232 // (0.49102474f +
6233 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6234 //
6235 // error 0.0000037995730, which is better than 18 bits
6236 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6237 getF32Constant(DAG, 0x3c5d51ce, dl));
6238 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6239 getF32Constant(DAG, 0x3e00685a, dl));
6240 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6241 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6242 getF32Constant(DAG, 0x3efb6798, dl));
6243 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6244 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6245 getF32Constant(DAG, 0x3f88d192, dl));
6246 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6247 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6248 getF32Constant(DAG, 0x3fc4316c, dl));
6249 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6250 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6251 getF32Constant(DAG, 0x3f57ce70, dl));
6252 }
6253
6254 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6255 }
6256
6257 // No special expansion.
6258 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6259}
6260
6261/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6262/// limited-precision mode.
6264 const TargetLowering &TLI, SDNodeFlags Flags) {
6265 if (Op.getValueType() == MVT::f32 &&
6267 return getLimitedPrecisionExp2(Op, dl, DAG);
6268
6269 // No special expansion.
6270 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6271}
6272
6273/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6274/// limited-precision mode with x == 10.0f.
6276 SelectionDAG &DAG, const TargetLowering &TLI,
6277 SDNodeFlags Flags) {
6278 bool IsExp10 = false;
6279 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6282 APFloat Ten(10.0f);
6283 IsExp10 = LHSC->isExactlyValue(Ten);
6284 }
6285 }
6286
6287 // TODO: What fast-math-flags should be set on the FMUL node?
6288 if (IsExp10) {
6289 // Put the exponent in the right bit position for later addition to the
6290 // final result:
6291 //
6292 // #define LOG2OF10 3.3219281f
6293 // t0 = Op * LOG2OF10;
6294 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6295 getF32Constant(DAG, 0x40549a78, dl));
6296 return getLimitedPrecisionExp2(t0, dl, DAG);
6297 }
6298
6299 // No special expansion.
6300 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6301}
6302
6303/// ExpandPowI - Expand a llvm.powi intrinsic.
6305 SelectionDAG &DAG) {
6306 // If RHS is a constant, we can expand this out to a multiplication tree if
6307 // it's beneficial on the target, otherwise we end up lowering to a call to
6308 // __powidf2 (for example).
6310 unsigned Val = RHSC->getSExtValue();
6311
6312 // powi(x, 0) -> 1.0
6313 if (Val == 0)
6314 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6315
6317 Val, DAG.shouldOptForSize())) {
6318 // Get the exponent as a positive value.
6319 if ((int)Val < 0)
6320 Val = -Val;
6321 // We use the simple binary decomposition method to generate the multiply
6322 // sequence. There are more optimal ways to do this (for example,
6323 // powi(x,15) generates one more multiply than it should), but this has
6324 // the benefit of being both really simple and much better than a libcall.
6325 SDValue Res; // Logically starts equal to 1.0
6326 SDValue CurSquare = LHS;
6327 // TODO: Intrinsics should have fast-math-flags that propagate to these
6328 // nodes.
6329 while (Val) {
6330 if (Val & 1) {
6331 if (Res.getNode())
6332 Res =
6333 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6334 else
6335 Res = CurSquare; // 1.0*CurSquare.
6336 }
6337
6338 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6339 CurSquare, CurSquare);
6340 Val >>= 1;
6341 }
6342
6343 // If the original was negative, invert the result, producing 1/(x*x*x).
6344 if (RHSC->getSExtValue() < 0)
6345 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6346 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6347 return Res;
6348 }
6349 }
6350
6351 // Otherwise, expand to a libcall.
6352 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6353}
6354
6355static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6356 SDValue LHS, SDValue RHS, SDValue Scale,
6357 SelectionDAG &DAG, const TargetLowering &TLI) {
6358 EVT VT = LHS.getValueType();
6359 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6360 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6361 LLVMContext &Ctx = *DAG.getContext();
6362
6363 // If the type is legal but the operation isn't, this node might survive all
6364 // the way to operation legalization. If we end up there and we do not have
6365 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6366 // node.
6367
6368 // Coax the legalizer into expanding the node during type legalization instead
6369 // by bumping the size by one bit. This will force it to Promote, enabling the
6370 // early expansion and avoiding the need to expand later.
6371
6372 // We don't have to do this if Scale is 0; that can always be expanded, unless
6373 // it's a saturating signed operation. Those can experience true integer
6374 // division overflow, a case which we must avoid.
6375
6376 // FIXME: We wouldn't have to do this (or any of the early
6377 // expansion/promotion) if it was possible to expand a libcall of an
6378 // illegal type during operation legalization. But it's not, so things
6379 // get a bit hacky.
6380 unsigned ScaleInt = Scale->getAsZExtVal();
6381 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6382 (TLI.isTypeLegal(VT) ||
6383 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6385 Opcode, VT, ScaleInt);
6386 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6387 EVT PromVT;
6388 if (VT.isScalarInteger())
6389 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6390 else if (VT.isVector()) {
6391 PromVT = VT.getVectorElementType();
6392 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6393 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6394 } else
6395 llvm_unreachable("Wrong VT for DIVFIX?");
6396 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6397 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6398 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6399 // For saturating operations, we need to shift up the LHS to get the
6400 // proper saturation width, and then shift down again afterwards.
6401 if (Saturating)
6402 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6403 DAG.getConstant(1, DL, ShiftTy));
6404 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6405 if (Saturating)
6406 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6407 DAG.getConstant(1, DL, ShiftTy));
6408 return DAG.getZExtOrTrunc(Res, DL, VT);
6409 }
6410 }
6411
6412 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6413}
6414
6415// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6416// bitcasted, or split argument. Returns a list of <Register, size in bits>
6417static void
6418getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6419 const SDValue &N) {
6420 switch (N.getOpcode()) {
6421 case ISD::CopyFromReg: {
6422 SDValue Op = N.getOperand(1);
6423 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6424 Op.getValueType().getSizeInBits());
6425 return;
6426 }
6427 case ISD::BITCAST:
6428 case ISD::AssertZext:
6429 case ISD::AssertSext:
6430 case ISD::TRUNCATE:
6431 getUnderlyingArgRegs(Regs, N.getOperand(0));
6432 return;
6433 case ISD::BUILD_PAIR:
6434 case ISD::BUILD_VECTOR:
6436 for (SDValue Op : N->op_values())
6437 getUnderlyingArgRegs(Regs, Op);
6438 return;
6439 default:
6440 return;
6441 }
6442}
6443
6444/// If the DbgValueInst is a dbg_value of a function argument, create the
6445/// corresponding DBG_VALUE machine instruction for it now. At the end of
6446/// instruction selection, they will be inserted to the entry BB.
6447/// We don't currently support this for variadic dbg_values, as they shouldn't
6448/// appear for function arguments or in the prologue.
6449bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6450 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6451 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6452 const Argument *Arg = dyn_cast<Argument>(V);
6453 if (!Arg)
6454 return false;
6455
6456 MachineFunction &MF = DAG.getMachineFunction();
6457 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6458
6459 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6460 // we've been asked to pursue.
6461 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6462 bool Indirect) {
6463 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6464 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6465 // pointing at the VReg, which will be patched up later.
6466 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6468 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6469 /* isKill */ false, /* isDead */ false,
6470 /* isUndef */ false, /* isEarlyClobber */ false,
6471 /* SubReg */ 0, /* isDebug */ true)});
6472
6473 auto *NewDIExpr = FragExpr;
6474 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6475 // the DIExpression.
6476 if (Indirect)
6477 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6479 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6480 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6481 } else {
6482 // Create a completely standard DBG_VALUE.
6483 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6484 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6485 }
6486 };
6487
6488 if (Kind == FuncArgumentDbgValueKind::Value) {
6489 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6490 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6491 // the entry block.
6492 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6493 if (!IsInEntryBlock)
6494 return false;
6495
6496 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6497 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6498 // variable that also is a param.
6499 //
6500 // Although, if we are at the top of the entry block already, we can still
6501 // emit using ArgDbgValue. This might catch some situations when the
6502 // dbg.value refers to an argument that isn't used in the entry block, so
6503 // any CopyToReg node would be optimized out and the only way to express
6504 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6505 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6506 // we should only emit as ArgDbgValue if the Variable is an argument to the
6507 // current function, and the dbg.value intrinsic is found in the entry
6508 // block.
6509 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6510 !DL->getInlinedAt();
6511 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6512 if (!IsInPrologue && !VariableIsFunctionInputArg)
6513 return false;
6514
6515 // Here we assume that a function argument on IR level only can be used to
6516 // describe one input parameter on source level. If we for example have
6517 // source code like this
6518 //
6519 // struct A { long x, y; };
6520 // void foo(struct A a, long b) {
6521 // ...
6522 // b = a.x;
6523 // ...
6524 // }
6525 //
6526 // and IR like this
6527 //
6528 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6529 // entry:
6530 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6531 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6532 // call void @llvm.dbg.value(metadata i32 %b, "b",
6533 // ...
6534 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6535 // ...
6536 //
6537 // then the last dbg.value is describing a parameter "b" using a value that
6538 // is an argument. But since we already has used %a1 to describe a parameter
6539 // we should not handle that last dbg.value here (that would result in an
6540 // incorrect hoisting of the DBG_VALUE to the function entry).
6541 // Notice that we allow one dbg.value per IR level argument, to accommodate
6542 // for the situation with fragments above.
6543 // If there is no node for the value being handled, we return true to skip
6544 // the normal generation of debug info, as it would kill existing debug
6545 // info for the parameter in case of duplicates.
6546 if (VariableIsFunctionInputArg) {
6547 unsigned ArgNo = Arg->getArgNo();
6548 if (ArgNo >= FuncInfo.DescribedArgs.size())
6549 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6550 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6551 return !NodeMap[V].getNode();
6552 FuncInfo.DescribedArgs.set(ArgNo);
6553 }
6554 }
6555
6556 bool IsIndirect = false;
6557 std::optional<MachineOperand> Op;
6558 // Some arguments' frame index is recorded during argument lowering.
6559 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6560 if (FI != std::numeric_limits<int>::max())
6562
6564 if (!Op && N.getNode()) {
6565 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6566 Register Reg;
6567 if (ArgRegsAndSizes.size() == 1)
6568 Reg = ArgRegsAndSizes.front().first;
6569
6570 if (Reg && Reg.isVirtual()) {
6571 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6572 Register PR = RegInfo.getLiveInPhysReg(Reg);
6573 if (PR)
6574 Reg = PR;
6575 }
6576 if (Reg) {
6578 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6579 }
6580 }
6581
6582 if (!Op && N.getNode()) {
6583 // Check if frame index is available.
6584 SDValue LCandidate = peekThroughBitcasts(N);
6585 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6586 if (FrameIndexSDNode *FINode =
6587 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6588 Op = MachineOperand::CreateFI(FINode->getIndex());
6589 }
6590
6591 if (!Op) {
6592 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6593 auto splitMultiRegDbgValue =
6594 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6595 unsigned Offset = 0;
6596 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6597 // FIXME: Scalable sizes are not supported in fragment expressions.
6598 if (RegSizeInBits.isScalable())
6599 return false;
6600
6601 // If the expression is already a fragment, the current register
6602 // offset+size might extend beyond the fragment. In this case, only
6603 // the register bits that are inside the fragment are relevant.
6604 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6605 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6606 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6607 // The register is entirely outside the expression fragment,
6608 // so is irrelevant for debug info.
6609 if (Offset >= ExprFragmentSizeInBits)
6610 break;
6611 // The register is partially outside the expression fragment, only
6612 // the low bits within the fragment are relevant for debug info.
6613 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6614 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6615 }
6616 }
6617
6618 auto FragmentExpr = DIExpression::createFragmentExpression(
6619 Expr, Offset, RegFragmentSizeInBits);
6620 Offset += RegSizeInBits.getFixedValue();
6621 // If a valid fragment expression cannot be created, the variable's
6622 // correct value cannot be determined and so it is set as poison.
6623 if (!FragmentExpr) {
6624 SDDbgValue *SDV = DAG.getConstantDbgValue(
6625 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6626 DAG.AddDbgValue(SDV, false);
6627 continue;
6628 }
6629 MachineInstr *NewMI = MakeVRegDbgValue(
6630 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6631 FuncInfo.ArgDbgValues.push_back(NewMI);
6632 }
6633
6634 return true;
6635 };
6636
6637 // Check if ValueMap has reg number.
6639 VMI = FuncInfo.ValueMap.find(V);
6640 if (VMI != FuncInfo.ValueMap.end()) {
6641 const auto &TLI = DAG.getTargetLoweringInfo();
6642 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6643 V->getType(), std::nullopt);
6644 if (RFV.occupiesMultipleRegs())
6645 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6646
6647 Op = MachineOperand::CreateReg(VMI->second, false);
6648 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6649 } else if (ArgRegsAndSizes.size() > 1) {
6650 // This was split due to the calling convention, and no virtual register
6651 // mapping exists for the value.
6652 return splitMultiRegDbgValue(ArgRegsAndSizes);
6653 }
6654 }
6655
6656 if (!Op)
6657 return false;
6658
6659 assert(Variable->isValidLocationForIntrinsic(DL) &&
6660 "Expected inlined-at fields to agree");
6661 MachineInstr *NewMI = nullptr;
6662
6663 if (Op->isReg())
6664 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6665 else
6666 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6667 Variable, Expr);
6668
6669 // Otherwise, use ArgDbgValues.
6670 FuncInfo.ArgDbgValues.push_back(NewMI);
6671 return true;
6672}
6673
6674/// Return the appropriate SDDbgValue based on N.
6675SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6676 DILocalVariable *Variable,
6677 DIExpression *Expr,
6678 const DebugLoc &dl,
6679 unsigned DbgSDNodeOrder) {
6680 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6681 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6682 // stack slot locations.
6683 //
6684 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6685 // debug values here after optimization:
6686 //
6687 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6688 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6689 //
6690 // Both describe the direct values of their associated variables.
6691 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6692 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6693 }
6694 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6695 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6696}
6697
6698static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6699 switch (Intrinsic) {
6700 case Intrinsic::smul_fix:
6701 return ISD::SMULFIX;
6702 case Intrinsic::umul_fix:
6703 return ISD::UMULFIX;
6704 case Intrinsic::smul_fix_sat:
6705 return ISD::SMULFIXSAT;
6706 case Intrinsic::umul_fix_sat:
6707 return ISD::UMULFIXSAT;
6708 case Intrinsic::sdiv_fix:
6709 return ISD::SDIVFIX;
6710 case Intrinsic::udiv_fix:
6711 return ISD::UDIVFIX;
6712 case Intrinsic::sdiv_fix_sat:
6713 return ISD::SDIVFIXSAT;
6714 case Intrinsic::udiv_fix_sat:
6715 return ISD::UDIVFIXSAT;
6716 default:
6717 llvm_unreachable("Unhandled fixed point intrinsic");
6718 }
6719}
6720
6721/// Given a @llvm.call.preallocated.setup, return the corresponding
6722/// preallocated call.
6723static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6724 assert(cast<CallBase>(PreallocatedSetup)
6726 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6727 "expected call_preallocated_setup Value");
6728 for (const auto *U : PreallocatedSetup->users()) {
6729 auto *UseCall = cast<CallBase>(U);
6730 const Function *Fn = UseCall->getCalledFunction();
6731 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6732 return UseCall;
6733 }
6734 }
6735 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6736}
6737
6738/// If DI is a debug value with an EntryValue expression, lower it using the
6739/// corresponding physical register of the associated Argument value
6740/// (guaranteed to exist by the verifier).
6741bool SelectionDAGBuilder::visitEntryValueDbgValue(
6743 DIExpression *Expr, DebugLoc DbgLoc) {
6744 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6745 return false;
6746
6747 // These properties are guaranteed by the verifier.
6748 const Argument *Arg = cast<Argument>(Values[0]);
6749 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6750
6751 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6752 if (ArgIt == FuncInfo.ValueMap.end()) {
6753 LLVM_DEBUG(
6754 dbgs() << "Dropping dbg.value: expression is entry_value but "
6755 "couldn't find an associated register for the Argument\n");
6756 return true;
6757 }
6758 Register ArgVReg = ArgIt->getSecond();
6759
6760 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6761 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6762 SDDbgValue *SDV = DAG.getVRegDbgValue(
6763 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6764 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6765 return true;
6766 }
6767 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6768 "couldn't find a physical register\n");
6769 return true;
6770}
6771
6772/// Lower the call to the specified intrinsic function.
6773void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6774 unsigned Intrinsic) {
6775 SDLoc sdl = getCurSDLoc();
6776 switch (Intrinsic) {
6777 case Intrinsic::experimental_convergence_anchor:
6778 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6779 break;
6780 case Intrinsic::experimental_convergence_entry:
6781 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6782 break;
6783 case Intrinsic::experimental_convergence_loop: {
6784 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6785 auto *Token = Bundle->Inputs[0].get();
6786 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6787 getValue(Token)));
6788 break;
6789 }
6790 }
6791}
6792
6793void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6794 unsigned IntrinsicID) {
6795 // For now, we're only lowering an 'add' histogram.
6796 // We can add others later, e.g. saturating adds, min/max.
6797 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6798 "Tried to lower unsupported histogram type");
6799 SDLoc sdl = getCurSDLoc();
6800 Value *Ptr = I.getOperand(0);
6801 SDValue Inc = getValue(I.getOperand(1));
6802 SDValue Mask = getValue(I.getOperand(2));
6803
6804 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6805 DataLayout TargetDL = DAG.getDataLayout();
6806 EVT VT = Inc.getValueType();
6807 Align Alignment = DAG.getEVTAlign(VT);
6808
6809 const MDNode *Ranges = getRangeMetadata(I);
6810
6811 SDValue Root = DAG.getRoot();
6812 SDValue Base;
6813 SDValue Index;
6814 SDValue Scale;
6815 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6816 I.getParent(), VT.getScalarStoreSize());
6817
6818 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6819
6820 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6821 MachinePointerInfo(AS),
6823 MemoryLocation::UnknownSize, Alignment,
6824 MMOMetadata(I.getAAMetadata(), Ranges));
6825
6826 if (!UniformBase) {
6827 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6828 Index = getValue(Ptr);
6829 Scale =
6830 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6831 }
6832
6833 EVT IdxVT = Index.getValueType();
6834
6835 // Avoid using e.g. i32 as index type when the increment must be performed
6836 // on i64's.
6837 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6838 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6839 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6840 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6841 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6842 }
6843
6844 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6845
6846 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6847 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6848 Ops, MMO, ISD::SIGNED_SCALED);
6849
6850 setValue(&I, Histogram);
6851 DAG.setRoot(Histogram);
6852}
6853
6854void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6855 unsigned Intrinsic) {
6856 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6857 "Tried lowering invalid vector extract last");
6858 SDLoc sdl = getCurSDLoc();
6859 const DataLayout &Layout = DAG.getDataLayout();
6860 SDValue Data = getValue(I.getOperand(0));
6861 SDValue Mask = getValue(I.getOperand(1));
6862
6863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6864 EVT ResVT = TLI.getValueType(Layout, I.getType());
6865
6866 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6867 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6868 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6869
6870 Value *Default = I.getOperand(2);
6872 SDValue PassThru = getValue(Default);
6873 EVT BoolVT = Mask.getValueType().getScalarType();
6874 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6875 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6876 }
6877
6878 setValue(&I, Result);
6879}
6880
6881/// Lower the call to the specified intrinsic function.
6882void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6883 unsigned Intrinsic) {
6884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6885 SDLoc sdl = getCurSDLoc();
6886 DebugLoc dl = getCurDebugLoc();
6887 SDValue Res;
6888
6889 SDNodeFlags Flags;
6890 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6891 Flags.copyFMF(*FPOp);
6892
6893 switch (Intrinsic) {
6894 default:
6895 // By default, turn this into a target intrinsic node.
6896 visitTargetIntrinsic(I, Intrinsic);
6897 return;
6898 case Intrinsic::vscale: {
6899 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6900 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6901 return;
6902 }
6903 case Intrinsic::vastart: visitVAStart(I); return;
6904 case Intrinsic::vaend: visitVAEnd(I); return;
6905 case Intrinsic::vacopy: visitVACopy(I); return;
6906 case Intrinsic::returnaddress:
6907 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6908 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6909 getValue(I.getArgOperand(0))));
6910 return;
6911 case Intrinsic::addressofreturnaddress:
6912 setValue(&I,
6913 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6914 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6915 return;
6916 case Intrinsic::sponentry:
6917 setValue(&I,
6918 DAG.getNode(ISD::SPONENTRY, sdl,
6919 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6920 return;
6921 case Intrinsic::frameaddress:
6922 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6923 TLI.getFrameIndexTy(DAG.getDataLayout()),
6924 getValue(I.getArgOperand(0))));
6925 return;
6926 case Intrinsic::read_volatile_register:
6927 case Intrinsic::read_register: {
6928 Value *Reg = I.getArgOperand(0);
6929 SDValue Chain = getRoot();
6930 SDValue RegName =
6931 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6932 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6933 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6934 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6935 setValue(&I, Res);
6936 DAG.setRoot(Res.getValue(1));
6937 return;
6938 }
6939 case Intrinsic::write_register: {
6940 Value *Reg = I.getArgOperand(0);
6941 Value *RegValue = I.getArgOperand(1);
6942 SDValue Chain = getRoot();
6943 SDValue RegName =
6944 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6945 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6946 RegName, getValue(RegValue)));
6947 return;
6948 }
6949 case Intrinsic::write_volatile_register: {
6950 Value *Reg = I.getArgOperand(0);
6951 Value *RegValue = I.getArgOperand(1);
6952 SDValue Chain = getRoot();
6953 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6954 SDValue RegName = DAG.getMDNode(MD);
6955 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6956 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6957 Chain, RegName, getValue(RegValue));
6958 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6959 // preventing the backend from dead-eliminating the write. This is
6960 // preferred over READ_REGISTER, which would emit extra register copies
6961 // (e.g. fmov xN, dN for FP/SIMD registers).
6962 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6963 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6964 const MachineFunction &MF = DAG.getMachineFunction();
6965 Register PhysReg =
6966 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6967 if (PhysReg.isValid()) {
6968 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6969 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6970 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6971 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6972 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6973 } else {
6974 DAG.setRoot(WriteChain);
6975 }
6976 return;
6977 }
6978 case Intrinsic::memcpy:
6979 case Intrinsic::memcpy_inline: {
6980 const auto &MCI = cast<MemCpyInst>(I);
6981 SDValue Dst = getValue(I.getArgOperand(0));
6982 SDValue Src = getValue(I.getArgOperand(1));
6983 SDValue Size = getValue(I.getArgOperand(2));
6984 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6985 "memcpy_inline needs constant size");
6986 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6987 Align DstAlign = MCI.getDestAlign().valueOrOne();
6988 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6989 bool isVol = MCI.isVolatile();
6990 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6991 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
6992 isVol, MCI.isForceInlined(), &I, std::nullopt,
6993 MachinePointerInfo(I.getArgOperand(0)),
6994 MachinePointerInfo(I.getArgOperand(1)),
6995 I.getAAMetadata(), BatchAA);
6996 updateDAGForMaybeTailCall(MC);
6997 return;
6998 }
6999 case Intrinsic::memset:
7000 case Intrinsic::memset_inline: {
7001 const auto &MSII = cast<MemSetInst>(I);
7002 SDValue Dst = getValue(I.getArgOperand(0));
7003 SDValue Value = getValue(I.getArgOperand(1));
7004 SDValue Size = getValue(I.getArgOperand(2));
7005 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
7006 "memset_inline needs constant size");
7007 // @llvm.memset defines 0 and 1 to both mean no alignment.
7008 Align DstAlign = MSII.getDestAlign().valueOrOne();
7009 bool isVol = MSII.isVolatile();
7010 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7011 SDValue MC = DAG.getMemset(
7012 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
7013 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
7014 updateDAGForMaybeTailCall(MC);
7015 return;
7016 }
7017 case Intrinsic::memmove: {
7018 const auto &MMI = cast<MemMoveInst>(I);
7019 SDValue Op1 = getValue(I.getArgOperand(0));
7020 SDValue Op2 = getValue(I.getArgOperand(1));
7021 SDValue Op3 = getValue(I.getArgOperand(2));
7022 // @llvm.memmove defines 0 and 1 to both mean no alignment.
7023 Align DstAlign = MMI.getDestAlign().valueOrOne();
7024 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
7025 bool isVol = MMI.isVolatile();
7026 SDValue Root = isVol ? getRoot() : getMemoryRoot();
7027 SDValue MM = DAG.getMemmove(
7028 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
7029 /* OverrideTailCall */ std::nullopt,
7030 MachinePointerInfo(I.getArgOperand(0)),
7031 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
7032 updateDAGForMaybeTailCall(MM);
7033 return;
7034 }
7035 case Intrinsic::memcpy_element_unordered_atomic: {
7036 auto &MI = cast<AnyMemCpyInst>(I);
7037 SDValue Dst = getValue(MI.getRawDest());
7038 SDValue Src = getValue(MI.getRawSource());
7039 SDValue Length = getValue(MI.getLength());
7040
7041 Type *LengthTy = MI.getLength()->getType();
7042 unsigned ElemSz = MI.getElementSizeInBytes();
7043 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7044 SDValue MC =
7045 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7046 isTC, MachinePointerInfo(MI.getRawDest()),
7047 MachinePointerInfo(MI.getRawSource()));
7048 updateDAGForMaybeTailCall(MC);
7049 return;
7050 }
7051 case Intrinsic::memmove_element_unordered_atomic: {
7052 auto &MI = cast<AnyMemMoveInst>(I);
7053 SDValue Dst = getValue(MI.getRawDest());
7054 SDValue Src = getValue(MI.getRawSource());
7055 SDValue Length = getValue(MI.getLength());
7056
7057 Type *LengthTy = MI.getLength()->getType();
7058 unsigned ElemSz = MI.getElementSizeInBytes();
7059 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7060 SDValue MC =
7061 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
7062 isTC, MachinePointerInfo(MI.getRawDest()),
7063 MachinePointerInfo(MI.getRawSource()));
7064 updateDAGForMaybeTailCall(MC);
7065 return;
7066 }
7067 case Intrinsic::memset_element_unordered_atomic: {
7068 auto &MI = cast<AnyMemSetInst>(I);
7069 SDValue Dst = getValue(MI.getRawDest());
7070 SDValue Val = getValue(MI.getValue());
7071 SDValue Length = getValue(MI.getLength());
7072
7073 Type *LengthTy = MI.getLength()->getType();
7074 unsigned ElemSz = MI.getElementSizeInBytes();
7075 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
7076 SDValue MC =
7077 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
7078 isTC, MachinePointerInfo(MI.getRawDest()));
7079 updateDAGForMaybeTailCall(MC);
7080 return;
7081 }
7082 case Intrinsic::call_preallocated_setup: {
7083 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
7084 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7085 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
7086 getRoot(), SrcValue);
7087 setValue(&I, Res);
7088 DAG.setRoot(Res);
7089 return;
7090 }
7091 case Intrinsic::call_preallocated_arg: {
7092 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
7093 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
7094 SDValue Ops[3];
7095 Ops[0] = getRoot();
7096 Ops[1] = SrcValue;
7097 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7098 MVT::i32); // arg index
7099 SDValue Res = DAG.getNode(
7101 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
7102 setValue(&I, Res);
7103 DAG.setRoot(Res.getValue(1));
7104 return;
7105 }
7106
7107 case Intrinsic::eh_typeid_for: {
7108 // Find the type id for the given typeinfo.
7109 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
7110 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
7111 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
7112 setValue(&I, Res);
7113 return;
7114 }
7115
7116 case Intrinsic::eh_return_i32:
7117 case Intrinsic::eh_return_i64:
7118 DAG.getMachineFunction().setCallsEHReturn(true);
7119 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
7120 MVT::Other,
7122 getValue(I.getArgOperand(0)),
7123 getValue(I.getArgOperand(1))));
7124 return;
7125 case Intrinsic::eh_unwind_init:
7126 DAG.getMachineFunction().setCallsUnwindInit(true);
7127 return;
7128 case Intrinsic::eh_dwarf_cfa:
7129 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
7130 TLI.getPointerTy(DAG.getDataLayout()),
7131 getValue(I.getArgOperand(0))));
7132 return;
7133 case Intrinsic::eh_sjlj_callsite: {
7134 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
7135 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
7136
7137 FuncInfo.setCurrentCallSite(CI->getZExtValue());
7138 return;
7139 }
7140 case Intrinsic::eh_sjlj_functioncontext: {
7141 // Get and store the index of the function context.
7142 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7143 AllocaInst *FnCtx =
7144 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
7145 int FI = FuncInfo.StaticAllocaMap[FnCtx];
7147 return;
7148 }
7149 case Intrinsic::eh_sjlj_setjmp: {
7150 SDValue Ops[2];
7151 Ops[0] = getRoot();
7152 Ops[1] = getValue(I.getArgOperand(0));
7153 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
7154 DAG.getVTList(MVT::i32, MVT::Other), Ops);
7155 setValue(&I, Op.getValue(0));
7156 DAG.setRoot(Op.getValue(1));
7157 return;
7158 }
7159 case Intrinsic::eh_sjlj_longjmp:
7160 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
7161 getRoot(), getValue(I.getArgOperand(0))));
7162 return;
7163 case Intrinsic::eh_sjlj_setup_dispatch:
7164 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
7165 getRoot()));
7166 return;
7167 case Intrinsic::masked_gather:
7168 visitMaskedGather(I);
7169 return;
7170 case Intrinsic::masked_load:
7171 visitMaskedLoad(I);
7172 return;
7173 case Intrinsic::masked_scatter:
7174 visitMaskedScatter(I);
7175 return;
7176 case Intrinsic::masked_store:
7177 visitMaskedStore(I);
7178 return;
7179 case Intrinsic::masked_expandload:
7180 visitMaskedLoad(I, true /* IsExpanding */);
7181 return;
7182 case Intrinsic::masked_compressstore:
7183 visitMaskedStore(I, true /* IsCompressing */);
7184 return;
7185 case Intrinsic::speculative_load:
7186 visitSpeculativeLoad(I);
7187 return;
7188 case Intrinsic::powi:
7189 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
7190 getValue(I.getArgOperand(1)), DAG));
7191 return;
7192 case Intrinsic::log:
7193 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7194 return;
7195 case Intrinsic::log2:
7196 setValue(&I,
7197 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7198 return;
7199 case Intrinsic::log10:
7200 setValue(&I,
7201 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7202 return;
7203 case Intrinsic::exp:
7204 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7205 return;
7206 case Intrinsic::exp2:
7207 setValue(&I,
7208 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7209 return;
7210 case Intrinsic::pow:
7211 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7212 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7213 return;
7214 case Intrinsic::sqrt:
7215 case Intrinsic::fabs:
7216 case Intrinsic::sin:
7217 case Intrinsic::cos:
7218 case Intrinsic::tan:
7219 case Intrinsic::asin:
7220 case Intrinsic::acos:
7221 case Intrinsic::atan:
7222 case Intrinsic::sinh:
7223 case Intrinsic::cosh:
7224 case Intrinsic::tanh:
7225 case Intrinsic::exp10:
7226 case Intrinsic::floor:
7227 case Intrinsic::ceil:
7228 case Intrinsic::trunc:
7229 case Intrinsic::rint:
7230 case Intrinsic::nearbyint:
7231 case Intrinsic::round:
7232 case Intrinsic::roundeven:
7233 case Intrinsic::canonicalize: {
7234 unsigned Opcode;
7235 // clang-format off
7236 switch (Intrinsic) {
7237 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7238 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7239 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7240 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7241 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7242 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7243 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7244 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7245 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7246 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7247 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7248 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7249 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7250 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7251 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7252 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7253 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7254 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7255 case Intrinsic::round: Opcode = ISD::FROUND; break;
7256 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7257 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7258 }
7259 // clang-format on
7260
7261 setValue(&I, DAG.getNode(Opcode, sdl,
7262 getValue(I.getArgOperand(0)).getValueType(),
7263 getValue(I.getArgOperand(0)), Flags));
7264 return;
7265 }
7266 case Intrinsic::atan2:
7267 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7268 getValue(I.getArgOperand(0)).getValueType(),
7269 getValue(I.getArgOperand(0)),
7270 getValue(I.getArgOperand(1)), Flags));
7271 return;
7272 case Intrinsic::lround:
7273 case Intrinsic::llround:
7274 case Intrinsic::lrint:
7275 case Intrinsic::llrint: {
7276 unsigned Opcode;
7277 // clang-format off
7278 switch (Intrinsic) {
7279 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7280 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7281 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7282 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7283 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7284 }
7285 // clang-format on
7286
7287 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7288 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7289 getValue(I.getArgOperand(0))));
7290 return;
7291 }
7292 case Intrinsic::minnum:
7293 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7294 getValue(I.getArgOperand(0)).getValueType(),
7295 getValue(I.getArgOperand(0)),
7296 getValue(I.getArgOperand(1)), Flags));
7297 return;
7298 case Intrinsic::maxnum:
7299 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7300 getValue(I.getArgOperand(0)).getValueType(),
7301 getValue(I.getArgOperand(0)),
7302 getValue(I.getArgOperand(1)), Flags));
7303 return;
7304 case Intrinsic::minimum:
7305 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7306 getValue(I.getArgOperand(0)).getValueType(),
7307 getValue(I.getArgOperand(0)),
7308 getValue(I.getArgOperand(1)), Flags));
7309 return;
7310 case Intrinsic::maximum:
7311 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7312 getValue(I.getArgOperand(0)).getValueType(),
7313 getValue(I.getArgOperand(0)),
7314 getValue(I.getArgOperand(1)), Flags));
7315 return;
7316 case Intrinsic::minimumnum:
7317 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7318 getValue(I.getArgOperand(0)).getValueType(),
7319 getValue(I.getArgOperand(0)),
7320 getValue(I.getArgOperand(1)), Flags));
7321 return;
7322 case Intrinsic::maximumnum:
7323 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7324 getValue(I.getArgOperand(0)).getValueType(),
7325 getValue(I.getArgOperand(0)),
7326 getValue(I.getArgOperand(1)), Flags));
7327 return;
7328 case Intrinsic::copysign:
7329 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7330 getValue(I.getArgOperand(0)).getValueType(),
7331 getValue(I.getArgOperand(0)),
7332 getValue(I.getArgOperand(1)), Flags));
7333 return;
7334 case Intrinsic::ldexp:
7335 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7336 getValue(I.getArgOperand(0)).getValueType(),
7337 getValue(I.getArgOperand(0)),
7338 getValue(I.getArgOperand(1)), Flags));
7339 return;
7340 case Intrinsic::modf:
7341 case Intrinsic::sincos:
7342 case Intrinsic::sincospi:
7343 case Intrinsic::frexp: {
7344 unsigned Opcode;
7345 switch (Intrinsic) {
7346 default:
7347 llvm_unreachable("unexpected intrinsic");
7348 case Intrinsic::sincos:
7349 Opcode = ISD::FSINCOS;
7350 break;
7351 case Intrinsic::sincospi:
7352 Opcode = ISD::FSINCOSPI;
7353 break;
7354 case Intrinsic::modf:
7355 Opcode = ISD::FMODF;
7356 break;
7357 case Intrinsic::frexp:
7358 Opcode = ISD::FFREXP;
7359 break;
7360 }
7361 SmallVector<EVT, 2> ValueVTs;
7362 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7363 SDVTList VTs = DAG.getVTList(ValueVTs);
7364 setValue(
7365 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7366 return;
7367 }
7368 case Intrinsic::arithmetic_fence: {
7369 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7370 getValue(I.getArgOperand(0)).getValueType(),
7371 getValue(I.getArgOperand(0)), Flags));
7372 return;
7373 }
7374 case Intrinsic::fma:
7375 setValue(&I, DAG.getNode(
7376 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7377 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7378 getValue(I.getArgOperand(2)), Flags));
7379 return;
7380#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7381 case Intrinsic::INTRINSIC:
7382#include "llvm/IR/ConstrainedOps.def"
7383 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7384 return;
7385#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7386#include "llvm/IR/VPIntrinsics.def"
7387 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7388 return;
7389 case Intrinsic::fptrunc_round: {
7390 // Get the last argument, the metadata and convert it to an integer in the
7391 // call
7392 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7393 std::optional<RoundingMode> RoundMode =
7394 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7395
7396 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7397
7398 // Propagate fast-math-flags from IR to node(s).
7399 SDNodeFlags Flags;
7400 Flags.copyFMF(*cast<FPMathOperator>(&I));
7401 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7402
7403 SDValue Result;
7404 Result = DAG.getNode(
7405 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7406 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7407 setValue(&I, Result);
7408
7409 return;
7410 }
7411 case Intrinsic::fmuladd: {
7412 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7413 if (TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7414 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7415 getValue(I.getArgOperand(0)).getValueType(),
7416 getValue(I.getArgOperand(0)),
7417 getValue(I.getArgOperand(1)),
7418 getValue(I.getArgOperand(2)), Flags));
7419 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7420 // TODO: Support splitting the vector.
7421 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7422 getValue(I.getArgOperand(0)).getValueType(),
7423 getValue(I.getArgOperand(0)),
7424 getValue(I.getArgOperand(1)),
7425 getValue(I.getArgOperand(2)), Flags));
7426 } else {
7427 // TODO: Intrinsic calls should have fast-math-flags.
7428 SDValue Mul = DAG.getNode(
7429 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7430 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7431 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7432 getValue(I.getArgOperand(0)).getValueType(),
7433 Mul, getValue(I.getArgOperand(2)), Flags);
7434 setValue(&I, Add);
7435 }
7436 return;
7437 }
7438 case Intrinsic::fptosi_sat: {
7439 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7440 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7441 getValue(I.getArgOperand(0)),
7442 DAG.getValueType(VT.getScalarType())));
7443 return;
7444 }
7445 case Intrinsic::fptoui_sat: {
7446 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7447 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7448 getValue(I.getArgOperand(0)),
7449 DAG.getValueType(VT.getScalarType())));
7450 return;
7451 }
7452 case Intrinsic::convert_from_arbitrary_fp: {
7453 // Extract format metadata and convert to semantics enum.
7454 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7455 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7456 StringRef FormatStr = cast<MDString>(MD)->getString();
7457 const fltSemantics *SrcSem =
7459 if (!SrcSem) {
7460 DAG.getContext()->emitError(
7461 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7462 "'");
7463 setValue(&I, DAG.getPOISON(DstVT));
7464 return;
7465 }
7467
7468 SDValue IntVal = getValue(I.getArgOperand(0));
7469
7470 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7471 SDValue SemConst =
7472 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7473 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7474 SemConst));
7475 return;
7476 }
7477 case Intrinsic::convert_to_arbitrary_fp: {
7478 // Extract format metadata and convert to semantics enum.
7479 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7480 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7481 StringRef FormatStr = cast<MDString>(MD)->getString();
7482 const fltSemantics *DstSem =
7484 if (!DstSem) {
7485 DAG.getContext()->emitError(
7486 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7487 "'");
7488 setValue(&I, DAG.getPOISON(DstVT));
7489 return;
7490 }
7492
7493 Metadata *RoundMD =
7494 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7495 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7496 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7497 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7498 "Dynamic rounding mode should have been rejected by the verifier");
7499
7500 uint64_t Saturate =
7501 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7502
7503 SDValue FloatVal = getValue(I.getArgOperand(0));
7504
7505 SDValue SemConst =
7506 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7507 SDValue RoundConst =
7508 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7509 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7510 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7511 SemConst, RoundConst, SatConst));
7512 return;
7513 }
7514 case Intrinsic::set_rounding:
7515 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7516 {getRoot(), getValue(I.getArgOperand(0))});
7517 setValue(&I, Res);
7518 DAG.setRoot(Res.getValue(0));
7519 return;
7520 case Intrinsic::is_fpclass: {
7521 const DataLayout DLayout = DAG.getDataLayout();
7522 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7523 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7524 FPClassTest Test = static_cast<FPClassTest>(
7525 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7526 MachineFunction &MF = DAG.getMachineFunction();
7527 const Function &F = MF.getFunction();
7528 SDValue Op = getValue(I.getArgOperand(0));
7529 SDNodeFlags Flags;
7530 Flags.setNoFPExcept(
7531 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7532 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7533 // expansion can use illegal types. Making expansion early allows
7534 // legalizing these types prior to selection.
7535 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7536 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7537 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7538 setValue(&I, Result);
7539 return;
7540 }
7541
7542 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7543 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7544 setValue(&I, V);
7545 return;
7546 }
7547 case Intrinsic::get_fpenv: {
7548 const DataLayout DLayout = DAG.getDataLayout();
7549 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7550 Align TempAlign = DAG.getEVTAlign(EnvVT);
7551 SDValue Chain = getRoot();
7552 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7553 // and temporary storage in stack.
7554 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7555 Res = DAG.getNode(
7556 ISD::GET_FPENV, sdl,
7557 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7558 MVT::Other),
7559 Chain);
7560 } else {
7561 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7562 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7563 auto MPI =
7564 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7565 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7567 TempAlign);
7568 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7569 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7570 }
7571 setValue(&I, Res);
7572 DAG.setRoot(Res.getValue(1));
7573 return;
7574 }
7575 case Intrinsic::set_fpenv: {
7576 const DataLayout DLayout = DAG.getDataLayout();
7577 SDValue Env = getValue(I.getArgOperand(0));
7578 EVT EnvVT = Env.getValueType();
7579 Align TempAlign = DAG.getEVTAlign(EnvVT);
7580 SDValue Chain = getRoot();
7581 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7582 // environment from memory.
7583 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7584 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7585 } else {
7586 // Allocate space in stack, copy environment bits into it and use this
7587 // memory in SET_FPENV_MEM.
7588 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7589 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7590 auto MPI =
7591 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7592 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7594 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7596 TempAlign);
7597 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7598 }
7599 DAG.setRoot(Chain);
7600 return;
7601 }
7602 case Intrinsic::reset_fpenv:
7603 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7604 return;
7605 case Intrinsic::get_fpmode:
7606 Res = DAG.getNode(
7607 ISD::GET_FPMODE, sdl,
7608 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7609 MVT::Other),
7610 DAG.getRoot());
7611 setValue(&I, Res);
7612 DAG.setRoot(Res.getValue(1));
7613 return;
7614 case Intrinsic::set_fpmode:
7615 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7616 getValue(I.getArgOperand(0)));
7617 DAG.setRoot(Res);
7618 return;
7619 case Intrinsic::reset_fpmode: {
7620 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7621 DAG.setRoot(Res);
7622 return;
7623 }
7624 case Intrinsic::pcmarker: {
7625 SDValue Tmp = getValue(I.getArgOperand(0));
7626 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7627 return;
7628 }
7629 case Intrinsic::readcyclecounter: {
7630 SDValue Op = getRoot();
7631 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7632 DAG.getVTList(MVT::i64, MVT::Other), Op);
7633 setValue(&I, Res);
7634 DAG.setRoot(Res.getValue(1));
7635 return;
7636 }
7637 case Intrinsic::readsteadycounter: {
7638 SDValue Op = getRoot();
7639 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7640 DAG.getVTList(MVT::i64, MVT::Other), Op);
7641 setValue(&I, Res);
7642 DAG.setRoot(Res.getValue(1));
7643 return;
7644 }
7645 case Intrinsic::bitreverse:
7646 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7647 getValue(I.getArgOperand(0)).getValueType(),
7648 getValue(I.getArgOperand(0))));
7649 return;
7650 case Intrinsic::bswap:
7651 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7652 getValue(I.getArgOperand(0)).getValueType(),
7653 getValue(I.getArgOperand(0))));
7654 return;
7655 case Intrinsic::cttz: {
7656 SDValue Arg = getValue(I.getArgOperand(0));
7657 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7658 EVT Ty = Arg.getValueType();
7659 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7660 sdl, Ty, Arg));
7661 return;
7662 }
7663 case Intrinsic::ctlz: {
7664 SDValue Arg = getValue(I.getArgOperand(0));
7665 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7666 EVT Ty = Arg.getValueType();
7667 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7668 sdl, Ty, Arg));
7669 return;
7670 }
7671 case Intrinsic::ctpop: {
7672 SDValue Arg = getValue(I.getArgOperand(0));
7673 EVT Ty = Arg.getValueType();
7674 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7675 return;
7676 }
7677 case Intrinsic::fshl:
7678 case Intrinsic::fshr: {
7679 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7680 SDValue X = getValue(I.getArgOperand(0));
7681 SDValue Y = getValue(I.getArgOperand(1));
7682 SDValue Z = getValue(I.getArgOperand(2));
7683 EVT VT = X.getValueType();
7684
7685 if (X == Y) {
7686 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7687 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7688 } else {
7689 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7690 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7691 }
7692 return;
7693 }
7694 case Intrinsic::clmul: {
7695 SDValue X = getValue(I.getArgOperand(0));
7696 SDValue Y = getValue(I.getArgOperand(1));
7697 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7698 return;
7699 }
7700 case Intrinsic::pext: {
7701 SDValue X = getValue(I.getArgOperand(0));
7702 SDValue Y = getValue(I.getArgOperand(1));
7703 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7704 return;
7705 }
7706 case Intrinsic::pdep: {
7707 SDValue X = getValue(I.getArgOperand(0));
7708 SDValue Y = getValue(I.getArgOperand(1));
7709 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7710 return;
7711 }
7712 case Intrinsic::smulh:
7713 case Intrinsic::umulh: {
7714 auto Opc = Intrinsic == Intrinsic::smulh ? ISD::MULHS : ISD::MULHU;
7715 SDValue X = getValue(I.getArgOperand(0));
7716 SDValue Y = getValue(I.getArgOperand(1));
7717 setValue(&I, DAG.getNode(Opc, sdl, X.getValueType(), X, Y));
7718 return;
7719 }
7720 case Intrinsic::sadd_sat: {
7721 SDValue Op1 = getValue(I.getArgOperand(0));
7722 SDValue Op2 = getValue(I.getArgOperand(1));
7723 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7724 return;
7725 }
7726 case Intrinsic::uadd_sat: {
7727 SDValue Op1 = getValue(I.getArgOperand(0));
7728 SDValue Op2 = getValue(I.getArgOperand(1));
7729 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7730 return;
7731 }
7732 case Intrinsic::ssub_sat: {
7733 SDValue Op1 = getValue(I.getArgOperand(0));
7734 SDValue Op2 = getValue(I.getArgOperand(1));
7735 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7736 return;
7737 }
7738 case Intrinsic::usub_sat: {
7739 SDValue Op1 = getValue(I.getArgOperand(0));
7740 SDValue Op2 = getValue(I.getArgOperand(1));
7741 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7742 return;
7743 }
7744 case Intrinsic::sshl_sat:
7745 case Intrinsic::ushl_sat: {
7746 SDValue Op1 = getValue(I.getArgOperand(0));
7747 SDValue Op2 = getValue(I.getArgOperand(1));
7748
7749 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7750 Op1.getValueType(), DAG.getDataLayout());
7751
7752 // Coerce the shift amount to the right type if we can. This exposes the
7753 // truncate or zext to optimization early.
7754 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7755 assert(ShiftTy.getSizeInBits() >=
7757 "Unexpected shift type");
7758 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7759 }
7760
7761 unsigned Opc =
7762 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7763 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7764 return;
7765 }
7766 case Intrinsic::smul_fix:
7767 case Intrinsic::umul_fix:
7768 case Intrinsic::smul_fix_sat:
7769 case Intrinsic::umul_fix_sat: {
7770 SDValue Op1 = getValue(I.getArgOperand(0));
7771 SDValue Op2 = getValue(I.getArgOperand(1));
7772 SDValue Op3 = getValue(I.getArgOperand(2));
7773 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7774 Op1.getValueType(), Op1, Op2, Op3));
7775 return;
7776 }
7777 case Intrinsic::sdiv_fix:
7778 case Intrinsic::udiv_fix:
7779 case Intrinsic::sdiv_fix_sat:
7780 case Intrinsic::udiv_fix_sat: {
7781 SDValue Op1 = getValue(I.getArgOperand(0));
7782 SDValue Op2 = getValue(I.getArgOperand(1));
7783 SDValue Op3 = getValue(I.getArgOperand(2));
7785 Op1, Op2, Op3, DAG, TLI));
7786 return;
7787 }
7788 case Intrinsic::smax: {
7789 SDValue Op1 = getValue(I.getArgOperand(0));
7790 SDValue Op2 = getValue(I.getArgOperand(1));
7791 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7792 return;
7793 }
7794 case Intrinsic::smin: {
7795 SDValue Op1 = getValue(I.getArgOperand(0));
7796 SDValue Op2 = getValue(I.getArgOperand(1));
7797 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7798 return;
7799 }
7800 case Intrinsic::umax: {
7801 SDValue Op1 = getValue(I.getArgOperand(0));
7802 SDValue Op2 = getValue(I.getArgOperand(1));
7803 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7804 return;
7805 }
7806 case Intrinsic::umin: {
7807 SDValue Op1 = getValue(I.getArgOperand(0));
7808 SDValue Op2 = getValue(I.getArgOperand(1));
7809 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7810 return;
7811 }
7812 case Intrinsic::abs: {
7813 SDValue Op1 = getValue(I.getArgOperand(0));
7814 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7815 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7816 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7817 return;
7818 }
7819 case Intrinsic::scmp: {
7820 SDValue Op1 = getValue(I.getArgOperand(0));
7821 SDValue Op2 = getValue(I.getArgOperand(1));
7822 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7823 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7824 break;
7825 }
7826 case Intrinsic::ucmp: {
7827 SDValue Op1 = getValue(I.getArgOperand(0));
7828 SDValue Op2 = getValue(I.getArgOperand(1));
7829 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7830 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7831 break;
7832 }
7833 case Intrinsic::stackaddress:
7834 case Intrinsic::stacksave: {
7835 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7837 SDValue Op = getRoot();
7838 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7839 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7840 setValue(&I, Res);
7841 DAG.setRoot(Res.getValue(1));
7842 return;
7843 }
7844 case Intrinsic::stackrestore:
7845 Res = getValue(I.getArgOperand(0));
7846 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7847 return;
7848 case Intrinsic::get_dynamic_area_offset: {
7849 SDValue Op = getRoot();
7850 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7851 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7852 Op);
7853 DAG.setRoot(Op);
7854 setValue(&I, Res);
7855 return;
7856 }
7857 case Intrinsic::stackguard: {
7858 MachineFunction &MF = DAG.getMachineFunction();
7859 const Module &M = *MF.getFunction().getParent();
7860 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7861 SDValue Chain = getRoot();
7862 if (TLI.useLoadStackGuardNode(M)) {
7863 Res = getLoadStackGuard(DAG, sdl, Chain);
7864 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7865 } else {
7866 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7867 if (!Global) {
7868 LLVMContext &Ctx = *DAG.getContext();
7869 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7870 setValue(&I, DAG.getPOISON(PtrTy));
7871 return;
7872 }
7873
7874 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7875 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7876 MachinePointerInfo(Global, 0), Align,
7878 }
7879 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7880 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7881 // post-RA expansion of LOAD_STACK_GUARD.
7882 if (TLI.useStackGuardMixFP() && !TLI.useLoadStackGuardNode(M))
7883 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7884 DAG.setRoot(Chain);
7885 setValue(&I, Res);
7886 return;
7887 }
7888 case Intrinsic::stackprotector: {
7889 // Emit code into the DAG to store the stack guard onto the stack.
7890 MachineFunction &MF = DAG.getMachineFunction();
7891 MachineFrameInfo &MFI = MF.getFrameInfo();
7892 const Module &M = *MF.getFunction().getParent();
7893 SDValue Src, Chain = getRoot();
7894
7895 if (TLI.useLoadStackGuardNode(M))
7896 Src = getLoadStackGuard(DAG, sdl, Chain);
7897 else
7898 Src = getValue(I.getArgOperand(0)); // The guard's value.
7899
7900 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7901
7902 int FI = FuncInfo.StaticAllocaMap[Slot];
7903 MFI.setStackProtectorIndex(FI);
7904 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7905
7906 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7907
7908 // Store the stack protector onto the stack.
7909 Res = DAG.getStore(
7910 Chain, sdl, Src, FIN,
7911 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7912 MaybeAlign(), MachineMemOperand::MOVolatile);
7913 setValue(&I, Res);
7914 DAG.setRoot(Res);
7915 return;
7916 }
7917 case Intrinsic::objectsize:
7918 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7919
7920 case Intrinsic::is_constant:
7921 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7922
7923 case Intrinsic::annotation:
7924 case Intrinsic::ptr_annotation:
7925 case Intrinsic::launder_invariant_group:
7926 // Drop the intrinsic, but forward the value
7927 setValue(&I, getValue(I.getOperand(0)));
7928 return;
7929
7930 case Intrinsic::type_test:
7931 case Intrinsic::public_type_test:
7932 case Intrinsic::type_checked_load:
7933 case Intrinsic::type_checked_load_relative: {
7934 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7935 // before code generation. Surviving until here usually indicates a
7936 // misconfiguration, for instance when devirtualization is enabled but LTO
7937 // does not actually run.
7938 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7939 *I.getFunction(),
7940 Intrinsic::getBaseName(Intrinsic) +
7941 " intrinsic must be lowered by the LowerTypeTests pass "
7942 "before code generation",
7943 sdl.getDebugLoc()));
7944
7945 // Lower the result to poison so that compilation can continue and collect
7946 // any further diagnostics.
7947 setValueToPoison(&I, sdl);
7948 return;
7949 }
7950
7951 case Intrinsic::assume:
7952 case Intrinsic::experimental_noalias_scope_decl:
7953 case Intrinsic::var_annotation:
7954 case Intrinsic::sideeffect:
7955 // Discard annotate attributes, noalias scope declarations, assumptions, and
7956 // artificial side-effects.
7957 return;
7958
7959 case Intrinsic::codeview_annotation: {
7960 // Emit a label associated with this metadata.
7961 MachineFunction &MF = DAG.getMachineFunction();
7962 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7963 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7964 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7965 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7966 DAG.setRoot(Res);
7967 return;
7968 }
7969
7970 case Intrinsic::init_trampoline: {
7971 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7972
7973 SDValue Ops[6];
7974 Ops[0] = getRoot();
7975 Ops[1] = getValue(I.getArgOperand(0));
7976 Ops[2] = getValue(I.getArgOperand(1));
7977 Ops[3] = getValue(I.getArgOperand(2));
7978 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7979 Ops[5] = DAG.getSrcValue(F);
7980
7981 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7982
7983 DAG.setRoot(Res);
7984 return;
7985 }
7986 case Intrinsic::adjust_trampoline:
7987 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7988 TLI.getPointerTy(DAG.getDataLayout()),
7989 getValue(I.getArgOperand(0))));
7990 return;
7991 case Intrinsic::gcroot: {
7992 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7993 "only valid in functions with gc specified, enforced by Verifier");
7994 assert(GFI && "implied by previous");
7995 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7996 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7997
7998 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7999 GFI->addStackRoot(FI->getIndex(), TypeMap);
8000 return;
8001 }
8002 case Intrinsic::gcread:
8003 case Intrinsic::gcwrite:
8004 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
8005 case Intrinsic::get_rounding:
8006 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
8007 setValue(&I, Res);
8008 DAG.setRoot(Res.getValue(1));
8009 return;
8010
8011 case Intrinsic::expect:
8012 case Intrinsic::expect_with_probability:
8013 // Just replace __builtin_expect(exp, c) and
8014 // __builtin_expect_with_probability(exp, c, p) with EXP.
8015 setValue(&I, getValue(I.getArgOperand(0)));
8016 return;
8017
8018 case Intrinsic::ubsantrap:
8019 case Intrinsic::debugtrap:
8020 case Intrinsic::trap: {
8021 StringRef TrapFuncName =
8022 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
8023 if (TrapFuncName.empty()) {
8024 switch (Intrinsic) {
8025 case Intrinsic::trap:
8026 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
8027 break;
8028 case Intrinsic::debugtrap:
8029 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
8030 break;
8031 case Intrinsic::ubsantrap:
8032 DAG.setRoot(DAG.getNode(
8033 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
8034 DAG.getTargetConstant(
8035 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
8036 MVT::i32)));
8037 break;
8038 default: llvm_unreachable("unknown trap intrinsic");
8039 }
8040 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
8041 I.hasFnAttr(Attribute::NoMerge));
8042 return;
8043 }
8045 if (Intrinsic == Intrinsic::ubsantrap) {
8046 Value *Arg = I.getArgOperand(0);
8047 Args.emplace_back(Arg, getValue(Arg),
8048 LibInfo->getExtAttrForI8Param(/*Signed=*/false));
8049 }
8050
8051 TargetLowering::CallLoweringInfo CLI(DAG);
8052 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
8053 CallingConv::C, I.getType(),
8054 DAG.getExternalSymbol(TrapFuncName.data(),
8055 TLI.getPointerTy(DAG.getDataLayout())),
8056 std::move(Args));
8057 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
8058 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8059 DAG.setRoot(Result.second);
8060 return;
8061 }
8062
8063 case Intrinsic::allow_runtime_check:
8064 case Intrinsic::allow_ubsan_check:
8065 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
8066 return;
8067
8068 case Intrinsic::uadd_with_overflow:
8069 case Intrinsic::sadd_with_overflow:
8070 case Intrinsic::usub_with_overflow:
8071 case Intrinsic::ssub_with_overflow:
8072 case Intrinsic::umul_with_overflow:
8073 case Intrinsic::smul_with_overflow: {
8075 switch (Intrinsic) {
8076 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8077 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
8078 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
8079 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
8080 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
8081 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
8082 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
8083 }
8084 SDValue Op1 = getValue(I.getArgOperand(0));
8085 SDValue Op2 = getValue(I.getArgOperand(1));
8086
8087 EVT ResultVT = Op1.getValueType();
8088 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
8089
8090 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
8091 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
8092 return;
8093 }
8094 case Intrinsic::prefetch: {
8095 SDValue Ops[5];
8096 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8098 Ops[0] = DAG.getRoot();
8099 Ops[1] = getValue(I.getArgOperand(0));
8100 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
8101 MVT::i32);
8102 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
8103 MVT::i32);
8104 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
8105 MVT::i32);
8106 SDValue Result = DAG.getMemIntrinsicNode(
8107 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
8108 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
8109 /* align */ std::nullopt, Flags);
8110
8111 // Chain the prefetch in parallel with any pending loads, to stay out of
8112 // the way of later optimizations.
8113 PendingLoads.push_back(Result);
8114 Result = getRoot();
8115 DAG.setRoot(Result);
8116 return;
8117 }
8118 case Intrinsic::lifetime_start:
8119 case Intrinsic::lifetime_end: {
8120 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
8121 // Stack coloring is not enabled in O0, discard region information.
8122 if (TM.getOptLevel() == CodeGenOptLevel::None)
8123 return;
8124
8125 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
8126 if (!LifetimeObject)
8127 return;
8128
8129 // First check that the Alloca is static, otherwise it won't have a
8130 // valid frame index.
8131 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
8132 if (SI == FuncInfo.StaticAllocaMap.end())
8133 return;
8134
8135 const int FrameIndex = SI->second;
8136 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
8137 DAG.setRoot(Res);
8138 return;
8139 }
8140 case Intrinsic::pseudoprobe: {
8141 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
8142 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
8143 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
8144 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
8145 DAG.setRoot(Res);
8146 return;
8147 }
8148 case Intrinsic::invariant_start:
8149 // Discard region information.
8150 setValue(&I,
8151 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
8152 return;
8153 case Intrinsic::invariant_end:
8154 // Discard region information.
8155 return;
8156 case Intrinsic::clear_cache: {
8157 SDValue InputChain = DAG.getRoot();
8158 SDValue StartVal = getValue(I.getArgOperand(0));
8159 SDValue EndVal = getValue(I.getArgOperand(1));
8160 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
8161 {InputChain, StartVal, EndVal});
8162 setValue(&I, Res);
8163 DAG.setRoot(Res);
8164 return;
8165 }
8166 case Intrinsic::donothing:
8167 case Intrinsic::seh_try_begin:
8168 case Intrinsic::seh_scope_begin:
8169 case Intrinsic::seh_try_end:
8170 case Intrinsic::seh_scope_end:
8171 // ignore
8172 return;
8173 case Intrinsic::experimental_stackmap:
8174 visitStackmap(I);
8175 return;
8176 case Intrinsic::experimental_patchpoint_void:
8177 case Intrinsic::experimental_patchpoint:
8178 visitPatchpoint(I);
8179 return;
8180 case Intrinsic::experimental_gc_statepoint:
8182 return;
8183 case Intrinsic::experimental_gc_result:
8184 visitGCResult(cast<GCResultInst>(I));
8185 return;
8186 case Intrinsic::experimental_gc_relocate:
8187 visitGCRelocate(cast<GCRelocateInst>(I));
8188 return;
8189 case Intrinsic::instrprof_cover:
8190 llvm_unreachable("instrprof failed to lower a cover");
8191 case Intrinsic::instrprof_increment:
8192 llvm_unreachable("instrprof failed to lower an increment");
8193 case Intrinsic::instrprof_timestamp:
8194 llvm_unreachable("instrprof failed to lower a timestamp");
8195 case Intrinsic::instrprof_value_profile:
8196 llvm_unreachable("instrprof failed to lower a value profiling call");
8197 case Intrinsic::instrprof_mcdc_parameters:
8198 llvm_unreachable("instrprof failed to lower mcdc parameters");
8199 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8200 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8201 case Intrinsic::localescape: {
8202 MachineFunction &MF = DAG.getMachineFunction();
8203 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8204
8205 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8206 // is the same on all targets.
8207 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8208 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8209 if (isa<ConstantPointerNull>(Arg))
8210 continue; // Skip null pointers. They represent a hole in index space.
8211 AllocaInst *Slot = cast<AllocaInst>(Arg);
8212 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8213 "can only escape static allocas");
8214 int FI = FuncInfo.StaticAllocaMap[Slot];
8215 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8217 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8218 TII->get(TargetOpcode::LOCAL_ESCAPE))
8219 .addSym(FrameAllocSym)
8220 .addFrameIndex(FI);
8221 }
8222
8223 return;
8224 }
8225
8226 case Intrinsic::localrecover: {
8227 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8228 MachineFunction &MF = DAG.getMachineFunction();
8229
8230 // Get the symbol that defines the frame offset.
8231 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8232 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8233 unsigned IdxVal =
8234 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8235 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8237
8238 Value *FP = I.getArgOperand(1);
8239 SDValue FPVal = getValue(FP);
8240 EVT PtrVT = FPVal.getValueType();
8241
8242 // Create a MCSymbol for the label to avoid any target lowering
8243 // that would make this PC relative.
8244 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8245 SDValue OffsetVal =
8246 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8247
8248 // Add the offset to the FP.
8249 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8250 setValue(&I, Add);
8251
8252 return;
8253 }
8254
8255 case Intrinsic::fake_use: {
8256 Value *V = I.getArgOperand(0);
8257 SDValue Ops[2];
8258 // For Values not declared or previously used in this basic block, the
8259 // NodeMap will not have an entry, and `getValue` will assert if V has no
8260 // valid register value.
8261 auto FakeUseValue = [&]() -> SDValue {
8262 SDValue &N = NodeMap[V];
8263 if (N.getNode())
8264 return N;
8265
8266 // If there's a virtual register allocated and initialized for this
8267 // value, use it.
8268 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8269 return copyFromReg;
8270 // FIXME: Do we want to preserve constants? It seems pointless.
8271 if (isa<Constant>(V))
8272 return getValue(V);
8273 return SDValue();
8274 }();
8275 if (!FakeUseValue || FakeUseValue.isUndef())
8276 return;
8277 Ops[0] = getRoot();
8278 Ops[1] = FakeUseValue;
8279 // Also, do not translate a fake use with an undef operand, or any other
8280 // empty SDValues.
8281 if (!Ops[1] || Ops[1].isUndef())
8282 return;
8283 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8284 return;
8285 }
8286
8287 case Intrinsic::reloc_none: {
8288 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8289 StringRef SymbolName = cast<MDString>(MD)->getString();
8290 SDValue Ops[2] = {
8291 getRoot(),
8292 DAG.getTargetExternalSymbol(
8293 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8294 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8295 return;
8296 }
8297
8298 case Intrinsic::cond_loop: {
8299 SDValue InputChain = DAG.getRoot();
8300 SDValue P = getValue(I.getArgOperand(0));
8301 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8302 {InputChain, P});
8303 setValue(&I, Res);
8304 DAG.setRoot(Res);
8305 return;
8306 }
8307
8308 case Intrinsic::eh_exceptionpointer:
8309 case Intrinsic::eh_exceptioncode: {
8310 // Get the exception pointer vreg, copy from it, and resize it to fit.
8311 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8312 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8313 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8314 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8315 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8316 if (Intrinsic == Intrinsic::eh_exceptioncode)
8317 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8318 setValue(&I, N);
8319 return;
8320 }
8321 case Intrinsic::xray_customevent: {
8322 // Here we want to make sure that the intrinsic behaves as if it has a
8323 // specific calling convention.
8324 const auto &Triple = DAG.getTarget().getTargetTriple();
8325 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8326 Triple.getArch() != Triple::hexagon)
8327 return;
8328
8330
8331 // We want to say that we always want the arguments in registers.
8332 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8333 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8334 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8335 SDValue Chain = getRoot();
8336 Ops.push_back(LogEntryVal);
8337 Ops.push_back(StrSizeVal);
8338 Ops.push_back(Chain);
8339
8340 // We need to enforce the calling convention for the callsite, so that
8341 // argument ordering is enforced correctly, and that register allocation can
8342 // see that some registers may be assumed clobbered and have to preserve
8343 // them across calls to the intrinsic.
8344 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8345 sdl, NodeTys, Ops);
8346 SDValue patchableNode = SDValue(MN, 0);
8347 DAG.setRoot(patchableNode);
8348 setValue(&I, patchableNode);
8349 return;
8350 }
8351 case Intrinsic::xray_typedevent: {
8352 // Here we want to make sure that the intrinsic behaves as if it has a
8353 // specific calling convention.
8354 const auto &Triple = DAG.getTarget().getTargetTriple();
8355 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8356 Triple.getArch() != Triple::hexagon)
8357 return;
8358
8360
8361 // We want to say that we always want the arguments in registers.
8362 // It's unclear to me how manipulating the selection DAG here forces callers
8363 // to provide arguments in registers instead of on the stack.
8364 SDValue LogTypeId = getValue(I.getArgOperand(0));
8365 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8366 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8367 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8368 SDValue Chain = getRoot();
8369 Ops.push_back(LogTypeId);
8370 Ops.push_back(LogEntryVal);
8371 Ops.push_back(StrSizeVal);
8372 Ops.push_back(Chain);
8373
8374 // We need to enforce the calling convention for the callsite, so that
8375 // argument ordering is enforced correctly, and that register allocation can
8376 // see that some registers may be assumed clobbered and have to preserve
8377 // them across calls to the intrinsic.
8378 MachineSDNode *MN = DAG.getMachineNode(
8379 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8380 SDValue patchableNode = SDValue(MN, 0);
8381 DAG.setRoot(patchableNode);
8382 setValue(&I, patchableNode);
8383 return;
8384 }
8385 case Intrinsic::experimental_deoptimize:
8387 return;
8388 case Intrinsic::stepvector:
8389 visitStepVector(I);
8390 return;
8391 case Intrinsic::vector_reduce_fadd:
8392 case Intrinsic::vector_reduce_fmul:
8393 case Intrinsic::vector_reduce_add:
8394 case Intrinsic::vector_reduce_mul:
8395 case Intrinsic::vector_reduce_and:
8396 case Intrinsic::vector_reduce_or:
8397 case Intrinsic::vector_reduce_xor:
8398 case Intrinsic::vector_reduce_smax:
8399 case Intrinsic::vector_reduce_smin:
8400 case Intrinsic::vector_reduce_umax:
8401 case Intrinsic::vector_reduce_umin:
8402 case Intrinsic::vector_reduce_fmax:
8403 case Intrinsic::vector_reduce_fmin:
8404 case Intrinsic::vector_reduce_fmaximum:
8405 case Intrinsic::vector_reduce_fminimum:
8406 case Intrinsic::vector_reduce_fmaximumnum:
8407 case Intrinsic::vector_reduce_fminimumnum:
8408 visitVectorReduce(I, Intrinsic);
8409 return;
8410
8411 case Intrinsic::icall_branch_funnel: {
8413 Ops.push_back(getValue(I.getArgOperand(0)));
8414
8415 int64_t Offset;
8417 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8418 if (!Base)
8420 "llvm.icall.branch.funnel operand must be a GlobalValue");
8421 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8422
8423 struct BranchFunnelTarget {
8424 int64_t Offset;
8425 SDValue Target;
8426 };
8428
8429 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8431 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8432 if (ElemBase != Base)
8433 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8434 "to the same GlobalValue");
8435
8436 SDValue Val = getValue(I.getArgOperand(Op + 1));
8437 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8438 if (!GA)
8440 "llvm.icall.branch.funnel operand must be a GlobalValue");
8441 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8442 GA->getGlobal(), sdl, Val.getValueType(),
8443 GA->getOffset())});
8444 }
8445 llvm::sort(Targets,
8446 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8447 return T1.Offset < T2.Offset;
8448 });
8449
8450 for (auto &T : Targets) {
8451 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8452 Ops.push_back(T.Target);
8453 }
8454
8455 Ops.push_back(DAG.getRoot()); // Chain
8456 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8457 MVT::Other, Ops),
8458 0);
8459 DAG.setRoot(N);
8460 setValue(&I, N);
8461 HasTailCall = true;
8462 return;
8463 }
8464
8465 case Intrinsic::wasm_landingpad_index:
8466 // Information this intrinsic contained has been transferred to
8467 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8468 // delete it now.
8469 return;
8470
8471 case Intrinsic::aarch64_settag:
8472 case Intrinsic::aarch64_settag_zero: {
8473 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8474 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8475 SDValue Val = TSI.EmitTargetCodeForSetTag(
8476 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8477 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8478 ZeroMemory);
8479 DAG.setRoot(Val);
8480 setValue(&I, Val);
8481 return;
8482 }
8483 case Intrinsic::amdgcn_cs_chain: {
8484 // At this point we don't care if it's amdgpu_cs_chain or
8485 // amdgpu_cs_chain_preserve.
8487
8488 Type *RetTy = I.getType();
8489 assert(RetTy->isVoidTy() && "Should not return");
8490
8491 SDValue Callee = getValue(I.getOperand(0));
8492
8493 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8494 // We'll also tack the value of the EXEC mask at the end.
8496 Args.reserve(3);
8497
8498 for (unsigned Idx : {2, 3, 1}) {
8499 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8500 I.getOperand(Idx)->getType());
8501 Arg.setAttributes(&I, Idx);
8502 Args.push_back(Arg);
8503 }
8504
8505 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8506 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8507 Args[2].IsInReg = true; // EXEC should be inreg
8508
8509 // Forward the flags and any additional arguments.
8510 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8511 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8512 I.getOperand(Idx)->getType());
8513 Arg.setAttributes(&I, Idx);
8514 Args.push_back(Arg);
8515 }
8516
8517 TargetLowering::CallLoweringInfo CLI(DAG);
8518 CLI.setDebugLoc(getCurSDLoc())
8519 .setChain(getRoot())
8520 .setCallee(CC, RetTy, Callee, std::move(Args))
8521 .setNoReturn(true)
8522 .setTailCall(true)
8523 .setConvergent(I.isConvergent());
8524 CLI.CB = &I;
8525 std::pair<SDValue, SDValue> Result =
8526 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8527 (void)Result;
8528 assert(!Result.first.getNode() && !Result.second.getNode() &&
8529 "Should've lowered as tail call");
8530
8531 HasTailCall = true;
8532 return;
8533 }
8534 case Intrinsic::amdgcn_call_whole_wave: {
8536 bool isTailCall = I.isTailCall();
8537
8538 // The first argument is the callee. Skip it when assembling the call args.
8539 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8540 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8541 I.getArgOperand(Idx)->getType());
8542 Arg.setAttributes(&I, Idx);
8543
8544 // If we have an explicit sret argument that is an Instruction, (i.e., it
8545 // might point to function-local memory), we can't meaningfully tail-call.
8546 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8547 isTailCall = false;
8548
8549 Args.push_back(Arg);
8550 }
8551
8552 SDValue ConvControlToken;
8553 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8554 auto *Token = Bundle->Inputs[0].get();
8555 ConvControlToken = getValue(Token);
8556 }
8557
8558 TargetLowering::CallLoweringInfo CLI(DAG);
8559 CLI.setDebugLoc(getCurSDLoc())
8560 .setChain(getRoot())
8561 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8562 getValue(I.getArgOperand(0)), std::move(Args))
8563 .setTailCall(isTailCall && canTailCall(I))
8564 .setIsPreallocated(
8565 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8566 .setConvergent(I.isConvergent())
8567 .setConvergenceControlToken(ConvControlToken);
8568 CLI.CB = &I;
8569
8570 std::pair<SDValue, SDValue> Result =
8571 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8572
8573 if (Result.first.getNode())
8574 setValue(&I, Result.first);
8575 return;
8576 }
8577 case Intrinsic::ptrmask: {
8578 SDValue Ptr = getValue(I.getOperand(0));
8579 SDValue Mask = getValue(I.getOperand(1));
8580
8581 // On arm64_32, pointers are 32 bits when stored in memory, but
8582 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8583 // match the index type, but the pointer is 64 bits, so the mask must be
8584 // zero-extended up to 64 bits to match the pointer.
8585 EVT PtrVT =
8586 TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8587 EVT MemVT =
8588 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8589 assert(PtrVT == Ptr.getValueType());
8590 if (Mask.getValueType().getFixedSizeInBits() < MemVT.getFixedSizeInBits()) {
8591 // For AMDGPU buffer descriptors the mask is 48 bits, but the pointer is
8592 // 128-bit, so we have to pad the mask with ones for unused bits.
8593 auto HighOnes = DAG.getNode(
8594 ISD::SHL, sdl, PtrVT, DAG.getAllOnesConstant(sdl, PtrVT),
8595 DAG.getShiftAmountConstant(Mask.getValueType().getFixedSizeInBits(),
8596 PtrVT, sdl));
8597 Mask = DAG.getNode(ISD::OR, sdl, PtrVT,
8598 DAG.getZExtOrTrunc(Mask, sdl, PtrVT), HighOnes);
8599 } else if (Mask.getValueType() != PtrVT)
8600 Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8601
8602 assert(Mask.getValueType() == PtrVT);
8603 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8604 return;
8605 }
8606 case Intrinsic::threadlocal_address: {
8607 setValue(&I, getValue(I.getOperand(0)));
8608 return;
8609 }
8610 case Intrinsic::get_active_lane_mask: {
8611 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8612 SDValue Index = getValue(I.getOperand(0));
8613 SDValue TripCount = getValue(I.getOperand(1));
8614 EVT ElementVT = Index.getValueType();
8615
8616 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8617 setValue(&I, DAG.getNode(ISD::GET_ACTIVE_LANE_MASK, sdl, CCVT, Index,
8618 TripCount));
8619 return;
8620 }
8621
8622 EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8623 CCVT.getVectorElementCount());
8624
8625 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8626 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8627 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8628 SDValue VectorInduction = DAG.getNode(
8629 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8630 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8631 VectorTripCount, ISD::CondCode::SETULT);
8632 setValue(&I, SetCC);
8633 return;
8634 }
8635 case Intrinsic::mask_beforefirst: {
8636 SDValue Op = getValue(I.getOperand(0));
8637 setValue(&I,
8638 DAG.getNode(ISD::MASK_BEFOREFIRST, sdl, Op.getValueType(), Op));
8639 return;
8640 }
8641 case Intrinsic::experimental_get_vector_length: {
8642 assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8643 "Expected positive VF");
8644 unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8645 bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8646
8647 SDValue Count = getValue(I.getOperand(0));
8648 EVT CountVT = Count.getValueType();
8649
8650 if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8651 visitTargetIntrinsic(I, Intrinsic);
8652 return;
8653 }
8654
8655 // Expand to a umin between the trip count and the maximum elements the type
8656 // can hold.
8657 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8658
8659 // Extend the trip count to at least the result VT.
8660 if (CountVT.bitsLT(VT)) {
8661 Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8662 CountVT = VT;
8663 }
8664
8665 SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8666 ElementCount::get(VF, IsScalable));
8667
8668 SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8669 // Clip to the result type if needed.
8670 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8671
8672 setValue(&I, Trunc);
8673 return;
8674 }
8675 case Intrinsic::vector_partial_reduce_add: {
8676 SDValue Acc = getValue(I.getOperand(0));
8677 SDValue Input = getValue(I.getOperand(1));
8678 setValue(&I,
8679 DAG.getNode(ISD::PARTIAL_REDUCE_UMLA, sdl, Acc.getValueType(), Acc,
8680 Input, DAG.getConstant(1, sdl, Input.getValueType())));
8681 return;
8682 }
8683 case Intrinsic::vector_partial_reduce_fadd: {
8684 SDNodeFlags Flags;
8685 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
8686 Flags.copyFMF(*FPOp);
8687 SDValue Acc = getValue(I.getOperand(0));
8688 SDValue Input = getValue(I.getOperand(1));
8689 setValue(&I, DAG.getNode(ISD::PARTIAL_REDUCE_FMLA, sdl, Acc.getValueType(),
8690 Acc, Input,
8691 DAG.getConstantFP(1.0, sdl, Input.getValueType()),
8692 Flags));
8693 return;
8694 }
8695 case Intrinsic::experimental_cttz_elts: {
8696 SDValue Op = getValue(I.getOperand(0));
8697 EVT OpVT = Op.getValueType();
8698 EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8699 bool ZeroIsPoison =
8700 !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8701 if (OpVT.getVectorElementType() != MVT::i1) {
8702 // Compare the input vector elements to zero & use to count trailing
8703 // zeros.
8704 SDValue AllZero = DAG.getConstant(0, sdl, OpVT);
8705 EVT I1OpVT = OpVT.changeVectorElementType(*DAG.getContext(), MVT::i1);
8706 Op = DAG.getSetCC(sdl, I1OpVT, Op, AllZero, ISD::SETNE);
8707 }
8708 setValue(&I, DAG.getNode(ZeroIsPoison ? ISD::CTTZ_ELTS_ZERO_POISON
8710 sdl, RetTy, Op));
8711 return;
8712 }
8713 case Intrinsic::vector_insert: {
8714 SDValue Vec = getValue(I.getOperand(0));
8715 SDValue SubVec = getValue(I.getOperand(1));
8716 SDValue Index = getValue(I.getOperand(2));
8717
8718 // The intrinsic's index type is i64, but the SDNode requires an index type
8719 // suitable for the target. Convert the index as required.
8720 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8721 if (Index.getValueType() != VectorIdxTy)
8722 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8723
8724 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8725 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8726 Index));
8727 return;
8728 }
8729 case Intrinsic::vector_extract: {
8730 SDValue Vec = getValue(I.getOperand(0));
8731 SDValue Index = getValue(I.getOperand(1));
8732 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8733
8734 // The intrinsic's index type is i64, but the SDNode requires an index type
8735 // suitable for the target. Convert the index as required.
8736 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8737 if (Index.getValueType() != VectorIdxTy)
8738 Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8739
8740 setValue(&I,
8741 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8742 return;
8743 }
8744 case Intrinsic::experimental_vector_match: {
8745 SDValue Op1 = getValue(I.getOperand(0));
8746 SDValue Op2 = getValue(I.getOperand(1));
8747 SDValue Mask = getValue(I.getOperand(2));
8748 EVT ResVT = Mask.getValueType();
8749 setValue(&I, DAG.getNode(ISD::VECTOR_MATCH, sdl, ResVT, Op1, Op2, Mask));
8750 return;
8751 }
8752 case Intrinsic::vector_reverse:
8753 visitVectorReverse(I);
8754 return;
8755 case Intrinsic::vector_splice_left:
8756 case Intrinsic::vector_splice_right:
8757 visitVectorSplice(I);
8758 return;
8759 case Intrinsic::callbr_landingpad:
8760 visitCallBrLandingPad(I);
8761 return;
8762 case Intrinsic::vector_interleave2:
8763 visitVectorInterleave(I, 2);
8764 return;
8765 case Intrinsic::vector_interleave3:
8766 visitVectorInterleave(I, 3);
8767 return;
8768 case Intrinsic::vector_interleave4:
8769 visitVectorInterleave(I, 4);
8770 return;
8771 case Intrinsic::vector_interleave5:
8772 visitVectorInterleave(I, 5);
8773 return;
8774 case Intrinsic::vector_interleave6:
8775 visitVectorInterleave(I, 6);
8776 return;
8777 case Intrinsic::vector_interleave7:
8778 visitVectorInterleave(I, 7);
8779 return;
8780 case Intrinsic::vector_interleave8:
8781 visitVectorInterleave(I, 8);
8782 return;
8783 case Intrinsic::vector_deinterleave2:
8784 visitVectorDeinterleave(I, 2);
8785 return;
8786 case Intrinsic::vector_deinterleave3:
8787 visitVectorDeinterleave(I, 3);
8788 return;
8789 case Intrinsic::vector_deinterleave4:
8790 visitVectorDeinterleave(I, 4);
8791 return;
8792 case Intrinsic::vector_deinterleave5:
8793 visitVectorDeinterleave(I, 5);
8794 return;
8795 case Intrinsic::vector_deinterleave6:
8796 visitVectorDeinterleave(I, 6);
8797 return;
8798 case Intrinsic::vector_deinterleave7:
8799 visitVectorDeinterleave(I, 7);
8800 return;
8801 case Intrinsic::vector_deinterleave8:
8802 visitVectorDeinterleave(I, 8);
8803 return;
8804 case Intrinsic::vector_repeat: {
8805 SDValue Vec = getValue(I.getOperand(0));
8806 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8807 setValue(&I, DAG.getNode(ISD::VECTOR_REPEAT, sdl, ResultVT, Vec));
8808 return;
8809 }
8810 case Intrinsic::experimental_vector_compress:
8811 setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8812 getValue(I.getArgOperand(0)).getValueType(),
8813 getValue(I.getArgOperand(0)),
8814 getValue(I.getArgOperand(1)),
8815 getValue(I.getArgOperand(2)), Flags));
8816 return;
8817 case Intrinsic::experimental_convergence_anchor:
8818 case Intrinsic::experimental_convergence_entry:
8819 case Intrinsic::experimental_convergence_loop:
8820 visitConvergenceControl(I, Intrinsic);
8821 return;
8822 case Intrinsic::experimental_vector_histogram_add: {
8823 visitVectorHistogram(I, Intrinsic);
8824 return;
8825 }
8826 case Intrinsic::experimental_vector_extract_last_active: {
8827 visitVectorExtractLastActive(I, Intrinsic);
8828 return;
8829 }
8830 case Intrinsic::loop_dependence_war_mask:
8831 setValue(&I,
8833 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8834 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8835 DAG.getConstant(0, sdl, MVT::i64)));
8836 return;
8837 case Intrinsic::loop_dependence_raw_mask:
8838 setValue(&I,
8840 EVT::getEVT(I.getType()), getValue(I.getOperand(0)),
8841 getValue(I.getOperand(1)), getValue(I.getOperand(2)),
8842 DAG.getConstant(0, sdl, MVT::i64)));
8843 return;
8844 case Intrinsic::masked_udiv:
8845 setValue(&I,
8846 DAG.getNode(ISD::MASKED_UDIV, sdl, EVT::getEVT(I.getType()),
8847 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8848 getValue(I.getOperand(2))));
8849 return;
8850 case Intrinsic::masked_sdiv:
8851 setValue(&I,
8852 DAG.getNode(ISD::MASKED_SDIV, sdl, EVT::getEVT(I.getType()),
8853 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8854 getValue(I.getOperand(2))));
8855 return;
8856 case Intrinsic::masked_urem:
8857 setValue(&I,
8858 DAG.getNode(ISD::MASKED_UREM, sdl, EVT::getEVT(I.getType()),
8859 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8860 getValue(I.getOperand(2))));
8861 return;
8862 case Intrinsic::masked_srem:
8863 setValue(&I,
8864 DAG.getNode(ISD::MASKED_SREM, sdl, EVT::getEVT(I.getType()),
8865 getValue(I.getOperand(0)), getValue(I.getOperand(1)),
8866 getValue(I.getOperand(2))));
8867 return;
8868 }
8869}
8870
8871void SelectionDAGBuilder::pushFPOpOutChain(SDValue Result,
8873 assert(Result.getNode()->getNumValues() == 2);
8874 SDValue OutChain = Result.getValue(1);
8875 assert(OutChain.getValueType() == MVT::Other);
8876
8877 // Instead of updating the root immediately, push the produced chain to the
8878 // appropriate list, deferring the update until the root is requested. In this
8879 // case, the nodes from the lists are chained using TokenFactor, indicating
8880 // that the operations are independent.
8881 //
8882 // In particular, the root is updated before any call that might access the
8883 // floating-point environment, except for constrained intrinsics.
8884 switch (EB) {
8887 PendingConstrainedFP.push_back(OutChain);
8888 break;
8890 PendingConstrainedFPStrict.push_back(OutChain);
8891 break;
8892 }
8893}
8894
8895void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8896 const ConstrainedFPIntrinsic &FPI) {
8897 SDLoc sdl = getCurSDLoc();
8898
8899 // We do not need to serialize constrained FP intrinsics against
8900 // each other or against (nonvolatile) loads, so they can be
8901 // chained like loads.
8903 SDValue Chain = getFPOperationRoot(EB);
8905 Opers.push_back(Chain);
8906 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8907 Opers.push_back(getValue(FPI.getArgOperand(I)));
8908
8909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8910 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8911 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8912
8913 SDNodeFlags Flags;
8915 Flags.setNoFPExcept(true);
8916
8917 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8918 Flags.copyFMF(*FPOp);
8919
8920 unsigned Opcode;
8921 switch (FPI.getIntrinsicID()) {
8922 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
8923#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8924 case Intrinsic::INTRINSIC: \
8925 Opcode = ISD::STRICT_##DAGN; \
8926 break;
8927#include "llvm/IR/ConstrainedOps.def"
8928 case Intrinsic::experimental_constrained_fmuladd: {
8929 Opcode = ISD::STRICT_FMA;
8930 // Break fmuladd into fmul and fadd.
8931 if (!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8932 Opers.pop_back();
8933 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8934 pushFPOpOutChain(Mul, EB);
8935 Opcode = ISD::STRICT_FADD;
8936 Opers.clear();
8937 Opers.push_back(Mul.getValue(1));
8938 Opers.push_back(Mul.getValue(0));
8939 Opers.push_back(getValue(FPI.getArgOperand(2)));
8940 }
8941 break;
8942 }
8943 }
8944
8945 // A few strict DAG nodes carry additional operands that are not
8946 // set up by the default code above.
8947 switch (Opcode) {
8948 default: break;
8950 Opers.push_back(
8951 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8952 break;
8953 case ISD::STRICT_FSETCC:
8954 case ISD::STRICT_FSETCCS: {
8955 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8956 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8957 if (DAG.isKnownNeverNaN(Opers[1]) && DAG.isKnownNeverNaN(Opers[2]))
8958 Condition = getFCmpCodeWithoutNaN(Condition);
8959 Opers.push_back(DAG.getCondCode(Condition));
8960 break;
8961 }
8962 }
8963
8964 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8965 pushFPOpOutChain(Result, EB);
8966
8967 SDValue FPResult = Result.getValue(0);
8968 setValue(&FPI, FPResult);
8969}
8970
8971static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8972 std::optional<unsigned> ResOPC;
8973 switch (VPIntrin.getIntrinsicID()) {
8974 case Intrinsic::vp_cttz_elts: {
8975 bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8976 ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_POISON : ISD::VP_CTTZ_ELTS;
8977 break;
8978 }
8979#define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
8980 case Intrinsic::VPID: \
8981 ResOPC = ISD::VPSD; \
8982 break;
8983#include "llvm/IR/VPIntrinsics.def"
8984 }
8985
8986 if (!ResOPC)
8988 "Inconsistency: no SDNode available for this VPIntrinsic!");
8989
8990 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8991 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8992 if (VPIntrin.getFastMathFlags().allowReassoc())
8993 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8994 : ISD::VP_REDUCE_FMUL;
8995 }
8996
8997 return *ResOPC;
8998}
8999
9000void SelectionDAGBuilder::visitVPLoad(
9001 const VPIntrinsic &VPIntrin, EVT VT,
9002 const SmallVectorImpl<SDValue> &OpValues) {
9003 SDLoc DL = getCurSDLoc();
9004 Value *PtrOperand = VPIntrin.getArgOperand(0);
9005 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9006 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9007 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9008 SDValue LD;
9009 // Do not serialize variable-length loads of constant memory with
9010 // anything.
9011 if (!Alignment)
9012 Alignment = DAG.getEVTAlign(VT);
9013 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9014 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9015 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9016 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9017 MachineMemOperand::Flags MMOFlags =
9018 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9019 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9020 MachinePointerInfo(PtrOperand), MMOFlags,
9022 MMOMetadata(AAInfo, Ranges));
9023 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9024 MMO, false /*IsExpanding */);
9025 if (AddToChain)
9026 PendingLoads.push_back(LD.getValue(1));
9027 setValue(&VPIntrin, LD);
9028}
9029
9030void SelectionDAGBuilder::visitVPLoadFF(
9031 const VPIntrinsic &VPIntrin, EVT VT, EVT EVLVT,
9032 const SmallVectorImpl<SDValue> &OpValues) {
9033 assert(OpValues.size() == 3 && "Unexpected number of operands");
9034 SDLoc DL = getCurSDLoc();
9035 Value *PtrOperand = VPIntrin.getArgOperand(0);
9036 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9037 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9038 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
9039 SDValue LD;
9040 // Do not serialize variable-length loads of constant memory with
9041 // anything.
9042 if (!Alignment)
9043 Alignment = DAG.getEVTAlign(VT);
9044 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9045 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9046 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9047 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9048 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
9050 MMOMetadata(AAInfo, Ranges));
9051 LD = DAG.getLoadFFVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
9052 MMO);
9053 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, EVLVT, LD.getValue(1));
9054 if (AddToChain)
9055 PendingLoads.push_back(LD.getValue(2));
9056 setValue(&VPIntrin, DAG.getMergeValues({LD.getValue(0), Trunc}, DL));
9057}
9058
9059void SelectionDAGBuilder::visitVPGather(
9060 const VPIntrinsic &VPIntrin, EVT VT,
9061 const SmallVectorImpl<SDValue> &OpValues) {
9062 SDLoc DL = getCurSDLoc();
9063 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9064 Value *PtrOperand = VPIntrin.getArgOperand(0);
9065 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9066 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9067 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9068 SDValue LD;
9069 if (!Alignment)
9070 Alignment = DAG.getEVTAlign(VT.getScalarType());
9071 unsigned AS =
9072 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9073 MachineMemOperand::Flags MMOFlags =
9074 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9075 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9076 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9077 *Alignment, MMOMetadata(AAInfo, Ranges));
9078 SDValue Base, Index, Scale;
9079 bool UniformBase =
9080 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9081 VT.getScalarStoreSize());
9082 if (!UniformBase) {
9083 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9084 Index = getValue(PtrOperand);
9085 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9086 }
9087 EVT IdxVT = Index.getValueType();
9088 EVT EltTy = IdxVT.getVectorElementType();
9089 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9090 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9091 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9092 }
9093 LD = DAG.getGatherVP(
9094 DAG.getVTList(VT, MVT::Other), VT, DL,
9095 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
9097 PendingLoads.push_back(LD.getValue(1));
9098 setValue(&VPIntrin, LD);
9099}
9100
9101void SelectionDAGBuilder::visitVPStore(
9102 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9103 SDLoc DL = getCurSDLoc();
9104 Value *PtrOperand = VPIntrin.getArgOperand(1);
9105 EVT VT = OpValues[0].getValueType();
9106 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9107 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9108 SDValue ST;
9109 if (!Alignment)
9110 Alignment = DAG.getEVTAlign(VT);
9111 SDValue Ptr = OpValues[1];
9112 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
9113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9114 MachineMemOperand::Flags MMOFlags =
9115 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9116 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9117 MachinePointerInfo(PtrOperand), MMOFlags,
9118 LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
9119 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
9120 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
9121 /* IsTruncating */ false, /*IsCompressing*/ false);
9122 DAG.setRoot(ST);
9123 setValue(&VPIntrin, ST);
9124}
9125
9126void SelectionDAGBuilder::visitVPScatter(
9127 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9128 SDLoc DL = getCurSDLoc();
9129 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9130 Value *PtrOperand = VPIntrin.getArgOperand(1);
9131 EVT VT = OpValues[0].getValueType();
9132 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9133 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9134 SDValue ST;
9135 if (!Alignment)
9136 Alignment = DAG.getEVTAlign(VT.getScalarType());
9137 unsigned AS =
9138 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
9139 MachineMemOperand::Flags MMOFlags =
9140 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9141 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9142 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9143 *Alignment, AAInfo);
9144 SDValue Base, Index, Scale;
9145 bool UniformBase =
9146 getUniformBase(PtrOperand, Base, Index, Scale, this, VPIntrin.getParent(),
9147 VT.getScalarStoreSize());
9148 if (!UniformBase) {
9149 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
9150 Index = getValue(PtrOperand);
9151 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
9152 }
9153 EVT IdxVT = Index.getValueType();
9154 EVT EltTy = IdxVT.getVectorElementType();
9155 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
9156 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
9157 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
9158 }
9159 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
9160 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
9161 OpValues[2], OpValues[3]},
9162 MMO, ISD::SIGNED_SCALED);
9163 DAG.setRoot(ST);
9164 setValue(&VPIntrin, ST);
9165}
9166
9167void SelectionDAGBuilder::visitVPStridedLoad(
9168 const VPIntrinsic &VPIntrin, EVT VT,
9169 const SmallVectorImpl<SDValue> &OpValues) {
9170 SDLoc DL = getCurSDLoc();
9171 Value *PtrOperand = VPIntrin.getArgOperand(0);
9172 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9173 if (!Alignment)
9174 Alignment = DAG.getEVTAlign(VT.getScalarType());
9175 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9176 const MDNode *Ranges = getRangeMetadata(VPIntrin);
9177 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
9178 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
9179 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
9180 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9182 MachineMemOperand::Flags MMOFlags =
9183 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9184 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9185 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9186 *Alignment, MMOMetadata(AAInfo, Ranges));
9187
9188 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
9189 OpValues[2], OpValues[3], MMO,
9190 false /*IsExpanding*/);
9191
9192 if (AddToChain)
9193 PendingLoads.push_back(LD.getValue(1));
9194 setValue(&VPIntrin, LD);
9195}
9196
9197void SelectionDAGBuilder::visitVPStridedStore(
9198 const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
9199 SDLoc DL = getCurSDLoc();
9200 Value *PtrOperand = VPIntrin.getArgOperand(1);
9201 EVT VT = OpValues[0].getValueType();
9202 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
9203 if (!Alignment)
9204 Alignment = DAG.getEVTAlign(VT.getScalarType());
9205 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
9206 unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
9207 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9208 MachineMemOperand::Flags MMOFlags =
9209 TLI.getVPIntrinsicMemOperandFlags(VPIntrin);
9210 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
9211 MachinePointerInfo(AS), MMOFlags, LocationSize::beforeOrAfterPointer(),
9212 *Alignment, AAInfo);
9213
9214 SDValue ST = DAG.getStridedStoreVP(
9215 getMemoryRoot(), DL, OpValues[0], OpValues[1],
9216 DAG.getPOISON(OpValues[1].getValueType()), OpValues[2], OpValues[3],
9217 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
9218 /*IsCompressing*/ false);
9219
9220 DAG.setRoot(ST);
9221 setValue(&VPIntrin, ST);
9222}
9223
9224void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
9225 const VPIntrinsic &VPIntrin) {
9226 SDLoc DL = getCurSDLoc();
9227 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
9228
9229 auto IID = VPIntrin.getIntrinsicID();
9230
9231 SmallVector<EVT, 4> ValueVTs;
9232 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9233 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
9234 SDVTList VTs = DAG.getVTList(ValueVTs);
9235
9236 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
9237
9238 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
9239 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
9240 "Unexpected target EVL type");
9241
9242 // Request operands.
9243 SmallVector<SDValue, 7> OpValues;
9244 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
9245 auto Op = getValue(VPIntrin.getArgOperand(I));
9246 if (I == EVLParamPos)
9247 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
9248 OpValues.push_back(Op);
9249 }
9250
9251 switch (Opcode) {
9252 default: {
9253 SDNodeFlags SDFlags;
9254 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
9255 SDFlags.copyFMF(*FPMO);
9256 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
9257 setValue(&VPIntrin, Result);
9258 break;
9259 }
9260 case ISD::VP_LOAD:
9261 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
9262 break;
9263 case ISD::VP_LOAD_FF:
9264 visitVPLoadFF(VPIntrin, ValueVTs[0], ValueVTs[1], OpValues);
9265 break;
9266 case ISD::VP_GATHER:
9267 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
9268 break;
9269 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
9270 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
9271 break;
9272 case ISD::VP_STORE:
9273 visitVPStore(VPIntrin, OpValues);
9274 break;
9275 case ISD::VP_SCATTER:
9276 visitVPScatter(VPIntrin, OpValues);
9277 break;
9278 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
9279 visitVPStridedStore(VPIntrin, OpValues);
9280 break;
9281 case ISD::VP_CTTZ_ELTS_ZERO_POISON:
9282 case ISD::VP_CTTZ_ELTS: {
9283 SDValue Result =
9284 DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
9285 setValue(&VPIntrin, Result);
9286 break;
9287 }
9288 }
9289}
9290
9292 const BasicBlock *EHPadBB,
9293 MCSymbol *&BeginLabel) {
9294 MachineFunction &MF = DAG.getMachineFunction();
9295
9296 // Skip emitting EH_LABEL on targets whose exception tables don't reference
9297 // them (32-bit x86 SEH, Wasm).
9299 FuncInfo.ExceptionModel)) {
9300 BeginLabel = nullptr;
9301 return Chain;
9302 }
9303
9304 // Insert a label before the invoke call to mark the try range. This can be
9305 // used to detect deletion of the invoke via the MachineModuleInfo.
9306 BeginLabel = MF.getContext().createTempSymbol();
9307
9308 // For SjLj, keep track of which landing pads go with which invokes
9309 // so as to maintain the ordering of pads in the LSDA.
9310 unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
9311 if (CallSiteIndex) {
9312 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
9313 LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
9314
9315 // Now that the call site is handled, stop tracking it.
9316 FuncInfo.setCurrentCallSite(0);
9317 }
9318
9319 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
9320}
9321
9322SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
9323 const BasicBlock *EHPadBB,
9324 MCSymbol *BeginLabel) {
9325 // No labels were emitted.
9326 if (!BeginLabel)
9327 return Chain;
9328
9330
9331 // Insert a label at the end of the invoke call to mark the try range. This
9332 // can be used to detect deletion of the invoke via the MachineModuleInfo.
9333 MCSymbol *EndLabel = MF.getContext().createTempSymbol();
9334 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
9335
9336 // Inform MachineModuleInfo of range.
9338 // There is a platform (e.g. wasm) that uses funclet style IR but does not
9339 // actually use outlined funclets and their LSDA info style.
9340 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
9341 assert(II && "II should've been set");
9342 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
9343 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
9344 } else if (!isScopedEHPersonality(Pers)) {
9345 assert(EHPadBB);
9346 MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
9347 }
9348
9349 return Chain;
9350}
9351
9352std::pair<SDValue, SDValue>
9354 const BasicBlock *EHPadBB) {
9355 MCSymbol *BeginLabel = nullptr;
9356
9357 if (EHPadBB) {
9358 // Both PendingLoads and PendingExports must be flushed here;
9359 // this call might not return.
9360 (void)getRoot();
9361 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
9362 CLI.setChain(getRoot());
9363 }
9364
9365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9366 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
9367
9368 assert((CLI.IsTailCall || Result.second.getNode()) &&
9369 "Non-null chain expected with non-tail call!");
9370 assert((Result.second.getNode() || !Result.first.getNode()) &&
9371 "Null value expected with tail call!");
9372
9373 if (!Result.second.getNode()) {
9374 // As a special case, a null chain means that a tail call has been emitted
9375 // and the DAG root is already updated.
9376 HasTailCall = true;
9377
9378 // Since there's no actual continuation from this block, nothing can be
9379 // relying on us setting vregs for them.
9380 PendingExports.clear();
9381 } else {
9382 DAG.setRoot(Result.second);
9383 }
9384
9385 if (EHPadBB) {
9386 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
9387 BeginLabel));
9388 Result.second = getRoot();
9389 }
9390
9391 return Result;
9392}
9393
9395 bool isMustTailCall = CB.isMustTailCall();
9396
9397 // Avoid emitting tail calls in functions with the disable-tail-calls
9398 // attribute.
9399 const Function *Caller = CB.getParent()->getParent();
9400 if (!isMustTailCall &&
9401 Caller->getFnAttribute("disable-tail-calls").getValueAsBool())
9402 return false;
9403
9404 // We can't tail call inside a function with a swifterror argument. Lowering
9405 // does not support this yet. It would have to move into the swifterror
9406 // register before the call.
9407 if (DAG.hasSwiftErrorArg())
9408 return false;
9409
9410 // Check if target-independent constraints permit a tail call here.
9411 // Target-dependent constraints are checked within TLI->LowerCallTo.
9412 return isInTailCallPosition(CB, DAG.getTarget());
9413}
9414
9416 bool isTailCall, bool isMustTailCall,
9417 const BasicBlock *EHPadBB,
9418 const TargetLowering::PtrAuthInfo *PAI) {
9419 auto &DL = DAG.getDataLayout();
9420 FunctionType *FTy = CB.getFunctionType();
9421 Type *RetTy = CB.getType();
9422
9424 Args.reserve(CB.arg_size());
9425
9426 const Value *SwiftErrorVal = nullptr;
9427 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9428
9429 if (isTailCall)
9430 isTailCall = canTailCall(CB);
9431
9432 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
9433 const Value *V = *I;
9434
9435 // Skip empty types
9436 if (V->getType()->isEmptyTy())
9437 continue;
9438
9439 SDValue ArgNode = getValue(V);
9440 TargetLowering::ArgListEntry Entry(ArgNode, V->getType());
9441 Entry.setAttributes(&CB, I - CB.arg_begin());
9442
9443 // Use swifterror virtual register as input to the call.
9444 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
9445 SwiftErrorVal = V;
9446 // We find the virtual register for the actual swifterror argument.
9447 // Instead of using the Value, we use the virtual register instead.
9448 Entry.Node =
9449 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
9450 EVT(TLI.getPointerTy(DL)));
9451 }
9452
9453 Args.push_back(Entry);
9454
9455 // If we have an explicit sret argument that is an Instruction, (i.e., it
9456 // might point to function-local memory), we can't meaningfully tail-call.
9457 if (Entry.IsSRet && isa<Instruction>(V))
9458 isTailCall = false;
9459 }
9460
9461 // If call site has a cfguardtarget operand bundle, create and add an
9462 // additional ArgListEntry.
9463 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
9464 Value *V = Bundle->Inputs[0];
9466 Entry.IsCFGuardTarget = true;
9467 Args.push_back(Entry);
9468 }
9469
9470 // Disable tail calls if there is an swifterror argument. Targets have not
9471 // been updated to support tail calls.
9472 if (TLI.supportSwiftError() && SwiftErrorVal)
9473 isTailCall = false;
9474
9475 ConstantInt *CFIType = nullptr;
9476 if (CB.isIndirectCall()) {
9477 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
9478 if (!TLI.supportKCFIBundles())
9480 "Target doesn't support calls with kcfi operand bundles.");
9481 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
9482 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
9483 }
9484 }
9485
9486 SDValue ConvControlToken;
9487 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
9488 auto *Token = Bundle->Inputs[0].get();
9489 ConvControlToken = getValue(Token);
9490 }
9491
9492 GlobalValue *DeactivationSymbol = nullptr;
9494 DeactivationSymbol = cast<GlobalValue>(Bundle->Inputs[0].get());
9495 }
9496
9499 .setChain(getRoot())
9500 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
9501 .setTailCall(isTailCall)
9505 .setCFIType(CFIType)
9506 .setConvergenceControlToken(ConvControlToken)
9507 .setDeactivationSymbol(DeactivationSymbol);
9508
9509 // Set the pointer authentication info if we have it.
9510 if (PAI) {
9511 if (!TLI.supportPtrAuthBundles())
9513 "This target doesn't support calls with ptrauth operand bundles.");
9514 CLI.setPtrAuth(*PAI);
9515 }
9516
9517 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9518
9519 if (Result.first.getNode()) {
9520 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
9521 Result.first = lowerNoFPClassToAssertNoFPClass(DAG, CB, Result.first);
9522 setValue(&CB, Result.first);
9523 }
9524
9525 // The last element of CLI.InVals has the SDValue for swifterror return.
9526 // Here we copy it to a virtual register and update SwiftErrorMap for
9527 // book-keeping.
9528 if (SwiftErrorVal && TLI.supportSwiftError()) {
9529 // Get the last element of InVals.
9530 SDValue Src = CLI.InVals.back();
9531 Register VReg =
9532 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
9533 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
9534 DAG.setRoot(CopyNode);
9535 }
9536}
9537
9538static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
9539 SelectionDAGBuilder &Builder) {
9540 // Check to see if this load can be trivially constant folded, e.g. if the
9541 // input is from a string literal.
9542 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9543 // Cast pointer to the type we really want to load.
9544 Type *LoadTy =
9545 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9546 if (LoadVT.isVector())
9547 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9548 if (const Constant *LoadCst =
9549 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9550 LoadTy, Builder.DAG.getDataLayout()))
9551 return Builder.getValue(LoadCst);
9552 }
9553
9554 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
9555 // still constant memory, the input chain can be the entry node.
9556 SDValue Root;
9557 bool ConstantMemory = false;
9558
9559 // Do not serialize (non-volatile) loads of constant memory with anything.
9560 if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9561 Root = Builder.DAG.getEntryNode();
9562 ConstantMemory = true;
9563 } else {
9564 // Do not serialize non-volatile loads against each other.
9565 Root = Builder.DAG.getRoot();
9566 }
9567
9568 SDValue Ptr = Builder.getValue(PtrVal);
9569 SDValue LoadVal =
9570 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9571 MachinePointerInfo(PtrVal), Align(1));
9572
9573 if (!ConstantMemory)
9574 Builder.PendingLoads.push_back(LoadVal.getValue(1));
9575 return LoadVal;
9576}
9577
9578/// Record the value for an instruction that produces an integer result,
9579/// converting the type where necessary.
9580void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9581 SDValue Value,
9582 bool IsSigned) {
9583 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9584 I.getType(), true);
9585 Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9586 setValue(&I, Value);
9587}
9588
9589/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9590/// true and lower it. Otherwise return false, and it will be lowered like a
9591/// normal call.
9592/// The caller already checked that \p I calls the appropriate LibFunc with a
9593/// correct prototype.
9594bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9595 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9596 const Value *Size = I.getArgOperand(2);
9597 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9598 if (CSize && CSize->getZExtValue() == 0) {
9599 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9600 I.getType(), true);
9601 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9602 return true;
9603 }
9604
9605 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9606 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9607 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9608 getValue(Size), &I);
9609 if (Res.first.getNode()) {
9610 processIntegerCallValue(I, Res.first, true);
9611 PendingLoads.push_back(Res.second);
9612 return true;
9613 }
9614
9615 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
9616 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
9617 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9618 return false;
9619
9620 // If the target has a fast compare for the given size, it will return a
9621 // preferred load type for that size. Require that the load VT is legal and
9622 // that the target supports unaligned loads of that type. Otherwise, return
9623 // INVALID.
9624 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9625 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9626 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9627 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9628 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9629 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9630 // TODO: Check alignment of src and dest ptrs.
9631 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9632 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9633 if (!TLI.isTypeLegal(LVT) ||
9634 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9635 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9637 }
9638
9639 return LVT;
9640 };
9641
9642 // This turns into unaligned loads. We only do this if the target natively
9643 // supports the MVT we'll be loading or if it is small enough (<= 4) that
9644 // we'll only produce a small number of byte loads.
9645 MVT LoadVT;
9646 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9647 switch (NumBitsToCompare) {
9648 default:
9649 return false;
9650 case 16:
9651 LoadVT = MVT::i16;
9652 break;
9653 case 32:
9654 LoadVT = MVT::i32;
9655 break;
9656 case 64:
9657 case 128:
9658 case 256:
9659 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9660 break;
9661 }
9662
9663 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9664 return false;
9665
9666 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9667 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9668
9669 // Bitcast to a wide integer type if the loads are vectors.
9670 if (LoadVT.isVector()) {
9671 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9672 LoadL = DAG.getBitcast(CmpVT, LoadL);
9673 LoadR = DAG.getBitcast(CmpVT, LoadR);
9674 }
9675
9676 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9677 processIntegerCallValue(I, Cmp, false);
9678 return true;
9679}
9680
9681/// See if we can lower a memchr call into an optimized form. If so, return
9682/// true and lower it. Otherwise return false, and it will be lowered like a
9683/// normal call.
9684/// The caller already checked that \p I calls the appropriate LibFunc with a
9685/// correct prototype.
9686bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9687 const Value *Src = I.getArgOperand(0);
9688 const Value *Char = I.getArgOperand(1);
9689 const Value *Length = I.getArgOperand(2);
9690
9691 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9692 std::pair<SDValue, SDValue> Res =
9693 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9694 getValue(Src), getValue(Char), getValue(Length),
9695 MachinePointerInfo(Src));
9696 if (Res.first.getNode()) {
9697 setValue(&I, Res.first);
9698 PendingLoads.push_back(Res.second);
9699 return true;
9700 }
9701
9702 return false;
9703}
9704
9705/// See if we can lower a memccpy call into an optimized form. If so, return
9706/// true and lower it, otherwise return false and it will be lowered like a
9707/// normal call.
9708/// The caller already checked that \p I calls the appropriate LibFunc with a
9709/// correct prototype.
9710bool SelectionDAGBuilder::visitMemCCpyCall(const CallInst &I) {
9711 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9712 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemccpy(
9713 DAG, getCurSDLoc(), DAG.getRoot(), getValue(I.getArgOperand(0)),
9714 getValue(I.getArgOperand(1)), getValue(I.getArgOperand(2)),
9715 getValue(I.getArgOperand(3)), &I);
9716
9717 if (Res.first) {
9718 processIntegerCallValue(I, Res.first, true);
9719 PendingLoads.push_back(Res.second);
9720 return true;
9721 }
9722 return false;
9723}
9724
9725/// See if we can lower a mempcpy call into an optimized form. If so, return
9726/// true and lower it. Otherwise return false, and it will be lowered like a
9727/// normal call.
9728/// The caller already checked that \p I calls the appropriate LibFunc with a
9729/// correct prototype.
9730bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9731 SDValue Dst = getValue(I.getArgOperand(0));
9732 SDValue Src = getValue(I.getArgOperand(1));
9733 SDValue Size = getValue(I.getArgOperand(2));
9734
9735 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9736 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9737
9738 SDLoc sdl = getCurSDLoc();
9739
9740 // In the mempcpy context we need to pass in a false value for isTailCall
9741 // because the return pointer needs to be adjusted by the size of
9742 // the copied memory.
9743 SDValue Root = getMemoryRoot();
9744 SDValue MC = DAG.getMemcpy(
9745 Root, sdl, Dst, Src, Size, DstAlign, SrcAlign, false, false,
9746 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9747 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9748 assert(MC.getNode() != nullptr &&
9749 "** memcpy should not be lowered as TailCall in mempcpy context **");
9750 DAG.setRoot(MC);
9751
9752 // Check if Size needs to be truncated or extended.
9753 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9754
9755 // Adjust return pointer to point just past the last dst byte.
9756 SDValue DstPlusSize = DAG.getMemBasePlusOffset(Dst, Size, sdl);
9757 setValue(&I, DstPlusSize);
9758 return true;
9759}
9760
9761/// See if we can lower a strcpy call into an optimized form. If so, return
9762/// true and lower it, otherwise return false and it will be lowered like a
9763/// normal call.
9764/// The caller already checked that \p I calls the appropriate LibFunc with a
9765/// correct prototype.
9766bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9767 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9768
9769 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9770 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcpy(
9771 DAG, getCurSDLoc(), getRoot(), getValue(Arg0), getValue(Arg1),
9772 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), isStpcpy, &I);
9773 if (Res.first.getNode()) {
9774 setValue(&I, Res.first);
9775 DAG.setRoot(Res.second);
9776 return true;
9777 }
9778
9779 return false;
9780}
9781
9782/// See if we can lower a strcmp call into an optimized form. If so, return
9783/// true and lower it, otherwise return false and it will be lowered like a
9784/// normal call.
9785/// The caller already checked that \p I calls the appropriate LibFunc with a
9786/// correct prototype.
9787bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9788 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9789
9790 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9791 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrcmp(
9792 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1),
9793 MachinePointerInfo(Arg0), MachinePointerInfo(Arg1), &I);
9794 if (Res.first.getNode()) {
9795 processIntegerCallValue(I, Res.first, true);
9796 PendingLoads.push_back(Res.second);
9797 return true;
9798 }
9799
9800 return false;
9801}
9802
9803/// See if we can lower a strlen call into an optimized form. If so, return
9804/// true and lower it, otherwise return false and it will be lowered like a
9805/// normal call.
9806/// The caller already checked that \p I calls the appropriate LibFunc with a
9807/// correct prototype.
9808bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9809 const Value *Arg0 = I.getArgOperand(0);
9810
9811 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9812 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrlen(
9813 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), &I);
9814 if (Res.first.getNode()) {
9815 processIntegerCallValue(I, Res.first, false);
9816 PendingLoads.push_back(Res.second);
9817 return true;
9818 }
9819
9820 return false;
9821}
9822
9823/// See if we can lower a strnlen call into an optimized form. If so, return
9824/// true and lower it, otherwise return false and it will be lowered like a
9825/// normal call.
9826/// The caller already checked that \p I calls the appropriate LibFunc with a
9827/// correct prototype.
9828bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9829 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9830
9831 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9832 std::pair<SDValue, SDValue> Res =
9833 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9834 getValue(Arg0), getValue(Arg1),
9835 MachinePointerInfo(Arg0));
9836 if (Res.first.getNode()) {
9837 processIntegerCallValue(I, Res.first, false);
9838 PendingLoads.push_back(Res.second);
9839 return true;
9840 }
9841
9842 return false;
9843}
9844
9845/// See if we can lower a Strstr call into an optimized form. If so, return
9846/// true and lower it, otherwise return false and it will be lowered like a
9847/// normal call.
9848/// The caller already checked that \p I calls the appropriate LibFunc with a
9849/// correct prototype.
9850bool SelectionDAGBuilder::visitStrstrCall(const CallInst &I) {
9851 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9852 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9853 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForStrstr(
9854 DAG, getCurSDLoc(), DAG.getRoot(), getValue(Arg0), getValue(Arg1), &I);
9855 if (Res.first) {
9856 processIntegerCallValue(I, Res.first, false);
9857 PendingLoads.push_back(Res.second);
9858 return true;
9859 }
9860 return false;
9861}
9862
9863/// See if we can lower a unary floating-point operation into an SDNode with
9864/// the specified Opcode. If so, return true and lower it, otherwise return
9865/// false and it will be lowered like a normal call.
9866/// The caller already checked that \p I calls the appropriate LibFunc with a
9867/// correct prototype.
9868bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9869 unsigned Opcode) {
9870 // We already checked this call's prototype; verify it doesn't modify errno.
9871 // Do not perform optimizations for call sites that require strict
9872 // floating-point semantics.
9873 if (!I.onlyReadsMemory() || I.isStrictFP())
9874 return false;
9875
9876 SDNodeFlags Flags;
9877 Flags.copyFMF(cast<FPMathOperator>(I));
9878
9879 SDValue Tmp = getValue(I.getArgOperand(0));
9880 setValue(&I,
9881 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9882 return true;
9883}
9884
9885/// See if we can lower a binary floating-point operation into an SDNode with
9886/// the specified Opcode. If so, return true and lower it. Otherwise return
9887/// false, and it will be lowered like a normal call.
9888/// The caller already checked that \p I calls the appropriate LibFunc with a
9889/// correct prototype.
9890bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9891 unsigned Opcode) {
9892 // We already checked this call's prototype; verify it doesn't modify errno.
9893 // Do not perform optimizations for call sites that require strict
9894 // floating-point semantics.
9895 if (!I.onlyReadsMemory() || I.isStrictFP())
9896 return false;
9897
9898 SDNodeFlags Flags;
9899 Flags.copyFMF(cast<FPMathOperator>(I));
9900
9901 SDValue Tmp0 = getValue(I.getArgOperand(0));
9902 SDValue Tmp1 = getValue(I.getArgOperand(1));
9903 EVT VT = Tmp0.getValueType();
9904 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9905 return true;
9906}
9907
9908void SelectionDAGBuilder::visitCall(const CallInst &I) {
9909 // Handle inline assembly differently.
9910 if (I.isInlineAsm()) {
9911 visitInlineAsm(I);
9912 return;
9913 }
9914
9916
9917 if (Function *F = I.getCalledFunction()) {
9918 if (F->isDeclaration()) {
9919 // Is this an LLVM intrinsic?
9920 if (unsigned IID = F->getIntrinsicID()) {
9921 visitIntrinsicCall(I, IID);
9922 return;
9923 }
9924 }
9925
9926 // Check for well-known libc/libm calls. If the function is internal, it
9927 // can't be a library call. Don't do the check if marked as nobuiltin for
9928 // some reason.
9929 // This code should not handle libcalls that are already canonicalized to
9930 // intrinsics by the middle-end.
9931 LibFunc Func = !I.isNoBuiltin() && !F->hasLocalLinkage() && F->hasName()
9932 ? LibInfo->getLibFunc(*F)
9933 : NotLibFunc;
9934 if (LibInfo->hasOptimizedCodeGen(Func)) {
9935 switch (Func) {
9936 default: break;
9937 case LibFunc_bcmp:
9938 if (visitMemCmpBCmpCall(I))
9939 return;
9940 break;
9941 case LibFunc_copysign:
9942 case LibFunc_copysignf:
9943 case LibFunc_copysignl:
9944 // We already checked this call's prototype; verify it doesn't modify
9945 // errno.
9946 if (I.onlyReadsMemory()) {
9947 SDValue LHS = getValue(I.getArgOperand(0));
9948 SDValue RHS = getValue(I.getArgOperand(1));
9950 LHS.getValueType(), LHS, RHS));
9951 return;
9952 }
9953 break;
9954 case LibFunc_sin:
9955 case LibFunc_sinf:
9956 case LibFunc_sinl:
9957 if (visitUnaryFloatCall(I, ISD::FSIN))
9958 return;
9959 break;
9960 case LibFunc_cos:
9961 case LibFunc_cosf:
9962 case LibFunc_cosl:
9963 if (visitUnaryFloatCall(I, ISD::FCOS))
9964 return;
9965 break;
9966 case LibFunc_tan:
9967 case LibFunc_tanf:
9968 case LibFunc_tanl:
9969 if (visitUnaryFloatCall(I, ISD::FTAN))
9970 return;
9971 break;
9972 case LibFunc_asin:
9973 case LibFunc_asinf:
9974 case LibFunc_asinl:
9975 if (visitUnaryFloatCall(I, ISD::FASIN))
9976 return;
9977 break;
9978 case LibFunc_acos:
9979 case LibFunc_acosf:
9980 case LibFunc_acosl:
9981 if (visitUnaryFloatCall(I, ISD::FACOS))
9982 return;
9983 break;
9984 case LibFunc_atan:
9985 case LibFunc_atanf:
9986 case LibFunc_atanl:
9987 if (visitUnaryFloatCall(I, ISD::FATAN))
9988 return;
9989 break;
9990 case LibFunc_atan2:
9991 case LibFunc_atan2f:
9992 case LibFunc_atan2l:
9993 if (visitBinaryFloatCall(I, ISD::FATAN2))
9994 return;
9995 break;
9996 case LibFunc_sinh:
9997 case LibFunc_sinhf:
9998 case LibFunc_sinhl:
9999 if (visitUnaryFloatCall(I, ISD::FSINH))
10000 return;
10001 break;
10002 case LibFunc_cosh:
10003 case LibFunc_coshf:
10004 case LibFunc_coshl:
10005 if (visitUnaryFloatCall(I, ISD::FCOSH))
10006 return;
10007 break;
10008 case LibFunc_tanh:
10009 case LibFunc_tanhf:
10010 case LibFunc_tanhl:
10011 if (visitUnaryFloatCall(I, ISD::FTANH))
10012 return;
10013 break;
10014 case LibFunc_sqrt:
10015 case LibFunc_sqrtf:
10016 case LibFunc_sqrtl:
10017 case LibFunc_sqrt_finite:
10018 case LibFunc_sqrtf_finite:
10019 case LibFunc_sqrtl_finite:
10020 if (visitUnaryFloatCall(I, ISD::FSQRT))
10021 return;
10022 break;
10023 case LibFunc_log2:
10024 case LibFunc_log2f:
10025 case LibFunc_log2l:
10026 if (visitUnaryFloatCall(I, ISD::FLOG2))
10027 return;
10028 break;
10029 case LibFunc_exp2:
10030 case LibFunc_exp2f:
10031 case LibFunc_exp2l:
10032 if (visitUnaryFloatCall(I, ISD::FEXP2))
10033 return;
10034 break;
10035 case LibFunc_exp10:
10036 case LibFunc_exp10f:
10037 case LibFunc_exp10l:
10038 if (visitUnaryFloatCall(I, ISD::FEXP10))
10039 return;
10040 break;
10041 case LibFunc_ldexp:
10042 case LibFunc_ldexpf:
10043 case LibFunc_ldexpl:
10044 if (visitBinaryFloatCall(I, ISD::FLDEXP))
10045 return;
10046 break;
10047 case LibFunc_strstr:
10048 if (visitStrstrCall(I))
10049 return;
10050 break;
10051 case LibFunc_memcmp:
10052 if (visitMemCmpBCmpCall(I))
10053 return;
10054 break;
10055 case LibFunc_memccpy:
10056 if (visitMemCCpyCall(I))
10057 return;
10058 break;
10059 case LibFunc_mempcpy:
10060 if (visitMemPCpyCall(I))
10061 return;
10062 break;
10063 case LibFunc_memchr:
10064 if (visitMemChrCall(I))
10065 return;
10066 break;
10067 case LibFunc_strcpy:
10068 if (visitStrCpyCall(I, false))
10069 return;
10070 break;
10071 case LibFunc_stpcpy:
10072 if (visitStrCpyCall(I, true))
10073 return;
10074 break;
10075 case LibFunc_strcmp:
10076 if (visitStrCmpCall(I))
10077 return;
10078 break;
10079 case LibFunc_strlen:
10080 if (visitStrLenCall(I))
10081 return;
10082 break;
10083 case LibFunc_strnlen:
10084 if (visitStrNLenCall(I))
10085 return;
10086 break;
10087 }
10088 }
10089 }
10090
10091 if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
10092 LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
10093 return;
10094 }
10095
10096 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
10097 // have to do anything here to lower funclet bundles.
10098 // CFGuardTarget bundles are lowered in LowerCallTo.
10100 I, "calls",
10105
10106 SDValue Callee = getValue(I.getCalledOperand());
10107
10108 if (I.hasDeoptState())
10109 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
10110 else
10111 // Check if we can potentially perform a tail call. More detailed checking
10112 // is be done within LowerCallTo, after more information about the call is
10113 // known.
10114 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
10115}
10116
10118 const CallBase &CB, const BasicBlock *EHPadBB) {
10119 auto PAB = CB.getOperandBundle("ptrauth");
10120 const Value *CalleeV = CB.getCalledOperand();
10121
10122 // Gather the call ptrauth data from the operand bundle:
10123 // [ i32 <key>, i64 <discriminator> ]
10124 const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
10125 const Value *Discriminator = PAB->Inputs[1];
10126
10127 assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
10128 assert(Discriminator->getType()->isIntegerTy(64) &&
10129 "Invalid ptrauth discriminator");
10130
10131 // Look through ptrauth constants to find the raw callee.
10132 // Do a direct unauthenticated call if we found it and everything matches.
10133 if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
10134 if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
10135 DAG.getDataLayout()))
10136 return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
10137 CB.isMustTailCall(), EHPadBB);
10138
10139 // Functions should never be ptrauth-called directly.
10140 assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
10141
10142 // Otherwise, do an authenticated indirect call.
10143 TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
10144 getValue(Discriminator)};
10145
10146 LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
10147 EHPadBB, &PAI);
10148}
10149
10150namespace {
10151
10152/// AsmOperandInfo - This contains information for each constraint that we are
10153/// lowering.
10154class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
10155public:
10156 /// CallOperand - If this is the result output operand or a clobber
10157 /// this is null, otherwise it is the incoming operand to the CallInst.
10158 /// This gets modified as the asm is processed.
10159 SDValue CallOperand;
10160
10161 /// AssignedRegs - If this is a register or register class operand, this
10162 /// contains the set of register corresponding to the operand.
10163 RegsForValue AssignedRegs;
10164
10165 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
10166 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
10167 }
10168
10169 /// Whether or not this operand accesses memory
10170 bool hasMemory(const TargetLowering &TLI) const {
10171 // Indirect operand accesses access memory.
10172 if (isIndirect)
10173 return true;
10174
10175 for (const auto &Code : Codes)
10177 return true;
10178
10179 return false;
10180 }
10181};
10182
10183
10184} // end anonymous namespace
10185
10186/// Make sure that the output operand \p OpInfo and its corresponding input
10187/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
10188/// out).
10189static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
10190 SDISelAsmOperandInfo &MatchingOpInfo,
10191 SelectionDAG &DAG) {
10192 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
10193 return;
10194
10196 const auto &TLI = DAG.getTargetLoweringInfo();
10197
10198 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
10199 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
10200 OpInfo.ConstraintVT);
10201 std::pair<unsigned, const TargetRegisterClass *> InputRC =
10202 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
10203 MatchingOpInfo.ConstraintVT);
10204 const bool OutOpIsIntOrFP =
10205 OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
10206 const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
10207 MatchingOpInfo.ConstraintVT.isFloatingPoint();
10208 if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
10209 // FIXME: error out in a more elegant fashion
10210 report_fatal_error("Unsupported asm: input constraint"
10211 " with a matching output constraint of"
10212 " incompatible type!");
10213 }
10214 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
10215}
10216
10217/// Get a direct memory input to behave well as an indirect operand.
10218/// This may introduce stores, hence the need for a \p Chain.
10219/// \return The (possibly updated) chain.
10220static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
10221 SDISelAsmOperandInfo &OpInfo,
10222 SelectionDAG &DAG) {
10223 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10224
10225 // If we don't have an indirect input, put it in the constpool if we can,
10226 // otherwise spill it to a stack slot.
10227 // TODO: This isn't quite right. We need to handle these according to
10228 // the addressing mode that the constraint wants. Also, this may take
10229 // an additional register for the computation and we don't want that
10230 // either.
10231
10232 // If the operand is a float, integer, or vector constant, spill to a
10233 // constant pool entry to get its address.
10234 const Value *OpVal = OpInfo.CallOperandVal;
10235 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
10237 OpInfo.CallOperand = DAG.getConstantPool(
10238 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
10239 return Chain;
10240 }
10241
10242 // Otherwise, create a stack slot and emit a store to it before the asm.
10243 Type *Ty = OpVal->getType();
10244 auto &DL = DAG.getDataLayout();
10245 TypeSize TySize = DL.getTypeAllocSize(Ty);
10248 int StackID = 0;
10249 if (TySize.isScalable())
10250 StackID = TFI->getStackIDForScalableVectors();
10251 int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
10252 DL.getPrefTypeAlign(Ty), false,
10253 nullptr, StackID);
10254 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
10255 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
10257 TLI.getMemValueType(DL, Ty));
10258 OpInfo.CallOperand = StackSlot;
10259
10260 return Chain;
10261}
10262
10263/// GetRegistersForValue - Assign registers (virtual or physical) for the
10264/// specified operand. We prefer to assign virtual registers, to allow the
10265/// register allocator to handle the assignment process. However, if the asm
10266/// uses features that we can't model on machineinstrs, we have SDISel do the
10267/// allocation. This produces generally horrible, but correct, code.
10268///
10269/// OpInfo describes the operand
10270/// RefOpInfo describes the matching operand if any, the operand otherwise
10271static std::optional<unsigned>
10273 SDISelAsmOperandInfo &OpInfo,
10274 SDISelAsmOperandInfo &RefOpInfo) {
10275 LLVMContext &Context = *DAG.getContext();
10276 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10277
10281
10282 // No work to do for memory/address operands.
10283 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
10284 OpInfo.ConstraintType == TargetLowering::C_Address)
10285 return std::nullopt;
10286
10287 // If this is a constraint for a single physreg, or a constraint for a
10288 // register class, find it.
10289 unsigned AssignedReg;
10290 const TargetRegisterClass *RC;
10291 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
10292 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
10293 // RC is unset only on failure. Return immediately.
10294 if (!RC)
10295 return std::nullopt;
10296
10297 // Get the actual register value type. This is important, because the user
10298 // may have asked for (e.g.) the AX register in i32 type. We need to
10299 // remember that AX is actually i16 to get the right extension.
10300 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
10301
10302 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
10303 // If this is an FP operand in an integer register (or visa versa), or more
10304 // generally if the operand value disagrees with the register class we plan
10305 // to stick it in, fix the operand type.
10306 //
10307 // If this is an input value, the bitcast to the new type is done now.
10308 // Bitcast for output value is done at the end of visitInlineAsm().
10309 if ((OpInfo.Type == InlineAsm::isOutput ||
10310 OpInfo.Type == InlineAsm::isInput) &&
10311 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
10312 // Try to convert to the first EVT that the reg class contains. If the
10313 // types are identical size, use a bitcast to convert (e.g. two differing
10314 // vector types). Note: output bitcast is done at the end of
10315 // visitInlineAsm().
10316 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
10317 // Exclude indirect inputs while they are unsupported because the code
10318 // to perform the load is missing and thus OpInfo.CallOperand still
10319 // refers to the input address rather than the pointed-to value.
10320 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
10321 OpInfo.CallOperand =
10322 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
10323 OpInfo.ConstraintVT = RegVT;
10324 // If the operand is an FP value and we want it in integer registers,
10325 // use the corresponding integer type. This turns an f64 value into
10326 // i64, which can be passed with two i32 values on a 32-bit machine.
10327 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
10328 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
10329 // No integer type of that size to bitcast to (e.g. f80).
10330 if (!VT.isValid())
10331 return std::nullopt;
10332 if (OpInfo.Type == InlineAsm::isInput)
10333 OpInfo.CallOperand =
10334 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
10335 OpInfo.ConstraintVT = VT;
10336 }
10337 }
10338 }
10339
10340 // No need to allocate a matching input constraint since the constraint it's
10341 // matching to has already been allocated.
10342 if (OpInfo.isMatchingInputConstraint())
10343 return std::nullopt;
10344
10345 EVT ValueVT = OpInfo.ConstraintVT;
10346 if (OpInfo.ConstraintVT == MVT::Other)
10347 ValueVT = RegVT;
10348
10349 // Initialize NumRegs.
10350 unsigned NumRegs = 1;
10351 if (OpInfo.ConstraintVT != MVT::Other)
10352 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
10353
10354 // If this is a constraint for a specific physical register, like {r17},
10355 // assign it now.
10356
10357 // If this associated to a specific register, initialize iterator to correct
10358 // place. If virtual, make sure we have enough registers
10359
10360 // Initialize iterator if necessary
10363
10364 // Do not check for single registers.
10365 if (AssignedReg) {
10366 I = std::find(I, RC->end(), AssignedReg);
10367 if (I == RC->end()) {
10368 // RC does not contain the selected register, which indicates a
10369 // mismatch between the register and the required type/bitwidth.
10370 return {AssignedReg};
10371 }
10372 }
10373
10374 for (; NumRegs; --NumRegs, ++I) {
10375 assert(I != RC->end() && "Ran out of registers to allocate!");
10376 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
10377 Regs.push_back(R);
10378 }
10379
10380 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
10381 return std::nullopt;
10382}
10383
10384static unsigned
10386 const std::vector<SDValue> &AsmNodeOperands) {
10387 // Scan until we find the definition we already emitted of this operand.
10388 unsigned CurOp = InlineAsm::Op_FirstOperand;
10389 for (; OperandNo; --OperandNo) {
10390 // Advance to the next operand.
10391 unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
10392 const InlineAsm::Flag F(OpFlag);
10393 assert(
10394 (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
10395 "Skipped past definitions?");
10396 CurOp += F.getNumOperandRegisters() + 1;
10397 }
10398 return CurOp;
10399}
10400
10401namespace {
10402
10403class ExtraFlags {
10404 unsigned Flags = 0;
10405
10406public:
10407 explicit ExtraFlags(const CallBase &Call) {
10408 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
10409 if (IA->hasSideEffects())
10411 if (IA->isAlignStack())
10413 if (IA->canThrow())
10415 if (Call.isConvergent())
10417 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
10418 }
10419
10420 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
10421 // Ideally, we would only check against memory constraints. However, the
10422 // meaning of an Other constraint can be target-specific and we can't easily
10423 // reason about it. Therefore, be conservative and set MayLoad/MayStore
10424 // for Other constraints as well.
10427 if (OpInfo.Type == InlineAsm::isInput)
10429 else if (OpInfo.Type == InlineAsm::isOutput)
10431 else if (OpInfo.Type == InlineAsm::isClobber)
10433 }
10434 }
10435
10436 unsigned get() const { return Flags; }
10437};
10438
10439} // end anonymous namespace
10440
10441static bool isFunction(SDValue Op) {
10442 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
10443 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10444 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
10445
10446 // In normal "call dllimport func" instruction (non-inlineasm) it force
10447 // indirect access by specifing call opcode. And usually specially print
10448 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
10449 // not do in this way now. (In fact, this is similar with "Data Access"
10450 // action). So here we ignore dllimport function.
10451 if (Fn && !Fn->hasDLLImportStorageClass())
10452 return true;
10453 }
10454 }
10455 return false;
10456}
10457
10458namespace {
10459
10460struct ConstraintDecisionInfo {
10461 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
10462 std::vector<SDValue> AsmNodeOperands;
10463 SDValue Glue, Chain;
10464 bool HasSideEffect = false;
10465 MCSymbol *BeginLabel = nullptr;
10466
10467 SmallVector<char> Buffer;
10468 raw_svector_ostream ErrorMsg;
10469
10470 ConstraintDecisionInfo() : ErrorMsg(Buffer) {}
10471};
10472
10473} // end anonymous namespace
10474
10475/// Construct operand info objects.
10476static bool
10477constructOperandInfo(ConstraintDecisionInfo &Info,
10478 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10479 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10480 ExtraFlags &ExtraInfo) {
10481 for (auto &T : TargetConstraints) {
10482 Info.ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
10483 SDISelAsmOperandInfo &OpInfo = Info.ConstraintOperands.back();
10484
10485 if (OpInfo.CallOperandVal)
10486 OpInfo.CallOperand = Builder.getValue(OpInfo.CallOperandVal);
10487
10488 if (!Info.HasSideEffect)
10489 Info.HasSideEffect = OpInfo.hasMemory(TLI);
10490
10491 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
10492 // FIXME: Could we compute this on OpInfo rather than T?
10493
10494 // Compute the constraint code and ConstraintType to use.
10496
10497 if (T.ConstraintType == TargetLowering::C_Immediate && OpInfo.CallOperand &&
10498 !isa<ConstantSDNode>(OpInfo.CallOperand)) {
10499 // We've delayed emitting a diagnostic like the "n" constraint because
10500 // inlining could cause an integer showing up.
10501 Info.ErrorMsg << "constraint '" << T.ConstraintCode
10502 << "' expects an integer constant expression";
10503 return true;
10504 }
10505
10506 ExtraInfo.update(T);
10507 }
10508
10509 return false;
10510}
10511
10512/// Compute which constraint option to use for each operand.
10513static void
10514computeConstraintToUse(ConstraintDecisionInfo &Info, const CallBase &Call,
10515 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10516 SelectionDAGBuilder &Builder, const TargetLowering &TLI,
10517 const TargetMachine &TM, SelectionDAG &DAG) {
10518 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10520 IA->collectAsmStrs(AsmStrs);
10521
10522 int OpNo = -1;
10523 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10524 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10525 OpNo++;
10526
10527 // If this is an output operand with a matching input operand, look up the
10528 // matching input. If their types mismatch, e.g. one is an integer, the
10529 // other is floating point, or their sizes are different, flag it as an
10530 // error.
10531 if (OpInfo.hasMatchingInput()) {
10532 SDISelAsmOperandInfo &Input =
10533 Info.ConstraintOperands[OpInfo.MatchingInput];
10534 patchMatchingInput(OpInfo, Input, DAG);
10535 }
10536
10537 // Compute the constraint code and ConstraintType to use.
10538 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10539
10540 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10541 OpInfo.Type == InlineAsm::isClobber) ||
10542 OpInfo.ConstraintType == TargetLowering::C_Address)
10543 continue;
10544
10545 // In Linux PIC model, there are 4 cases about value/label addressing:
10546 //
10547 // 1: Function call or Label jmp inside the module.
10548 // 2: Data access (such as global variable, static variable) inside module.
10549 // 3: Function call or Label jmp outside the module.
10550 // 4: Data access (such as global variable) outside the module.
10551 //
10552 // Due to current llvm inline asm architecture designed to not "recognize"
10553 // the asm code, there are quite troubles for us to treat mem addressing
10554 // differently for same value/adress used in different instructions.
10555 // For example, in pic model, call a func may in plt way or direclty
10556 // pc-related, but lea/mov a function adress may use got.
10557 //
10558 // Here we try to "recognize" function call for the case 1 and case 3 in
10559 // inline asm. And try to adjust the constraint for them.
10560 //
10561 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10562 // label, so here we don't handle jmp function label now, but we need to
10563 // enhance it (especilly in PIC model) if we meet meaningful requirements.
10564 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10565 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10567 OpInfo.isIndirect = false;
10568 OpInfo.ConstraintType = TargetLowering::C_Address;
10569 }
10570
10571 // If this is a memory input, and if the operand is not indirect, do what we
10572 // need to provide an address for the memory input.
10573 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10574 !OpInfo.isIndirect) {
10575 assert((OpInfo.isMultipleAlternative ||
10576 (OpInfo.Type == InlineAsm::isInput)) &&
10577 "Can only indirectify direct input operands!");
10578
10579 // Memory operands really want the address of the value.
10580 Info.Chain = getAddressForMemoryInput(Info.Chain, Builder.getCurSDLoc(),
10581 OpInfo, DAG);
10582
10583 // There is no longer a Value* corresponding to this operand.
10584 OpInfo.CallOperandVal = nullptr;
10585
10586 // It is now an indirect operand.
10587 OpInfo.isIndirect = true;
10588 }
10589 }
10590}
10591
10592/// Prepare DAG-level operands. As part of this, assign virtual and physical
10593/// registers for inputs and output.
10594static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info,
10595 const CallBase &Call,
10596 SelectionDAGBuilder &Builder,
10597 const TargetLowering &TLI,
10598 SelectionDAG &DAG) {
10599 SDLoc DL = Builder.getCurSDLoc();
10600 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10601 // Assign Registers.
10602 SDISelAsmOperandInfo &RefOpInfo =
10603 OpInfo.isMatchingInputConstraint()
10604 ? Info.ConstraintOperands[OpInfo.getMatchedOperand()]
10605 : OpInfo;
10606 const auto RegError = getRegistersForValue(DAG, DL, OpInfo, RefOpInfo);
10607 if (RegError) {
10608 const MachineFunction &MF = DAG.getMachineFunction();
10610 const char *RegName = TRI.getName(*RegError);
10611 Info.ErrorMsg << "register '" << RegName << "' allocated for constraint '"
10612 << OpInfo.ConstraintCode
10613 << "' does not match required type";
10614 return true;
10615 }
10616
10617 auto DetectWriteToReservedRegister = [&]() {
10618 const MachineFunction &MF = DAG.getMachineFunction();
10620
10621 for (Register Reg : OpInfo.AssignedRegs.Regs) {
10622 if (Reg.isPhysical() && TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10623 Info.ErrorMsg << "write to reserved register '"
10624 << TRI.getRegAsmName(Reg) << "'";
10625 return true;
10626 }
10627 }
10628
10629 return false;
10630 };
10631 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10632 (OpInfo.Type == InlineAsm::isInput &&
10633 !OpInfo.isMatchingInputConstraint())) &&
10634 "Only address as input operand is allowed.");
10635
10636 switch (OpInfo.Type) {
10638 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10639 const InlineAsm::ConstraintCode ConstraintID =
10640 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10642 "Failed to convert memory constraint code to constraint id.");
10643
10644 // Add information to the INLINEASM node to know about this output.
10646 OpFlags.setMemConstraint(ConstraintID);
10647 Info.AsmNodeOperands.push_back(
10648 DAG.getTargetConstant(OpFlags, DL, MVT::i32));
10649 Info.AsmNodeOperands.push_back(OpInfo.CallOperand);
10650 } else {
10651 // Otherwise, this outputs to a register (directly for C_Register /
10652 // C_RegisterClass, and a target-defined fashion for
10653 // C_Immediate/C_Other). Find a register that we can use.
10654 if (OpInfo.AssignedRegs.Regs.empty()) {
10655 Info.ErrorMsg << "could not allocate output register for "
10656 << "constraint '" << OpInfo.ConstraintCode << "'";
10657 return true;
10658 }
10659
10660 if (DetectWriteToReservedRegister())
10661 return true;
10662
10663 // Add information to the INLINEASM node to know that this register is
10664 // set.
10665 OpInfo.AssignedRegs.AddInlineAsmOperands(
10666 OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10668 false, 0, DL, DAG, Info.AsmNodeOperands);
10669 }
10670 break;
10671
10672 case InlineAsm::isInput:
10673 case InlineAsm::isLabel: {
10674 SDValue InOperandVal = OpInfo.CallOperand;
10675
10676 if (OpInfo.isMatchingInputConstraint()) {
10677 // If this is required to match an output register we have already set,
10678 // just use its register.
10679 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10680 Info.AsmNodeOperands);
10681 InlineAsm::Flag Flag(Info.AsmNodeOperands[CurOp]->getAsZExtVal());
10682 if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10683 if (OpInfo.isIndirect) {
10684 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10685 Info.ErrorMsg << "inline asm not supported yet: cannot handle "
10686 << "tied indirect register inputs";
10687 return true;
10688 }
10689
10694 auto *R = cast<RegisterSDNode>(Info.AsmNodeOperands[CurOp + 1]);
10695 Register TiedReg = R->getReg();
10696 MVT RegVT = R->getSimpleValueType(0);
10697 const TargetRegisterClass *RC =
10698 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
10699 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10700 : TRI.getMinimalPhysRegClass(TiedReg);
10701 for (unsigned I = 0, E = Flag.getNumOperandRegisters(); I != E; ++I)
10702 Regs.push_back(MRI.createVirtualRegister(RC));
10703
10704 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10705
10706 // Use the produced MatchedRegs object to
10707 MatchedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10708 &Info.Glue, &Call);
10710 OpInfo.getMatchedOperand(), DL, DAG,
10711 Info.AsmNodeOperands);
10712 break;
10713 }
10714
10715 assert(Flag.isMemKind() && "Unknown matching constraint!");
10716 assert(Flag.getNumOperandRegisters() == 1 &&
10717 "Unexpected number of operands");
10718
10719 // Add information to the INLINEASM node to know about this input.
10720 // See InlineAsm.h isUseOperandTiedToDef.
10721 Flag.clearMemConstraint();
10722 Flag.setMatchingOp(OpInfo.getMatchedOperand());
10723 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10724 Flag, DL, TLI.getPointerTy(DAG.getDataLayout())));
10725 Info.AsmNodeOperands.push_back(Info.AsmNodeOperands[CurOp + 1]);
10726 break;
10727 }
10728
10729 // Treat indirect 'X' constraint as memory.
10730 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10731 OpInfo.isIndirect)
10732 OpInfo.ConstraintType = TargetLowering::C_Memory;
10733
10734 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10735 OpInfo.ConstraintType == TargetLowering::C_Other) {
10736 std::vector<SDValue> Ops;
10737 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10738 Ops, DAG);
10739 if (Ops.empty()) {
10740 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10741 if (isa<ConstantSDNode>(InOperandVal)) {
10742 Info.ErrorMsg << "value out of range for constraint '"
10743 << OpInfo.ConstraintCode << "'";
10744 return true;
10745 }
10746
10747 Info.ErrorMsg << "invalid operand for inline asm constraint '"
10748 << OpInfo.ConstraintCode << "'";
10749 return true;
10750 }
10751
10752 // Add information to the INLINEASM node to know about this input.
10753 InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10754 Info.AsmNodeOperands.push_back(DAG.getTargetConstant(
10755 ResOpType, DL, TLI.getPointerTy(DAG.getDataLayout())));
10756 llvm::append_range(Info.AsmNodeOperands, Ops);
10757 break;
10758 }
10759
10760 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10761 assert((OpInfo.isIndirect ||
10762 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10763 "Operand must be indirect to be a mem!");
10764 assert(InOperandVal.getValueType() ==
10765 TLI.getPointerTy(DAG.getDataLayout()) &&
10766 "Memory operands expect pointer values");
10767
10768 const InlineAsm::ConstraintCode ConstraintID =
10769 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10771 "Failed to convert memory constraint code to constraint id.");
10772
10773 // Add information to the INLINEASM node to know about this input.
10775 ResOpType.setMemConstraint(ConstraintID);
10776 Info.AsmNodeOperands.push_back(
10777 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10778 Info.AsmNodeOperands.push_back(InOperandVal);
10779 break;
10780 }
10781
10782 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10783 const InlineAsm::ConstraintCode ConstraintID =
10784 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10786 "Failed to convert memory constraint code to constraint id.");
10787
10789
10790 SDValue AsmOp = InOperandVal;
10791 if (isFunction(InOperandVal)) {
10792 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10793 ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10794 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10795 InOperandVal.getValueType(),
10796 GA->getOffset());
10797 }
10798
10799 // Add information to the INLINEASM node to know about this input.
10800 ResOpType.setMemConstraint(ConstraintID);
10801
10802 Info.AsmNodeOperands.push_back(
10803 DAG.getTargetConstant(ResOpType, DL, MVT::i32));
10804 Info.AsmNodeOperands.push_back(AsmOp);
10805 break;
10806 }
10807
10808 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10809 OpInfo.ConstraintType != TargetLowering::C_Register) {
10810 Info.ErrorMsg << "unknown asm constraint '" << OpInfo.ConstraintCode
10811 << "'";
10812 return true;
10813 }
10814
10815 // TODO: Support this.
10816 if (OpInfo.isIndirect) {
10817 Info.ErrorMsg << "cannot handle indirect register inputs yet for "
10818 << "constraint '" << OpInfo.ConstraintCode << "'";
10819 return true;
10820 }
10821
10822 // Copy the input into the appropriate registers.
10823 if (OpInfo.AssignedRegs.Regs.empty()) {
10824 Info.ErrorMsg << "could not allocate input reg for constraint '"
10825 << OpInfo.ConstraintCode << "'";
10826 return true;
10827 }
10828
10829 if (DetectWriteToReservedRegister())
10830 return true;
10831
10832 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, DL, Info.Chain,
10833 &Info.Glue, &Call);
10834 OpInfo.AssignedRegs.AddInlineAsmOperands(
10835 InlineAsm::Kind::RegUse, false, 0, DL, DAG, Info.AsmNodeOperands);
10836 break;
10837 }
10838
10840 // Add the clobbered value to the operand list, so that the register
10841 // allocator is aware that the physreg got clobbered.
10842 if (!OpInfo.AssignedRegs.Regs.empty())
10843 OpInfo.AssignedRegs.AddInlineAsmOperands(
10844 InlineAsm::Kind::Clobber, false, 0, DL, DAG, Info.AsmNodeOperands);
10845 break;
10846 }
10847 }
10848
10849 return false;
10850}
10851
10852/// DetermineConstraints - Find the constraints to use for inline asm operands.
10853static bool
10854determineConstraints(ConstraintDecisionInfo &Info,
10855 TargetLowering::AsmOperandInfoVector &TargetConstraints,
10856 const CallBase &Call, SelectionDAGBuilder &Builder,
10857 const TargetLowering &TLI, const TargetMachine &TM,
10858 SelectionDAG &DAG, const BasicBlock *EHPadBB) {
10859 const auto *IA = cast<InlineAsm>(Call.getCalledOperand());
10860 ExtraFlags ExtraInfo(Call);
10861
10862 // First pass: Construct operand info objects.
10863 Info.HasSideEffect = IA->hasSideEffects();
10864 if (constructOperandInfo(Info, TargetConstraints, Builder, TLI, ExtraInfo))
10865 return true;
10866
10867 // We won't need to flush pending loads if this asm doesn't touch
10868 // memory and is nonvolatile.
10869 Info.Chain = Info.HasSideEffect ? Builder.getRoot() : DAG.getRoot();
10870
10871 bool IsCallBr = isa<CallBrInst>(Call);
10872 bool EmitEHLabels = isa<InvokeInst>(Call);
10873 if (IsCallBr || EmitEHLabels)
10874 // If this is a callbr or invoke we need to flush pending exports since
10875 // inlineasm_br and invoke are terminators.
10876 // We need to do this before nodes are glued to the inlineasm_br node.
10877 Info.Chain = Builder.getControlRoot();
10878
10879 if (EmitEHLabels)
10880 Info.Chain = Builder.lowerStartEH(Info.Chain, EHPadBB, Info.BeginLabel);
10881
10882 // Second pass: Compute which constraint option to use.
10883 computeConstraintToUse(Info, Call, TargetConstraints, Builder, TLI, TM, DAG);
10884
10885 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10886 Info.AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
10887 Info.AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10888 IA->getAsmString().data(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10889
10890 // If we have a !srcloc metadata node associated with it, we want to attach
10891 // this to the ultimately generated inline asm machineinstr. To do this, we
10892 // pass in the third operand as this (potentially null) inline asm MDNode.
10893 const MDNode *SrcLoc = Call.getMetadata("srcloc");
10894 Info.AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10895
10896 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10897 // bits as operand 3.
10898 Info.AsmNodeOperands.push_back(
10899 DAG.getTargetConstant(ExtraInfo.get(), Builder.getCurSDLoc(),
10900 TLI.getPointerTy(DAG.getDataLayout())));
10901
10902 // Third pass: Prepare DAG-level operands
10903 return prepareDAGLevelOperands(Info, Call, Builder, TLI, DAG);
10904}
10905
10906/// visitInlineAsm - Handle a call to an InlineAsm object.
10907void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
10908 const BasicBlock *EHPadBB) {
10909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10911 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
10912
10913 assert((!isa<InvokeInst>(Call) || EHPadBB) &&
10914 "InvokeInst must have an EHPadBB");
10915
10916 ConstraintDecisionInfo Info;
10917 if (determineConstraints(Info, TargetConstraints, Call, *this, TLI, TM, DAG,
10918 EHPadBB))
10919 return emitInlineAsmError(Call, Info.ErrorMsg.str());
10920
10921 SDValue Glue = Info.Glue;
10922 SDValue Chain = Info.Chain;
10923
10924 // Finish up input operands. Set the input chain and add the flag last.
10925 Info.AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10926 if (Glue.getNode())
10927 Info.AsmNodeOperands.push_back(Glue);
10928
10929 bool IsCallBr = isa<CallBrInst>(Call);
10930 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10931 Chain =
10932 DAG.getNode(ISDOpc, getCurSDLoc(), DAG.getVTList(MVT::Other, MVT::Glue),
10933 Info.AsmNodeOperands);
10934 Glue = Chain.getValue(1);
10935
10936 // Do additional work to generate outputs.
10937
10938 SmallVector<EVT, 1> ResultVTs;
10939 SmallVector<SDValue, 1> ResultValues;
10940 SmallVector<SDValue, 8> OutChains;
10941
10942 llvm::Type *CallResultType = Call.getType();
10943 ArrayRef<Type *> ResultTypes;
10944 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10945 ResultTypes = StructResult->elements();
10946 else if (!CallResultType->isVoidTy())
10947 ResultTypes = ArrayRef(CallResultType);
10948
10949 auto CurResultType = ResultTypes.begin();
10950 auto handleRegAssign = [&](SDValue V) {
10951 assert(CurResultType != ResultTypes.end() && "Unexpected value");
10952 assert((*CurResultType)->isSized() && "Unexpected unsized type");
10953 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10954 ++CurResultType;
10955 // If the type of the inline asm call site return value is different but has
10956 // same size as the type of the asm output bitcast it. One example of this
10957 // is for vectors with different width / number of elements. This can
10958 // happen for register classes that can contain multiple different value
10959 // types. The preg or vreg allocated may not have the same VT as was
10960 // expected.
10961 //
10962 // This can also happen for a return value that disagrees with the register
10963 // class it is put in, eg. a double in a general-purpose register on a
10964 // 32-bit machine.
10965 if (ResultVT != V.getValueType() &&
10966 ResultVT.getSizeInBits() == V.getValueSizeInBits())
10967 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10968 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10969 V.getValueType().isInteger()) {
10970 // If a result value was tied to an input value, the computed result
10971 // may have a wider width than the expected result. Extract the
10972 // relevant portion.
10973 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10974 }
10975 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10976 ResultVTs.push_back(ResultVT);
10977 ResultValues.push_back(V);
10978 };
10979
10980 // Deal with output operands.
10981 for (SDISelAsmOperandInfo &OpInfo : Info.ConstraintOperands) {
10982 if (OpInfo.Type == InlineAsm::isOutput) {
10983 SDValue Val;
10984 // Skip trivial output operands.
10985 if (OpInfo.AssignedRegs.Regs.empty())
10986 continue;
10987
10988 switch (OpInfo.ConstraintType) {
10991 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10992 Chain, &Glue, &Call);
10993 break;
10996 Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10997 OpInfo, DAG);
10998 break;
11000 break; // Already handled.
11002 break; // Silence warning.
11004 assert(false && "Unexpected unknown constraint");
11005 }
11006
11007 // Indirect output manifest as stores. Record output chains.
11008 if (OpInfo.isIndirect) {
11009 const Value *Ptr = OpInfo.CallOperandVal;
11010 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
11011 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
11012 MachinePointerInfo(Ptr));
11013 OutChains.push_back(Store);
11014 } else {
11015 // generate CopyFromRegs to associated registers.
11016 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
11017 if (Val.getOpcode() == ISD::MERGE_VALUES) {
11018 for (const SDValue &V : Val->op_values())
11019 handleRegAssign(V);
11020 } else
11021 handleRegAssign(Val);
11022 }
11023 }
11024 }
11025
11026 // Set results.
11027 if (!ResultValues.empty()) {
11028 assert(CurResultType == ResultTypes.end() &&
11029 "Mismatch in number of ResultTypes");
11030 assert(ResultValues.size() == ResultTypes.size() &&
11031 "Mismatch in number of output operands in asm result");
11032
11033 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11034 DAG.getVTList(ResultVTs), ResultValues);
11035 setValue(&Call, V);
11036 }
11037
11038 // Collect store chains.
11039 if (!OutChains.empty())
11040 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
11041
11042 if (const auto *II = dyn_cast<InvokeInst>(&Call))
11043 Chain = lowerEndEH(Chain, II, EHPadBB, Info.BeginLabel);
11044
11045 // Only Update Root if inline assembly has a memory effect.
11046 if (ResultValues.empty() || Info.HasSideEffect || !OutChains.empty() ||
11047 IsCallBr || isa<InvokeInst>(Call))
11048 DAG.setRoot(Chain);
11049}
11050
11051void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
11052 const Twine &Message) {
11053 LLVMContext &Ctx = *DAG.getContext();
11054 Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
11055
11056 // Make sure we leave the DAG in a valid state
11057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11058 SmallVector<EVT, 1> ValueVTs;
11059 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
11060
11061 if (ValueVTs.empty())
11062 return;
11063
11065 for (const EVT &VT : ValueVTs)
11066 Ops.push_back(DAG.getUNDEF(VT));
11067
11068 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
11069}
11070
11071void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
11072 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
11073 MVT::Other, getRoot(),
11074 getValue(I.getArgOperand(0)),
11075 DAG.getSrcValue(I.getArgOperand(0))));
11076}
11077
11078void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
11079 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11080 const DataLayout &DL = DAG.getDataLayout();
11081 SDValue V = DAG.getVAArg(
11082 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
11083 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
11084 DL.getABITypeAlign(I.getType()).value());
11085 DAG.setRoot(V.getValue(1));
11086
11087 if (I.getType()->isPointerTy())
11088 V = DAG.getPtrExtOrTrunc(
11089 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
11090 setValue(&I, V);
11091}
11092
11093void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
11094 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
11095 MVT::Other, getRoot(),
11096 getValue(I.getArgOperand(0)),
11097 DAG.getSrcValue(I.getArgOperand(0))));
11098}
11099
11100void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
11101 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
11102 MVT::Other, getRoot(),
11103 getValue(I.getArgOperand(0)),
11104 getValue(I.getArgOperand(1)),
11105 DAG.getSrcValue(I.getArgOperand(0)),
11106 DAG.getSrcValue(I.getArgOperand(1))));
11107}
11108
11110 const Instruction &I,
11111 SDValue Op) {
11112 std::optional<ConstantRange> CR = getRange(I);
11113
11114 if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
11115 return Op;
11116
11117 APInt Hi = CR->getUnsignedMax();
11118 unsigned Bits = std::max(Hi.getActiveBits(),
11119 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
11120
11121 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11122
11123 SDLoc SL = getCurSDLoc();
11124
11125 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
11126 DAG.getValueType(SmallVT));
11127 unsigned NumVals = Op.getNode()->getNumValues();
11128 if (NumVals == 1)
11129 return ZExt;
11130
11132
11133 Ops.push_back(ZExt);
11134 for (unsigned I = 1; I != NumVals; ++I)
11135 Ops.push_back(Op.getValue(I));
11136
11137 return DAG.getMergeValues(Ops, SL);
11138}
11139
11141 SelectionDAG &DAG, const Instruction &I, SDValue Op) {
11142 FPClassTest Classes = getNoFPClass(I);
11143 if (Classes == fcNone)
11144 return Op;
11145
11146 SDLoc SL = getCurSDLoc();
11147 SDValue TestConst = DAG.getTargetConstant(Classes, SDLoc(), MVT::i32);
11148
11149 if (Op.getOpcode() != ISD::MERGE_VALUES) {
11150 return DAG.getNode(ISD::AssertNoFPClass, SL, Op.getValueType(), Op,
11151 TestConst);
11152 }
11153
11154 SmallVector<SDValue, 8> Ops(Op.getNumOperands());
11155 for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
11156 SDValue MergeOp = Op.getOperand(I);
11157 Ops[I] = DAG.getNode(ISD::AssertNoFPClass, SL, MergeOp.getValueType(),
11158 MergeOp, TestConst);
11159 }
11160
11161 return DAG.getMergeValues(Ops, SL);
11162}
11163
11164/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
11165/// the call being lowered.
11166///
11167/// This is a helper for lowering intrinsics that follow a target calling
11168/// convention or require stack pointer adjustment. Only a subset of the
11169/// intrinsic's operands need to participate in the calling convention.
11172 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
11173 AttributeSet RetAttrs, bool IsPatchPoint) {
11175 Args.reserve(NumArgs);
11176
11177 // Populate the argument list.
11178 // Attributes for args start at offset 1, after the return attribute.
11179 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
11180 ArgI != ArgE; ++ArgI) {
11181 const Value *V = Call->getOperand(ArgI);
11182
11183 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
11184
11185 TargetLowering::ArgListEntry Entry(getValue(V), V->getType());
11186 Entry.setAttributes(Call, ArgI);
11187 Args.push_back(Entry);
11188 }
11189
11191 .setChain(getRoot())
11192 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
11193 RetAttrs)
11194 .setDiscardResult(Call->use_empty())
11195 .setIsPatchPoint(IsPatchPoint)
11197 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
11198}
11199
11200/// Add a stack map intrinsic call's live variable operands to a stackmap
11201/// or patchpoint target node's operand list.
11202///
11203/// Constants are converted to TargetConstants purely as an optimization to
11204/// avoid constant materialization and register allocation.
11205///
11206/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
11207/// generate addess computation nodes, and so FinalizeISel can convert the
11208/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
11209/// address materialization and register allocation, but may also be required
11210/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
11211/// alloca in the entry block, then the runtime may assume that the alloca's
11212/// StackMap location can be read immediately after compilation and that the
11213/// location is valid at any point during execution (this is similar to the
11214/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
11215/// only available in a register, then the runtime would need to trap when
11216/// execution reaches the StackMap in order to read the alloca's location.
11217static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
11219 SelectionDAGBuilder &Builder) {
11220 SelectionDAG &DAG = Builder.DAG;
11221 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
11222 SDValue Op = Builder.getValue(Call.getArgOperand(I));
11223
11224 // Things on the stack are pointer-typed, meaning that they are already
11225 // legal and can be emitted directly to target nodes.
11227 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
11228 } else {
11229 // Otherwise emit a target independent node to be legalised.
11230 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
11231 }
11232 }
11233}
11234
11235/// Lower llvm.experimental.stackmap.
11236void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
11237 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
11238 // [live variables...])
11239
11240 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
11241
11242 SDValue Chain, InGlue, Callee;
11244
11245 SDLoc DL = getCurSDLoc();
11247
11248 // The stackmap intrinsic only records the live variables (the arguments
11249 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
11250 // intrinsic, this won't be lowered to a function call. This means we don't
11251 // have to worry about calling conventions and target specific lowering code.
11252 // Instead we perform the call lowering right here.
11253 //
11254 // chain, flag = CALLSEQ_START(chain, 0, 0)
11255 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
11256 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
11257 //
11258 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
11259 InGlue = Chain.getValue(1);
11260
11261 // Add the STACKMAP operands, starting with DAG house-keeping.
11262 Ops.push_back(Chain);
11263 Ops.push_back(InGlue);
11264
11265 // Add the <id>, <numShadowBytes> operands.
11266 //
11267 // These do not require legalisation, and can be emitted directly to target
11268 // constant nodes.
11269 SDValue ID = getValue(CI.getArgOperand(0));
11270 assert(ID.getValueType() == MVT::i64);
11271 SDValue IDConst =
11272 DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
11273 Ops.push_back(IDConst);
11274
11275 SDValue Shad = getValue(CI.getArgOperand(1));
11276 assert(Shad.getValueType() == MVT::i32);
11277 SDValue ShadConst =
11278 DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
11279 Ops.push_back(ShadConst);
11280
11281 // Add the live variables.
11282 addStackMapLiveVars(CI, 2, DL, Ops, *this);
11283
11284 // Create the STACKMAP node.
11285 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11286 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
11287 InGlue = Chain.getValue(1);
11288
11289 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
11290
11291 // Stackmaps don't generate values, so nothing goes into the NodeMap.
11292
11293 // Set the root to the target-lowered call chain.
11294 DAG.setRoot(Chain);
11295
11296 // Inform the Frame Information that we have a stackmap in this function.
11297 FuncInfo.MF->getFrameInfo().setHasStackMap();
11298}
11299
11300/// Lower llvm.experimental.patchpoint directly to its target opcode.
11301void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
11302 const BasicBlock *EHPadBB) {
11303 // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
11304 // i32 <numBytes>,
11305 // i8* <target>,
11306 // i32 <numArgs>,
11307 // [Args...],
11308 // [live variables...])
11309
11311 bool IsAnyRegCC = CC == CallingConv::AnyReg;
11312 bool HasDef = !CB.getType()->isVoidTy();
11313 SDLoc dl = getCurSDLoc();
11315
11316 // Handle immediate and symbolic callees.
11317 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
11318 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
11319 /*isTarget=*/true);
11320 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
11321 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
11322 SDLoc(SymbolicCallee),
11323 SymbolicCallee->getValueType(0));
11324
11325 // Get the real number of arguments participating in the call <numArgs>
11326 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
11327 unsigned NumArgs = NArgVal->getAsZExtVal();
11328
11329 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
11330 // Intrinsics include all meta-operands up to but not including CC.
11331 unsigned NumMetaOpers = PatchPointOpers::CCPos;
11332 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
11333 "Not enough arguments provided to the patchpoint intrinsic");
11334
11335 // For AnyRegCC the arguments are lowered later on manually.
11336 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
11337 Type *ReturnTy =
11338 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
11339
11340 TargetLowering::CallLoweringInfo CLI(DAG);
11341 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
11342 ReturnTy, CB.getAttributes().getRetAttrs(), true);
11343 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
11344
11345 SDNode *CallEnd = Result.second.getNode();
11346 if (CallEnd->getOpcode() == ISD::EH_LABEL)
11347 CallEnd = CallEnd->getOperand(0).getNode();
11348 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
11349 CallEnd = CallEnd->getOperand(0).getNode();
11350
11351 /// Get a call instruction from the call sequence chain.
11352 /// Tail calls are not allowed.
11353 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
11354 "Expected a callseq node.");
11355 SDNode *Call = CallEnd->getOperand(0).getNode();
11356 bool HasGlue = Call->getGluedNode();
11357
11358 // Replace the target specific call node with the patchable intrinsic.
11360
11361 // Push the chain.
11362 Ops.push_back(*(Call->op_begin()));
11363
11364 // Optionally, push the glue (if any).
11365 if (HasGlue)
11366 Ops.push_back(*(Call->op_end() - 1));
11367
11368 // Push the register mask info.
11369 if (HasGlue)
11370 Ops.push_back(*(Call->op_end() - 2));
11371 else
11372 Ops.push_back(*(Call->op_end() - 1));
11373
11374 // Add the <id> and <numBytes> constants.
11375 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
11376 Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
11377 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
11378 Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
11379
11380 // Add the callee.
11381 Ops.push_back(Callee);
11382
11383 // Adjust <numArgs> to account for any arguments that have been passed on the
11384 // stack instead.
11385 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
11386 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
11387 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
11388 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
11389
11390 // Add the calling convention
11391 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
11392
11393 // Add the arguments we omitted previously. The register allocator should
11394 // place these in any free register.
11395 if (IsAnyRegCC)
11396 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
11397 Ops.push_back(getValue(CB.getArgOperand(i)));
11398
11399 // Push the arguments from the call instruction.
11400 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
11401 Ops.append(Call->op_begin() + 2, e);
11402
11403 // Push live variables for the stack map.
11404 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
11405
11406 SDVTList NodeTys;
11407 if (IsAnyRegCC && HasDef) {
11408 // Create the return types based on the intrinsic definition
11409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11410 SmallVector<EVT, 3> ValueVTs;
11411 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
11412 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
11413
11414 // There is always a chain and a glue type at the end
11415 ValueVTs.push_back(MVT::Other);
11416 ValueVTs.push_back(MVT::Glue);
11417 NodeTys = DAG.getVTList(ValueVTs);
11418 } else
11419 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11420
11421 // Replace the target specific call node with a PATCHPOINT node.
11422 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
11423
11424 // Update the NodeMap.
11425 if (HasDef) {
11426 if (IsAnyRegCC)
11427 setValue(&CB, SDValue(PPV.getNode(), 0));
11428 else
11429 setValue(&CB, Result.first);
11430 }
11431
11432 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
11433 // call sequence. Furthermore the location of the chain and glue can change
11434 // when the AnyReg calling convention is used and the intrinsic returns a
11435 // value.
11436 if (IsAnyRegCC && HasDef) {
11437 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
11438 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
11439 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11440 } else
11441 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
11442 DAG.DeleteNode(Call);
11443
11444 // Inform the Frame Information that we have a patchpoint in this function.
11445 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
11446}
11447
11448void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
11449 unsigned Intrinsic) {
11450 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11451 SDValue Op1 = getValue(I.getArgOperand(0));
11452 SDValue Op2;
11453 if (I.arg_size() > 1)
11454 Op2 = getValue(I.getArgOperand(1));
11455 SDLoc dl = getCurSDLoc();
11456 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11457 SDValue Res;
11458 SDNodeFlags SDFlags;
11459 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
11460 SDFlags.copyFMF(*FPMO);
11461
11462 switch (Intrinsic) {
11463 case Intrinsic::vector_reduce_fadd:
11464 if (SDFlags.hasAllowReassociation())
11465 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
11466 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
11467 SDFlags);
11468 else
11469 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
11470 break;
11471 case Intrinsic::vector_reduce_fmul:
11472 if (SDFlags.hasAllowReassociation())
11473 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
11474 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
11475 SDFlags);
11476 else
11477 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
11478 break;
11479 case Intrinsic::vector_reduce_add:
11480 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
11481 break;
11482 case Intrinsic::vector_reduce_mul:
11483 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
11484 break;
11485 case Intrinsic::vector_reduce_and:
11486 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
11487 break;
11488 case Intrinsic::vector_reduce_or:
11489 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
11490 break;
11491 case Intrinsic::vector_reduce_xor:
11492 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
11493 break;
11494 case Intrinsic::vector_reduce_smax:
11495 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
11496 break;
11497 case Intrinsic::vector_reduce_smin:
11498 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
11499 break;
11500 case Intrinsic::vector_reduce_umax:
11501 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
11502 break;
11503 case Intrinsic::vector_reduce_umin:
11504 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
11505 break;
11506 case Intrinsic::vector_reduce_fmax:
11507 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
11508 break;
11509 case Intrinsic::vector_reduce_fmin:
11510 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
11511 break;
11512 case Intrinsic::vector_reduce_fmaximum:
11513 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
11514 break;
11515 case Intrinsic::vector_reduce_fminimum:
11516 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
11517 break;
11518 case Intrinsic::vector_reduce_fmaximumnum:
11519 Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
11520 break;
11521 case Intrinsic::vector_reduce_fminimumnum:
11522 Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
11523 break;
11524 default:
11525 llvm_unreachable("Unhandled vector reduce intrinsic");
11526 }
11527 setValue(&I, Res);
11528}
11529
11530/// Returns an AttributeList representing the attributes applied to the return
11531/// value of the given call.
11534 if (CLI.RetSExt)
11535 Attrs.push_back(Attribute::SExt);
11536 if (CLI.RetZExt)
11537 Attrs.push_back(Attribute::ZExt);
11538 if (CLI.IsInReg)
11539 Attrs.push_back(Attribute::InReg);
11540
11541 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
11542 Attrs);
11543}
11544
11545/// TargetLowering::LowerCallTo - This is the default LowerCallTo
11546/// implementation, which just calls LowerCall.
11547/// FIXME: When all targets are
11548/// migrated to using LowerCall, this hook should be integrated into SDISel.
11549std::pair<SDValue, SDValue>
11551 LLVMContext &Context = CLI.RetTy->getContext();
11552
11553 // Handle the incoming return values from the call.
11554 CLI.Ins.clear();
11555 SmallVector<Type *, 4> RetOrigTys;
11557 auto &DL = CLI.DAG.getDataLayout();
11558 ComputeValueTypes(DL, CLI.OrigRetTy, RetOrigTys, &Offsets);
11559
11560 SmallVector<EVT, 4> RetVTs;
11561 if (CLI.RetTy != CLI.OrigRetTy) {
11562 assert(RetOrigTys.size() == 1 &&
11563 "Only supported for non-aggregate returns");
11564 RetVTs.push_back(getValueType(DL, CLI.RetTy));
11565 } else {
11566 for (Type *Ty : RetOrigTys)
11567 RetVTs.push_back(getValueType(DL, Ty));
11568 }
11569
11570 if (CLI.IsPostTypeLegalization) {
11571 // If we are lowering a libcall after legalization, split the return type.
11572 SmallVector<Type *, 4> OldRetOrigTys;
11573 SmallVector<EVT, 4> OldRetVTs;
11574 SmallVector<TypeSize, 4> OldOffsets;
11575 RetOrigTys.swap(OldRetOrigTys);
11576 RetVTs.swap(OldRetVTs);
11577 Offsets.swap(OldOffsets);
11578
11579 for (size_t i = 0, e = OldRetVTs.size(); i != e; ++i) {
11580 EVT RetVT = OldRetVTs[i];
11581 uint64_t Offset = OldOffsets[i];
11582 MVT RegisterVT = getRegisterType(Context, RetVT);
11583 unsigned NumRegs = getNumRegisters(Context, RetVT);
11584 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
11585 RetOrigTys.append(NumRegs, OldRetOrigTys[i]);
11586 RetVTs.append(NumRegs, RegisterVT);
11587 for (unsigned j = 0; j != NumRegs; ++j)
11588 Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
11589 }
11590 }
11591
11593 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
11594
11595 bool CanLowerReturn =
11597 CLI.IsVarArg, Outs, Context, CLI.RetTy);
11598
11599 SDValue DemoteStackSlot;
11600 int DemoteStackIdx = -100;
11601 if (!CanLowerReturn) {
11602 // FIXME: equivalent assert?
11603 // assert(!CS.hasInAllocaArgument() &&
11604 // "sret demotion is incompatible with inalloca");
11605 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
11606 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11608 DemoteStackIdx =
11609 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11610 Type *StackSlotPtrType = PointerType::get(Context, DL.getAllocaAddrSpace());
11611
11612 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11613 ArgListEntry Entry(DemoteStackSlot, StackSlotPtrType);
11614 Entry.IsSRet = true;
11615 Entry.Alignment = Alignment;
11616 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11617 CLI.NumFixedArgs += 1;
11618 CLI.getArgs()[0].IndirectType = CLI.RetTy;
11619 CLI.RetTy = CLI.OrigRetTy = Type::getVoidTy(Context);
11620
11621 // sret demotion isn't compatible with tail-calls, since the sret argument
11622 // points into the callers stack frame.
11623 CLI.IsTailCall = false;
11624 } else {
11625 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11626 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11627 for (unsigned I = 0, E = RetVTs.size(); I != E; ++I) {
11628 ISD::ArgFlagsTy Flags;
11629 if (NeedsRegBlock) {
11630 Flags.setInConsecutiveRegs();
11631 if (I == RetVTs.size() - 1)
11632 Flags.setInConsecutiveRegsLast();
11633 }
11634 EVT VT = RetVTs[I];
11635 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11636 unsigned NumRegs =
11637 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11638 for (unsigned i = 0; i != NumRegs; ++i) {
11639 ISD::InputArg Ret(Flags, RegisterVT, VT, RetOrigTys[I],
11641 if (CLI.RetTy->isPointerTy()) {
11642 Ret.Flags.setPointer();
11644 cast<PointerType>(CLI.RetTy)->getAddressSpace());
11645 }
11646 if (CLI.RetSExt)
11647 Ret.Flags.setSExt();
11648 if (CLI.RetZExt)
11649 Ret.Flags.setZExt();
11650 if (CLI.IsInReg)
11651 Ret.Flags.setInReg();
11652 CLI.Ins.push_back(Ret);
11653 }
11654 }
11655 }
11656
11657 // We push in swifterror return as the last element of CLI.Ins.
11658 ArgListTy &Args = CLI.getArgs();
11659 if (supportSwiftError()) {
11660 for (const ArgListEntry &Arg : Args) {
11661 if (Arg.IsSwiftError) {
11662 ISD::ArgFlagsTy Flags;
11663 Flags.setSwiftError();
11665 PointerType::getUnqual(Context),
11666 /*Used=*/true, ISD::InputArg::NoArgIndex, 0);
11667 CLI.Ins.push_back(Ret);
11668 }
11669 }
11670 }
11671
11672 // Handle all of the outgoing arguments.
11673 CLI.Outs.clear();
11674 CLI.OutVals.clear();
11675 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11676 SmallVector<Type *, 4> OrigArgTys;
11677 ComputeValueTypes(DL, Args[i].OrigTy, OrigArgTys);
11678 // FIXME: Split arguments if CLI.IsPostTypeLegalization
11679 Type *FinalType = Args[i].Ty;
11680 if (Args[i].IsByVal)
11681 FinalType = Args[i].IndirectType;
11682 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11683 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11684 for (unsigned Value = 0, NumValues = OrigArgTys.size(); Value != NumValues;
11685 ++Value) {
11686 Type *OrigArgTy = OrigArgTys[Value];
11687 Type *ArgTy = OrigArgTy;
11688 if (Args[i].Ty != Args[i].OrigTy) {
11689 assert(Value == 0 && "Only supported for non-aggregate arguments");
11690 ArgTy = Args[i].Ty;
11691 }
11692
11693 EVT VT = getValueType(DL, ArgTy);
11694 SDValue Op = SDValue(Args[i].Node.getNode(),
11695 Args[i].Node.getResNo() + Value);
11696 ISD::ArgFlagsTy Flags;
11697
11698 // Certain targets (such as MIPS), may have a different ABI alignment
11699 // for a type depending on the context. Give the target a chance to
11700 // specify the alignment it wants.
11701 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11702 Flags.setOrigAlign(OriginalAlignment);
11703
11704 if (i >= CLI.NumFixedArgs)
11705 Flags.setVarArg();
11706 if (ArgTy->isPointerTy()) {
11707 Flags.setPointer();
11708 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
11709 }
11710 if (Args[i].IsZExt)
11711 Flags.setZExt();
11712 if (Args[i].IsSExt)
11713 Flags.setSExt();
11714 if (Args[i].IsNoExt)
11715 Flags.setNoExt();
11716 if (Args[i].IsInReg) {
11717 // If we are using vectorcall calling convention, a structure that is
11718 // passed InReg - is surely an HVA
11720 isa<StructType>(FinalType)) {
11721 // The first value of a structure is marked
11722 if (0 == Value)
11723 Flags.setHvaStart();
11724 Flags.setHva();
11725 }
11726 // Set InReg Flag
11727 Flags.setInReg();
11728 }
11729 if (Args[i].IsSRet)
11730 Flags.setSRet();
11731 if (Args[i].IsSwiftSelf)
11732 Flags.setSwiftSelf();
11733 if (Args[i].IsSwiftAsync)
11734 Flags.setSwiftAsync();
11735 if (Args[i].IsSwiftError)
11736 Flags.setSwiftError();
11737 if (Args[i].IsCFGuardTarget)
11738 Flags.setCFGuardTarget();
11739 if (Args[i].IsByVal)
11740 Flags.setByVal();
11741 if (Args[i].IsByRef)
11742 Flags.setByRef();
11743 if (Args[i].IsPreallocated) {
11744 Flags.setPreallocated();
11745 // Set the byval flag for CCAssignFn callbacks that don't know about
11746 // preallocated. This way we can know how many bytes we should've
11747 // allocated and how many bytes a callee cleanup function will pop. If
11748 // we port preallocated to more targets, we'll have to add custom
11749 // preallocated handling in the various CC lowering callbacks.
11750 Flags.setByVal();
11751 }
11752 if (Args[i].IsInAlloca) {
11753 Flags.setInAlloca();
11754 // Set the byval flag for CCAssignFn callbacks that don't know about
11755 // inalloca. This way we can know how many bytes we should've allocated
11756 // and how many bytes a callee cleanup function will pop. If we port
11757 // inalloca to more targets, we'll have to add custom inalloca handling
11758 // in the various CC lowering callbacks.
11759 Flags.setByVal();
11760 }
11761 Align MemAlign;
11762 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11763 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11764 Flags.setByValSize(FrameSize);
11765
11766 // info is not there but there are cases it cannot get right.
11767 if (auto MA = Args[i].Alignment)
11768 MemAlign = *MA;
11769 else
11770 MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11771 } else if (auto MA = Args[i].Alignment) {
11772 MemAlign = *MA;
11773 } else {
11774 MemAlign = OriginalAlignment;
11775 }
11776 Flags.setMemAlign(MemAlign);
11777 if (Args[i].IsNest)
11778 Flags.setNest();
11779 if (NeedsRegBlock)
11780 Flags.setInConsecutiveRegs();
11781
11782 MVT PartVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11783 unsigned NumParts =
11784 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11785 SmallVector<SDValue, 4> Parts(NumParts);
11787
11788 if (Args[i].IsSExt)
11790 else if (Args[i].IsZExt)
11792
11793 // Conservatively only handle 'returned' on non-vectors that can be lowered,
11794 // for now.
11795 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11797 assert((CLI.RetTy == Args[i].Ty ||
11798 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11800 Args[i].Ty->getPointerAddressSpace())) &&
11801 RetVTs.size() == NumValues && "unexpected use of 'returned'");
11802 // Before passing 'returned' to the target lowering code, ensure that
11803 // either the register MVT and the actual EVT are the same size or that
11804 // the return value and argument are extended in the same way; in these
11805 // cases it's safe to pass the argument register value unchanged as the
11806 // return register value (although it's at the target's option whether
11807 // to do so)
11808 // TODO: allow code generation to take advantage of partially preserved
11809 // registers rather than clobbering the entire register when the
11810 // parameter extension method is not compatible with the return
11811 // extension method
11812 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11813 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11814 CLI.RetZExt == Args[i].IsZExt))
11815 Flags.setReturned();
11816 }
11817
11818 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11819 CLI.CallConv, ExtendKind);
11820
11821 for (unsigned j = 0; j != NumParts; ++j) {
11822 // if it isn't first piece, alignment must be 1
11823 // For scalable vectors the scalable part is currently handled
11824 // by individual targets, so we just use the known minimum size here.
11825 ISD::OutputArg MyFlags(
11826 Flags, Parts[j].getValueType().getSimpleVT(), VT, OrigArgTy, i,
11827 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11828 if (NumParts > 1 && j == 0)
11829 MyFlags.Flags.setSplit();
11830 else if (j != 0) {
11831 MyFlags.Flags.setOrigAlign(Align(1));
11832 if (j == NumParts - 1)
11833 MyFlags.Flags.setSplitEnd();
11834 }
11835
11836 CLI.Outs.push_back(MyFlags);
11837 CLI.OutVals.push_back(Parts[j]);
11838 }
11839
11840 if (NeedsRegBlock && Value == NumValues - 1)
11841 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11842 }
11843 }
11844
11846 CLI.Chain = LowerCall(CLI, InVals);
11847
11848 // Update CLI.InVals to use outside of this function.
11849 CLI.InVals = InVals;
11850
11851 // Verify that the target's LowerCall behaved as expected.
11852 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11853 "LowerCall didn't return a valid chain!");
11854 assert((!CLI.IsTailCall || InVals.empty()) &&
11855 "LowerCall emitted a return value for a tail call!");
11856 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11857 "LowerCall didn't emit the correct number of values!");
11858
11859 // For a tail call, the return value is merely live-out and there aren't
11860 // any nodes in the DAG representing it. Return a special value to
11861 // indicate that a tail call has been emitted and no more Instructions
11862 // should be processed in the current block.
11863 if (CLI.IsTailCall) {
11864 CLI.DAG.setRoot(CLI.Chain);
11865 return std::make_pair(SDValue(), SDValue());
11866 }
11867
11868#ifndef NDEBUG
11869 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11870 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11871 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11872 "LowerCall emitted a value with the wrong type!");
11873 }
11874#endif
11875
11876 SmallVector<SDValue, 4> ReturnValues;
11877 if (!CanLowerReturn) {
11878 // The instruction result is the result of loading from the
11879 // hidden sret parameter.
11880 MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11881
11882 unsigned NumValues = RetVTs.size();
11883 ReturnValues.resize(NumValues);
11884 SmallVector<SDValue, 4> Chains(NumValues);
11885
11886 // An aggregate return value cannot wrap around the address space, so
11887 // offsets to its parts don't wrap either.
11889 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11890 for (unsigned i = 0; i < NumValues; ++i) {
11892 DemoteStackSlot, CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11894 SDValue L = CLI.DAG.getLoad(
11895 RetVTs[i], CLI.DL, CLI.Chain, Add,
11897 DemoteStackIdx, Offsets[i]),
11898 HiddenSRetAlign);
11899 ReturnValues[i] = L;
11900 Chains[i] = L.getValue(1);
11901 }
11902
11903 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11904 } else {
11905 // Collect the legal value parts into potentially illegal values
11906 // that correspond to the original function's return values.
11907 std::optional<ISD::NodeType> AssertOp;
11908 if (CLI.RetSExt)
11909 AssertOp = ISD::AssertSext;
11910 else if (CLI.RetZExt)
11911 AssertOp = ISD::AssertZext;
11912 unsigned CurReg = 0;
11913 for (EVT VT : RetVTs) {
11914 MVT RegisterVT = getRegisterTypeForCallingConv(Context, CLI.CallConv, VT);
11915 unsigned NumRegs =
11916 getNumRegistersForCallingConv(Context, CLI.CallConv, VT);
11917
11918 ReturnValues.push_back(getCopyFromParts(
11919 CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11920 CLI.Chain, CLI.CallConv, AssertOp));
11921 CurReg += NumRegs;
11922 }
11923
11924 // For a function returning void, there is no return value. We can't create
11925 // such a node, so we just return a null return value in that case. In
11926 // that case, nothing will actually look at the value.
11927 if (ReturnValues.empty())
11928 return std::make_pair(SDValue(), CLI.Chain);
11929 }
11930
11931 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11932 CLI.DAG.getVTList(RetVTs), ReturnValues);
11933 return std::make_pair(Res, CLI.Chain);
11934}
11935
11936/// Places new result values for the node in Results (their number
11937/// and types must exactly match those of the original return values of
11938/// the node), or leaves Results empty, which indicates that the node is not
11939/// to be custom lowered after all.
11942 SelectionDAG &DAG) const {
11943 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11944
11945 if (!Res.getNode())
11946 return;
11947
11948 // If the original node has one result, take the return value from
11949 // LowerOperation as is. It might not be result number 0.
11950 if (N->getNumValues() == 1) {
11951 Results.push_back(Res);
11952 return;
11953 }
11954
11955 // If the original node has multiple results, then the return node should
11956 // have the same number of results.
11957 assert((N->getNumValues() == Res->getNumValues()) &&
11958 "Lowering returned the wrong number of results!");
11959
11960 // Places new result values base on N result number.
11961 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11962 Results.push_back(Res.getValue(I));
11963}
11964
11966 llvm_unreachable("LowerOperation not implemented for this target!");
11967}
11968
11970 Register Reg,
11971 ISD::NodeType ExtendType) {
11973 assert((Op.getOpcode() != ISD::CopyFromReg ||
11974 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11975 "Copy from a reg to the same reg!");
11976 assert(!Reg.isPhysical() && "Is a physreg");
11977
11978 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11979 // If this is an InlineAsm we have to match the registers required, not the
11980 // notional registers required by the type.
11981
11982 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11983 std::nullopt); // This is not an ABI copy.
11984 SDValue Chain = DAG.getEntryNode();
11985
11986 if (ExtendType == ISD::ANY_EXTEND) {
11987 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11988 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11989 ExtendType = PreferredExtendIt->second;
11990 }
11991 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11992 PendingExports.push_back(Chain);
11993}
11994
11996
11997/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11998/// entry block, return true. This includes arguments used by switches, since
11999/// the switch may expand into multiple basic blocks.
12000static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
12001 // With FastISel active, we may be splitting blocks, so force creation
12002 // of virtual registers for all non-dead arguments.
12003 if (FastISel)
12004 return A->use_empty();
12005
12006 const BasicBlock &Entry = A->getParent()->front();
12007 for (const User *U : A->users())
12008 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
12009 return false; // Use not in entry block.
12010
12011 return true;
12012}
12013
12015 DenseMap<const Argument *,
12016 std::pair<const AllocaInst *, const StoreInst *>>;
12017
12018/// Scan the entry block of the function in FuncInfo for arguments that look
12019/// like copies into a local alloca. Record any copied arguments in
12020/// ArgCopyElisionCandidates.
12021static void
12023 FunctionLoweringInfo *FuncInfo,
12024 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
12025 // Record the state of every static alloca used in the entry block. Argument
12026 // allocas are all used in the entry block, so we need approximately as many
12027 // entries as we have arguments.
12028 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
12030 unsigned NumArgs = FuncInfo->Fn->arg_size();
12031 StaticAllocas.reserve(NumArgs * 2);
12032
12033 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
12034 if (!V)
12035 return nullptr;
12036 V = V->stripPointerCasts();
12037 const auto *AI = dyn_cast<AllocaInst>(V);
12038 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
12039 return nullptr;
12040 auto Iter = StaticAllocas.insert({AI, Unknown});
12041 return &Iter.first->second;
12042 };
12043
12044 // Look for stores of arguments to static allocas. Look through bitcasts and
12045 // GEPs to handle type coercions, as long as the alloca is fully initialized
12046 // by the store. Any non-store use of an alloca escapes it and any subsequent
12047 // unanalyzed store might write it.
12048 // FIXME: Handle structs initialized with multiple stores.
12049 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
12050 // Look for stores, and handle non-store uses conservatively.
12051 const auto *SI = dyn_cast<StoreInst>(&I);
12052 if (!SI) {
12053 // We will look through cast uses, so ignore them completely.
12054 if (I.isCast())
12055 continue;
12056 // Ignore pseudo op intrinsics, they don't escape or store to allocas.
12058 continue;
12059 // This is an unknown instruction. Assume it escapes or writes to all
12060 // static alloca operands.
12061 for (const Use &U : I.operands()) {
12062 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
12063 *Info = StaticAllocaInfo::Clobbered;
12064 }
12065 continue;
12066 }
12067
12068 // If the stored value is a static alloca, mark it as escaped.
12069 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
12070 *Info = StaticAllocaInfo::Clobbered;
12071
12072 // Check if the destination is a static alloca.
12073 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
12074 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
12075 if (!Info)
12076 continue;
12077 const AllocaInst *AI = cast<AllocaInst>(Dst);
12078
12079 // Skip allocas that have been initialized or clobbered.
12080 if (*Info != StaticAllocaInfo::Unknown)
12081 continue;
12082
12083 // Check if the stored value is an argument, and that this store fully
12084 // initializes the alloca.
12085 // If the argument type has padding bits we can't directly forward a pointer
12086 // as the upper bits may contain garbage.
12087 // Don't elide copies from the same argument twice.
12088 const Value *Val = SI->getValueOperand()->stripPointerCasts();
12089 const auto *Arg = dyn_cast<Argument>(Val);
12090 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
12091 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
12092 Arg->getType()->isEmptyTy() || !AllocaSize ||
12093 DL.getTypeStoreSize(Arg->getType()) != *AllocaSize ||
12094 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
12095 ArgCopyElisionCandidates.count(Arg)) {
12096 *Info = StaticAllocaInfo::Clobbered;
12097 continue;
12098 }
12099
12100 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
12101 << '\n');
12102
12103 // Mark this alloca and store for argument copy elision.
12104 *Info = StaticAllocaInfo::Elidable;
12105 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
12106
12107 // Stop scanning if we've seen all arguments. This will happen early in -O0
12108 // builds, which is useful, because -O0 builds have large entry blocks and
12109 // many allocas.
12110 if (ArgCopyElisionCandidates.size() == NumArgs)
12111 break;
12112 }
12113}
12114
12115/// Try to elide argument copies from memory into a local alloca. Succeeds if
12116/// ArgVal is a load from a suitable fixed stack object.
12119 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
12120 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
12121 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
12122 ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
12123 // Check if this is a load from a fixed stack object.
12124 auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
12125 if (!LNode)
12126 return;
12127 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
12128 if (!FINode)
12129 return;
12130
12131 // Check that the fixed stack object is the right size and alignment.
12132 // Look at the alignment that the user wrote on the alloca instead of looking
12133 // at the stack object.
12134 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
12135 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
12136 const AllocaInst *AI = ArgCopyIter->second.first;
12137 int FixedIndex = FINode->getIndex();
12138 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
12139 int OldIndex = AllocaIndex;
12140 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
12141 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
12142 LLVM_DEBUG(
12143 dbgs() << " argument copy elision failed due to bad fixed stack "
12144 "object size\n");
12145 return;
12146 }
12147 Align RequiredAlignment = AI->getAlign();
12148 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
12149 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
12150 "greater than stack argument alignment ("
12151 << DebugStr(RequiredAlignment) << " vs "
12152 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
12153 return;
12154 }
12155
12156 // Perform the elision. Delete the old stack object and replace its only use
12157 // in the variable info map. Mark the stack object as mutable and aliased.
12158 LLVM_DEBUG({
12159 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
12160 << " Replacing frame index " << OldIndex << " with " << FixedIndex
12161 << '\n';
12162 });
12163 MFI.RemoveStackObject(OldIndex);
12164 MFI.setIsImmutableObjectIndex(FixedIndex, false);
12165 MFI.setIsAliasedObjectIndex(FixedIndex, true);
12166 AllocaIndex = FixedIndex;
12167 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
12168 for (SDValue ArgVal : ArgVals)
12169 Chains.push_back(ArgVal.getValue(1));
12170
12171 // Avoid emitting code for the store implementing the copy.
12172 const StoreInst *SI = ArgCopyIter->second.second;
12173 ElidedArgCopyInstrs.insert(SI);
12174
12175 // Check for uses of the argument again so that we can avoid exporting ArgVal
12176 // if it is't used by anything other than the store.
12177 for (const Value *U : Arg.users()) {
12178 if (U != SI) {
12179 ArgHasUses = true;
12180 break;
12181 }
12182 }
12183}
12184
12185void SelectionDAGISel::LowerArguments(const Function &F, bool FastISel) {
12186 SelectionDAG &DAG = SDB->DAG;
12187 SDLoc dl = SDB->getCurSDLoc();
12188 const DataLayout &DL = DAG.getDataLayout();
12190
12191 // In Naked functions we aren't going to save any registers.
12192 if (F.hasFnAttribute(Attribute::Naked))
12193 return;
12194
12195 if (!FuncInfo->CanLowerReturn) {
12196 // Put in an sret pointer parameter before all the other parameters.
12197 MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12198
12199 ISD::ArgFlagsTy Flags;
12200 Flags.setSRet();
12201 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
12202 ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, F.getReturnType(), true,
12204 Ins.push_back(RetArg);
12205 }
12206
12207 // Look for stores of arguments to static allocas. Mark such arguments with a
12208 // flag to ask the target to give us the memory location of that argument if
12209 // available.
12210 ArgCopyElisionMapTy ArgCopyElisionCandidates;
12212 ArgCopyElisionCandidates);
12213
12214 // Set up the incoming argument description vector.
12215 for (const Argument &Arg : F.args()) {
12216 unsigned ArgNo = Arg.getArgNo();
12218 ComputeValueTypes(DAG.getDataLayout(), Arg.getType(), Types);
12219 bool isArgValueUsed = !Arg.use_empty();
12220 Type *FinalType = Arg.getType();
12221 if (Arg.hasAttribute(Attribute::ByVal))
12222 FinalType = Arg.getParamByValType();
12223 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
12224 FinalType, F.getCallingConv(), F.isVarArg(), DL);
12225 for (unsigned Value = 0, NumValues = Types.size(); Value != NumValues;
12226 ++Value) {
12227 Type *ArgTy = Types[Value];
12228 EVT VT = TLI->getValueType(DL, ArgTy);
12229 ISD::ArgFlagsTy Flags;
12230
12231 if (ArgTy->isPointerTy()) {
12232 Flags.setPointer();
12233 Flags.setPointerAddrSpace(cast<PointerType>(ArgTy)->getAddressSpace());
12234 }
12235 if (Arg.hasAttribute(Attribute::ZExt))
12236 Flags.setZExt();
12237 if (Arg.hasAttribute(Attribute::SExt))
12238 Flags.setSExt();
12239 if (Arg.hasAttribute(Attribute::InReg)) {
12240 // If we are using vectorcall calling convention, a structure that is
12241 // passed InReg - is surely an HVA
12242 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
12243 isa<StructType>(Arg.getType())) {
12244 // The first value of a structure is marked
12245 if (0 == Value)
12246 Flags.setHvaStart();
12247 Flags.setHva();
12248 }
12249 // Set InReg Flag
12250 Flags.setInReg();
12251 }
12252 if (Arg.hasAttribute(Attribute::StructRet))
12253 Flags.setSRet();
12254 if (Arg.hasAttribute(Attribute::SwiftSelf))
12255 Flags.setSwiftSelf();
12256 if (Arg.hasAttribute(Attribute::SwiftAsync))
12257 Flags.setSwiftAsync();
12258 if (Arg.hasAttribute(Attribute::SwiftError))
12259 Flags.setSwiftError();
12260 if (Arg.hasAttribute(Attribute::ByVal))
12261 Flags.setByVal();
12262 if (Arg.hasAttribute(Attribute::ByRef))
12263 Flags.setByRef();
12264 if (Arg.hasAttribute(Attribute::InAlloca)) {
12265 Flags.setInAlloca();
12266 // Set the byval flag for CCAssignFn callbacks that don't know about
12267 // inalloca. This way we can know how many bytes we should've allocated
12268 // and how many bytes a callee cleanup function will pop. If we port
12269 // inalloca to more targets, we'll have to add custom inalloca handling
12270 // in the various CC lowering callbacks.
12271 Flags.setByVal();
12272 }
12273 if (Arg.hasAttribute(Attribute::Preallocated)) {
12274 Flags.setPreallocated();
12275 // Set the byval flag for CCAssignFn callbacks that don't know about
12276 // preallocated. This way we can know how many bytes we should've
12277 // allocated and how many bytes a callee cleanup function will pop. If
12278 // we port preallocated to more targets, we'll have to add custom
12279 // preallocated handling in the various CC lowering callbacks.
12280 Flags.setByVal();
12281 }
12282
12283 // Certain targets (such as MIPS), may have a different ABI alignment
12284 // for a type depending on the context. Give the target a chance to
12285 // specify the alignment it wants.
12286 const Align OriginalAlignment(
12287 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
12288 Flags.setOrigAlign(OriginalAlignment);
12289
12290 Align MemAlign;
12291 Type *ArgMemTy = nullptr;
12292 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
12293 Flags.isByRef()) {
12294 if (!ArgMemTy)
12295 ArgMemTy = Arg.getPointeeInMemoryValueType();
12296
12297 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
12298
12299 // For in-memory arguments, size and alignment should be passed from FE.
12300 // BE will guess if this info is not there but there are cases it cannot
12301 // get right.
12302 if (auto ParamAlign = Arg.getParamStackAlign())
12303 MemAlign = *ParamAlign;
12304 else if ((ParamAlign = Arg.getParamAlign()))
12305 MemAlign = *ParamAlign;
12306 else
12307 MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
12308 if (Flags.isByRef())
12309 Flags.setByRefSize(MemSize);
12310 else
12311 Flags.setByValSize(MemSize);
12312 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
12313 MemAlign = *ParamAlign;
12314 } else {
12315 MemAlign = OriginalAlignment;
12316 }
12317 Flags.setMemAlign(MemAlign);
12318
12319 if (Arg.hasAttribute(Attribute::Nest))
12320 Flags.setNest();
12321 if (NeedsRegBlock)
12322 Flags.setInConsecutiveRegs();
12323 if (ArgCopyElisionCandidates.count(&Arg))
12324 Flags.setCopyElisionCandidate();
12325 if (Arg.hasAttribute(Attribute::Returned))
12326 Flags.setReturned();
12327
12328 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
12329 *CurDAG->getContext(), F.getCallingConv(), VT);
12330 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
12331 *CurDAG->getContext(), F.getCallingConv(), VT);
12332 for (unsigned i = 0; i != NumRegs; ++i) {
12333 // For scalable vectors, use the minimum size; individual targets
12334 // are responsible for handling scalable vector arguments and
12335 // return values.
12336 ISD::InputArg MyFlags(
12337 Flags, RegisterVT, VT, ArgTy, isArgValueUsed, ArgNo,
12338 i * RegisterVT.getStoreSize().getKnownMinValue());
12339 if (NumRegs > 1 && i == 0)
12340 MyFlags.Flags.setSplit();
12341 // if it isn't first piece, alignment must be 1
12342 else if (i > 0) {
12343 MyFlags.Flags.setOrigAlign(Align(1));
12344 if (i == NumRegs - 1)
12345 MyFlags.Flags.setSplitEnd();
12346 }
12347 Ins.push_back(MyFlags);
12348 }
12349 if (NeedsRegBlock && Value == NumValues - 1)
12350 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
12351 }
12352 }
12353
12354 // Call the target to set up the argument values.
12356 SDValue NewRoot = TLI->LowerFormalArguments(
12357 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
12358
12359 // Verify that the target's LowerFormalArguments behaved as expected.
12360 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
12361 "LowerFormalArguments didn't return a valid chain!");
12362 assert(InVals.size() == Ins.size() &&
12363 "LowerFormalArguments didn't emit the correct number of values!");
12364 assert(all_of(InVals, [](SDValue InVal) { return InVal.getNode(); }) &&
12365 "LowerFormalArguments emitted a null value!");
12366
12367 // Update the DAG with the new chain value resulting from argument lowering.
12368 DAG.setRoot(NewRoot);
12369
12370 // Set up the argument values.
12371 unsigned i = 0;
12372 if (!FuncInfo->CanLowerReturn) {
12373 // Create a virtual register for the sret pointer, and put in a copy
12374 // from the sret argument into it.
12375 MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
12376 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
12377 std::optional<ISD::NodeType> AssertOp;
12378 SDValue ArgValue =
12379 getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
12380 F.getCallingConv(), AssertOp);
12381
12382 MachineFunction& MF = SDB->DAG.getMachineFunction();
12383 MachineRegisterInfo& RegInfo = MF.getRegInfo();
12384 Register SRetReg =
12385 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
12386 FuncInfo->DemoteRegister = SRetReg;
12387 NewRoot =
12388 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
12389 DAG.setRoot(NewRoot);
12390
12391 // i indexes lowered arguments. Bump it past the hidden sret argument.
12392 ++i;
12393 }
12394
12396 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
12397 for (const Argument &Arg : F.args()) {
12398 SmallVector<SDValue, 4> ArgValues;
12399 SmallVector<EVT, 4> ValueVTs;
12400 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
12401 unsigned NumValues = ValueVTs.size();
12402 if (NumValues == 0)
12403 continue;
12404
12405 bool ArgHasUses = !Arg.use_empty();
12406
12407 // Elide the copying store if the target loaded this argument from a
12408 // suitable fixed stack object.
12409 if (Ins[i].Flags.isCopyElisionCandidate()) {
12410 unsigned NumParts = 0;
12411 for (EVT VT : ValueVTs)
12412 NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
12413 F.getCallingConv(), VT);
12414
12415 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
12416 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
12417 ArrayRef(&InVals[i], NumParts), ArgHasUses);
12418 }
12419
12420 // If this argument is unused then remember its value. It is used to generate
12421 // debugging information.
12422 bool isSwiftErrorArg =
12423 TLI->supportSwiftError() &&
12424 Arg.hasAttribute(Attribute::SwiftError);
12425 if (!ArgHasUses && !isSwiftErrorArg) {
12426 SDB->setUnusedArgValue(&Arg, InVals[i]);
12427
12428 // Also remember any frame index for use in FastISel.
12429 if (FrameIndexSDNode *FI =
12431 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12432 }
12433
12434 for (unsigned Val = 0; Val != NumValues; ++Val) {
12435 EVT VT = ValueVTs[Val];
12436 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
12437 F.getCallingConv(), VT);
12438 unsigned NumParts = TLI->getNumRegistersForCallingConv(
12439 *CurDAG->getContext(), F.getCallingConv(), VT);
12440
12441 // Even an apparent 'unused' swifterror argument needs to be returned. So
12442 // we do generate a copy for it that can be used on return from the
12443 // function.
12444 if (ArgHasUses || isSwiftErrorArg) {
12445 std::optional<ISD::NodeType> AssertOp;
12446 if (Arg.hasAttribute(Attribute::SExt))
12447 AssertOp = ISD::AssertSext;
12448 else if (Arg.hasAttribute(Attribute::ZExt))
12449 AssertOp = ISD::AssertZext;
12450
12451 SDValue OutVal =
12452 getCopyFromParts(DAG, dl, &InVals[i], NumParts, PartVT, VT, nullptr,
12453 NewRoot, F.getCallingConv(), AssertOp);
12454
12455 FPClassTest NoFPClass = Arg.getNoFPClass();
12456 if (NoFPClass != fcNone) {
12457 SDValue SDNoFPClass = DAG.getTargetConstant(
12458 static_cast<uint64_t>(NoFPClass), dl, MVT::i32);
12459 OutVal = DAG.getNode(ISD::AssertNoFPClass, dl, OutVal.getValueType(),
12460 OutVal, SDNoFPClass);
12461 }
12462 ArgValues.push_back(OutVal);
12463 }
12464
12465 i += NumParts;
12466 }
12467
12468 // We don't need to do anything else for unused arguments.
12469 if (ArgValues.empty())
12470 continue;
12471
12472 // Note down frame index.
12473 if (FrameIndexSDNode *FI =
12474 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
12475 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12476
12477 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
12478 SDB->getCurSDLoc());
12479
12480 SDB->setValue(&Arg, Res);
12481 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
12482 // We want to associate the argument with the frame index, among
12483 // involved operands, that correspond to the lowest address. The
12484 // getCopyFromParts function, called earlier, is swapping the order of
12485 // the operands to BUILD_PAIR depending on endianness. The result of
12486 // that swapping is that the least significant bits of the argument will
12487 // be in the first operand of the BUILD_PAIR node, and the most
12488 // significant bits will be in the second operand.
12489 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
12490 if (LoadSDNode *LNode =
12491 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
12492 if (FrameIndexSDNode *FI =
12493 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
12494 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
12495 }
12496
12497 // Analyses past this point are naive and don't expect an assertion.
12498 if (Res.getOpcode() == ISD::AssertZext)
12499 Res = Res.getOperand(0);
12500
12501 // Update the SwiftErrorVRegDefMap.
12502 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
12503 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12504 if (Reg.isVirtual())
12505 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
12506 Reg);
12507 }
12508
12509 // If this argument is live outside of the entry block, insert a copy from
12510 // wherever we got it to the vreg that other BB's will reference it as.
12511 if (Res.getOpcode() == ISD::CopyFromReg) {
12512 // If we can, though, try to skip creating an unnecessary vreg.
12513 // FIXME: This isn't very clean... it would be nice to make this more
12514 // general.
12515 Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
12516 if (Reg.isVirtual()) {
12517 FuncInfo->ValueMap[&Arg] = Reg;
12518 continue;
12519 }
12520 }
12521 if (!isOnlyUsedInEntryBlock(&Arg, FastISel)) {
12522 FuncInfo->InitializeRegForValue(&Arg);
12523 SDB->CopyToExportRegsIfNeeded(&Arg);
12524 }
12525 }
12526
12527 if (!Chains.empty()) {
12528 Chains.push_back(NewRoot);
12529 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
12530 }
12531
12532 DAG.setRoot(NewRoot);
12533
12534 assert(i == InVals.size() && "Argument register count mismatch!");
12535
12536 // If any argument copy elisions occurred and we have debug info, update the
12537 // stale frame indices used in the dbg.declare variable info table.
12538 if (!ArgCopyElisionFrameIndexMap.empty()) {
12539 for (MachineFunction::VariableDbgInfo &VI :
12540 MF->getInStackSlotVariableDbgInfo()) {
12541 auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
12542 if (I != ArgCopyElisionFrameIndexMap.end())
12543 VI.updateStackSlot(I->second);
12544 }
12545 }
12546
12547 // Finally, if the target has anything special to do, allow it to do so.
12549}
12550
12551/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
12552/// ensure constants are generated when needed. Remember the virtual registers
12553/// that need to be added to the Machine PHI nodes as input. We cannot just
12554/// directly add them, because expansion might result in multiple MBB's for one
12555/// BB. As such, the start of the BB might correspond to a different MBB than
12556/// the end.
12557void
12558SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
12559 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12560
12561 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
12562
12563 // Check PHI nodes in successors that expect a value to be available from this
12564 // block.
12565 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
12566 if (!isa<PHINode>(SuccBB->begin())) continue;
12567 MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
12568
12569 // If this terminator has multiple identical successors (common for
12570 // switches), only handle each succ once.
12571 if (!SuccsHandled.insert(SuccMBB).second)
12572 continue;
12573
12575
12576 // At this point we know that there is a 1-1 correspondence between LLVM PHI
12577 // nodes and Machine PHI nodes, but the incoming operands have not been
12578 // emitted yet.
12579 for (const PHINode &PN : SuccBB->phis()) {
12580 // Ignore dead phi's.
12581 if (PN.use_empty())
12582 continue;
12583
12584 // Skip empty types
12585 if (PN.getType()->isEmptyTy())
12586 continue;
12587
12588 Register Reg;
12589 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
12590
12591 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12592 Register &RegOut = ConstantsOut[C];
12593 if (!RegOut) {
12594 RegOut = FuncInfo.CreateRegs(PHIOp);
12595 // We need to zero/sign extend ConstantInt phi operands to match
12596 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12597 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12598 if (auto *CI = dyn_cast<ConstantInt>(C))
12599 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12601 CopyValueToVirtualRegister(C, RegOut, ExtendType);
12602 }
12603 Reg = RegOut;
12604 } else {
12605 auto I = FuncInfo.ValueMap.find(PHIOp);
12606 if (I != FuncInfo.ValueMap.end())
12607 Reg = I->second;
12608 else {
12609 assert(isa<AllocaInst>(PHIOp) &&
12610 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12611 "Didn't codegen value into a register!??");
12612 Reg = FuncInfo.CreateRegs(PHIOp);
12614 }
12615 }
12616
12617 // Remember that this register needs to added to the machine PHI node as
12618 // the input for this MBB.
12619 SmallVector<EVT, 4> ValueVTs;
12620 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12621 for (EVT VT : ValueVTs) {
12622 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12623 for (unsigned i = 0; i != NumRegisters; ++i)
12624 FuncInfo.PHINodesToUpdate.emplace_back(&*MBBI++, Reg + i);
12625 Reg += NumRegisters;
12626 }
12627 }
12628 }
12629
12630 ConstantsOut.clear();
12631}
12632
12633MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12635 if (++I == FuncInfo.MF->end())
12636 return nullptr;
12637 return &*I;
12638}
12639
12640/// During lowering new call nodes can be created (such as memset, etc.).
12641/// Those will become new roots of the current DAG, but complications arise
12642/// when they are tail calls. In such cases, the call lowering will update
12643/// the root, but the builder still needs to know that a tail call has been
12644/// lowered in order to avoid generating an additional return.
12645void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12646 // If the node is null, we do have a tail call.
12647 if (MaybeTC.getNode() != nullptr)
12648 DAG.setRoot(MaybeTC);
12649 else
12650 HasTailCall = true;
12651}
12652
12653void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12654 MachineBasicBlock *SwitchMBB,
12655 MachineBasicBlock *DefaultMBB) {
12656 MachineFunction *CurMF = FuncInfo.MF;
12657 MachineBasicBlock *NextMBB = nullptr;
12659 if (++BBI != FuncInfo.MF->end())
12660 NextMBB = &*BBI;
12661
12662 unsigned Size = W.LastCluster - W.FirstCluster + 1;
12663
12664 BranchProbabilityInfo *BPI = FuncInfo.BPI;
12665
12666 if (Size == 2 && W.MBB == SwitchMBB) {
12667 // If any two of the cases has the same destination, and if one value
12668 // is the same as the other, but has one bit unset that the other has set,
12669 // use bit manipulation to do two compares at once. For example:
12670 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12671 // TODO: This could be extended to merge any 2 cases in switches with 3
12672 // cases.
12673 // TODO: Handle cases where W.CaseBB != SwitchBB.
12674 CaseCluster &Small = *W.FirstCluster;
12675 CaseCluster &Big = *W.LastCluster;
12676
12677 if (Small.Low == Small.High && Big.Low == Big.High &&
12678 Small.MBB == Big.MBB) {
12679 const APInt &SmallValue = Small.Low->getValue();
12680 const APInt &BigValue = Big.Low->getValue();
12681
12682 // Check that there is only one bit different.
12683 APInt CommonBit = BigValue ^ SmallValue;
12684 if (CommonBit.isPowerOf2()) {
12685 SDValue CondLHS = getValue(Cond);
12686 EVT VT = CondLHS.getValueType();
12687 SDLoc DL = getCurSDLoc();
12688
12689 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12690 DAG.getConstant(CommonBit, DL, VT));
12691 SDValue Cond = DAG.getSetCC(
12692 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12693 ISD::SETEQ);
12694
12695 // Update successor info.
12696 // Both Small and Big will jump to Small.BB, so we sum up the
12697 // probabilities.
12698 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12699 if (BPI)
12700 addSuccessorWithProb(
12701 SwitchMBB, DefaultMBB,
12702 // The default destination is the first successor in IR.
12703 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12704 else
12705 addSuccessorWithProb(SwitchMBB, DefaultMBB);
12706
12707 // Insert the true branch.
12708 SDValue BrCond =
12709 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12710 DAG.getBasicBlock(Small.MBB));
12711 // Insert the false branch.
12712 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12713 DAG.getBasicBlock(DefaultMBB));
12714
12715 DAG.setRoot(BrCond);
12716 return;
12717 }
12718 }
12719 }
12720
12721 if (TM.getOptLevel() != CodeGenOptLevel::None) {
12722 // Here, we order cases by probability so the most likely case will be
12723 // checked first. However, two clusters can have the same probability in
12724 // which case their relative ordering is non-deterministic. So we use Low
12725 // as a tie-breaker as clusters are guaranteed to never overlap.
12726 llvm::sort(W.FirstCluster, W.LastCluster + 1,
12727 [](const CaseCluster &a, const CaseCluster &b) {
12728 return a.Prob != b.Prob ?
12729 a.Prob > b.Prob :
12730 a.Low->getValue().slt(b.Low->getValue());
12731 });
12732
12733 // Rearrange the case blocks so that the last one falls through if possible
12734 // without changing the order of probabilities.
12735 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12736 --I;
12737 if (I->Prob > W.LastCluster->Prob)
12738 break;
12739 if (I->Kind == CC_Range && I->MBB == NextMBB) {
12740 std::swap(*I, *W.LastCluster);
12741 break;
12742 }
12743 }
12744 }
12745
12746 // Compute total probability.
12747 BranchProbability DefaultProb = W.DefaultProb;
12748 BranchProbability UnhandledProbs = DefaultProb;
12749 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12750 UnhandledProbs += I->Prob;
12751
12752 MachineBasicBlock *CurMBB = W.MBB;
12753 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12754 bool FallthroughUnreachable = false;
12755 MachineBasicBlock *Fallthrough;
12756 if (I == W.LastCluster) {
12757 // For the last cluster, fall through to the default destination.
12758 Fallthrough = DefaultMBB;
12759 FallthroughUnreachable =
12761 } else {
12762 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12763 CurMF->insert(BBI, Fallthrough);
12764 // Put Cond in a virtual register to make it available from the new blocks.
12766 }
12767 UnhandledProbs -= I->Prob;
12768
12769 switch (I->Kind) {
12770 case CC_JumpTable: {
12771 // FIXME: Optimize away range check based on pivot comparisons.
12772 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12773 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12774
12775 // The jump block hasn't been inserted yet; insert it here.
12776 MachineBasicBlock *JumpMBB = JT->MBB;
12777 CurMF->insert(BBI, JumpMBB);
12778
12779 auto JumpProb = I->Prob;
12780 auto FallthroughProb = UnhandledProbs;
12781
12782 // If the default statement is a target of the jump table, we evenly
12783 // distribute the default probability to successors of CurMBB. Also
12784 // update the probability on the edge from JumpMBB to Fallthrough.
12785 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12786 SE = JumpMBB->succ_end();
12787 SI != SE; ++SI) {
12788 if (*SI == DefaultMBB) {
12789 JumpProb += DefaultProb / 2;
12790 FallthroughProb -= DefaultProb / 2;
12791 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12792 JumpMBB->normalizeSuccProbs();
12793 break;
12794 }
12795 }
12796
12797 // If the default clause is unreachable, propagate that knowledge into
12798 // JTH->FallthroughUnreachable which will use it to suppress the range
12799 // check.
12800 //
12801 // However, don't do this if we're doing branch target enforcement
12802 // (e.g. Arm BTI, or the cf-protection-branch module flag used by
12803 // RISC-V Zicfilp and X86 IBT), because a table branch _without_ a
12804 // range check can be a tempting JOP gadget - out-of-bounds inputs
12805 // that are impossible in correct execution become possible again if
12806 // an attacker can influence the control flow. So if an attacker
12807 // doesn't already have a branch target enforcement bypass available,
12808 // we don't want them to be able to get one out of this table branch.
12809 if (FallthroughUnreachable) {
12810 Function &CurFunc = CurMF->getFunction();
12811 bool HasCFBranch = false;
12812 if (auto *CFBranch = mdconst::extract_or_null<ConstantInt>(
12813 CurFunc.getParent()->getModuleFlag("cf-protection-branch")))
12814 HasCFBranch = !CFBranch->isZero();
12815 if (!HasCFBranch &&
12816 !CurFunc.hasFnAttribute("branch-target-enforcement"))
12817 JTH->FallthroughUnreachable = true;
12818 }
12819
12820 if (!JTH->FallthroughUnreachable)
12821 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12822 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12823 CurMBB->normalizeSuccProbs();
12824
12825 // The jump table header will be inserted in our current block, do the
12826 // range check, and fall through to our fallthrough block.
12827 JTH->HeaderBB = CurMBB;
12828 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12829
12830 // If we're in the right place, emit the jump table header right now.
12831 if (CurMBB == SwitchMBB) {
12832 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12833 JTH->Emitted = true;
12834 }
12835 break;
12836 }
12837 case CC_BitTests: {
12838 // FIXME: Optimize away range check based on pivot comparisons.
12839 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12840
12841 // The bit test blocks haven't been inserted yet; insert them here.
12842 for (BitTestCase &BTC : BTB->Cases)
12843 CurMF->insert(BBI, BTC.ThisBB);
12844
12845 // Fill in fields of the BitTestBlock.
12846 BTB->Parent = CurMBB;
12847 BTB->Default = Fallthrough;
12848
12849 BTB->DefaultProb = UnhandledProbs;
12850 // If the cases in bit test don't form a contiguous range, we evenly
12851 // distribute the probability on the edge to Fallthrough to two
12852 // successors of CurMBB.
12853 if (!BTB->ContiguousRange) {
12854 BTB->Prob += DefaultProb / 2;
12855 BTB->DefaultProb -= DefaultProb / 2;
12856 }
12857
12858 if (FallthroughUnreachable)
12859 BTB->FallthroughUnreachable = true;
12860
12861 // If we're in the right place, emit the bit test header right now.
12862 if (CurMBB == SwitchMBB) {
12863 visitBitTestHeader(*BTB, SwitchMBB);
12864 BTB->Emitted = true;
12865 }
12866 break;
12867 }
12868 case CC_Range: {
12869 const Value *RHS, *LHS, *MHS;
12871 if (I->Low == I->High) {
12872 // Check Cond == I->Low.
12873 CC = ISD::SETEQ;
12874 LHS = Cond;
12875 RHS=I->Low;
12876 MHS = nullptr;
12877 } else {
12878 // Check I->Low <= Cond <= I->High.
12879 CC = ISD::SETLE;
12880 LHS = I->Low;
12881 MHS = Cond;
12882 RHS = I->High;
12883 }
12884
12885 // If Fallthrough is unreachable, fold away the comparison.
12886 if (FallthroughUnreachable)
12887 CC = ISD::SETTRUE;
12888
12889 // The false probability is the sum of all unhandled cases.
12890 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12891 getCurSDLoc(), I->Prob, UnhandledProbs);
12892
12893 if (CurMBB == SwitchMBB)
12894 visitSwitchCase(CB, SwitchMBB);
12895 else
12896 SL->SwitchCases.push_back(CB);
12897
12898 break;
12899 }
12900 }
12901 CurMBB = Fallthrough;
12902 }
12903}
12904
12905void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12906 const SwitchWorkListItem &W,
12907 Value *Cond,
12908 MachineBasicBlock *SwitchMBB) {
12909 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12910 "Clusters not sorted?");
12911 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12912
12913 auto [LastLeft, FirstRight, LeftProb, RightProb] =
12914 SL->computeSplitWorkItemInfo(W);
12915
12916 // Use the first element on the right as pivot since we will make less-than
12917 // comparisons against it.
12918 CaseClusterIt PivotCluster = FirstRight;
12919 assert(PivotCluster > W.FirstCluster);
12920 assert(PivotCluster <= W.LastCluster);
12921
12922 CaseClusterIt FirstLeft = W.FirstCluster;
12923 CaseClusterIt LastRight = W.LastCluster;
12924
12925 const ConstantInt *Pivot = PivotCluster->Low;
12926
12927 // New blocks will be inserted immediately after the current one.
12929 ++BBI;
12930
12931 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12932 // we can branch to its destination directly if it's squeezed exactly in
12933 // between the known lower bound and Pivot - 1.
12934 MachineBasicBlock *LeftMBB;
12935 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12936 FirstLeft->Low == W.GE &&
12937 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12938 LeftMBB = FirstLeft->MBB;
12939 } else {
12940 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12941 FuncInfo.MF->insert(BBI, LeftMBB);
12942 WorkList.push_back(
12943 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12944 // Put Cond in a virtual register to make it available from the new blocks.
12946 }
12947
12948 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12949 // single cluster, RHS.Low == Pivot, and we can branch to its destination
12950 // directly if RHS.High equals the current upper bound.
12951 MachineBasicBlock *RightMBB;
12952 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12953 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12954 RightMBB = FirstRight->MBB;
12955 } else {
12956 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12957 FuncInfo.MF->insert(BBI, RightMBB);
12958 WorkList.push_back(
12959 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12960 // Put Cond in a virtual register to make it available from the new blocks.
12962 }
12963
12964 // Create the CaseBlock record that will be used to lower the branch.
12965 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12966 getCurSDLoc(), LeftProb, RightProb);
12967
12968 if (W.MBB == SwitchMBB)
12969 visitSwitchCase(CB, SwitchMBB);
12970 else
12971 SL->SwitchCases.push_back(CB);
12972}
12973
12974// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12975// from the swith statement.
12977 BranchProbability PeeledCaseProb) {
12978 if (PeeledCaseProb == BranchProbability::getOne())
12980 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12981
12982 uint32_t Numerator = CaseProb.getNumerator();
12983 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12984 return BranchProbability(Numerator, std::max(Numerator, Denominator));
12985}
12986
12987// Try to peel the top probability case if it exceeds the threshold.
12988// Return current MachineBasicBlock for the switch statement if the peeling
12989// does not occur.
12990// If the peeling is performed, return the newly created MachineBasicBlock
12991// for the peeled switch statement. Also update Clusters to remove the peeled
12992// case. PeeledCaseProb is the BranchProbability for the peeled case.
12993MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12994 const SwitchInst &SI, CaseClusterVector &Clusters,
12995 BranchProbability &PeeledCaseProb) {
12996 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12997 // Don't perform if there is only one cluster or optimizing for size.
12998 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12999 TM.getOptLevel() == CodeGenOptLevel::None ||
13000 SwitchMBB->getParent()->getFunction().hasMinSize())
13001 return SwitchMBB;
13002
13003 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
13004 unsigned PeeledCaseIndex = 0;
13005 bool SwitchPeeled = false;
13006 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
13007 CaseCluster &CC = Clusters[Index];
13008 if (CC.Prob < TopCaseProb)
13009 continue;
13010 TopCaseProb = CC.Prob;
13011 PeeledCaseIndex = Index;
13012 SwitchPeeled = true;
13013 }
13014 if (!SwitchPeeled)
13015 return SwitchMBB;
13016
13017 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
13018 << TopCaseProb << "\n");
13019
13020 // Record the MBB for the peeled switch statement.
13021 MachineFunction::iterator BBI(SwitchMBB);
13022 ++BBI;
13023 MachineBasicBlock *PeeledSwitchMBB =
13024 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
13025 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
13026
13027 ExportFromCurrentBlock(SI.getCondition());
13028 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
13029 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
13030 nullptr, nullptr, TopCaseProb.getCompl()};
13031 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
13032
13033 Clusters.erase(PeeledCaseIt);
13034 for (CaseCluster &CC : Clusters) {
13035 LLVM_DEBUG(
13036 dbgs() << "Scale the probablity for one cluster, before scaling: "
13037 << CC.Prob << "\n");
13038 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
13039 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
13040 }
13041 PeeledCaseProb = TopCaseProb;
13042 return PeeledSwitchMBB;
13043}
13044
13045void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
13046 // Extract cases from the switch.
13047 BranchProbabilityInfo *BPI = FuncInfo.BPI;
13048 CaseClusterVector Clusters;
13049 Clusters.reserve(SI.getNumCases());
13050 for (auto I : SI.cases()) {
13051 MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
13052 const ConstantInt *CaseVal = I.getCaseValue();
13053 BranchProbability Prob =
13054 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
13055 : BranchProbability(1, SI.getNumCases() + 1);
13056 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
13057 }
13058
13059 MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
13060
13061 // Cluster adjacent cases with the same destination. We do this at all
13062 // optimization levels because it's cheap to do and will make codegen faster
13063 // if there are many clusters.
13064 sortAndRangeify(Clusters);
13065
13066 // The branch probablity of the peeled case.
13067 BranchProbability PeeledCaseProb = BranchProbability::getZero();
13068 MachineBasicBlock *PeeledSwitchMBB =
13069 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
13070
13071 // If there is only the default destination, jump there directly.
13072 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
13073 if (Clusters.empty()) {
13074 assert(PeeledSwitchMBB == SwitchMBB);
13075 SwitchMBB->addSuccessor(DefaultMBB);
13076 if (DefaultMBB != NextBlock(SwitchMBB)) {
13077 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
13078 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
13079 }
13080 return;
13081 }
13082
13083 SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
13084 DAG.getBFI());
13085 SL->findBitTestClusters(Clusters, &SI);
13086
13087 LLVM_DEBUG({
13088 dbgs() << "Case clusters: ";
13089 for (const CaseCluster &C : Clusters) {
13090 if (C.Kind == CC_JumpTable)
13091 dbgs() << "JT:";
13092 if (C.Kind == CC_BitTests)
13093 dbgs() << "BT:";
13094
13095 C.Low->getValue().print(dbgs(), true);
13096 if (C.Low != C.High) {
13097 dbgs() << '-';
13098 C.High->getValue().print(dbgs(), true);
13099 }
13100 dbgs() << ' ';
13101 }
13102 dbgs() << '\n';
13103 });
13104
13105 assert(!Clusters.empty());
13106 SwitchWorkList WorkList;
13107 CaseClusterIt First = Clusters.begin();
13108 CaseClusterIt Last = Clusters.end() - 1;
13109 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
13110 // Scale the branchprobability for DefaultMBB if the peel occurs and
13111 // DefaultMBB is not replaced.
13112 if (PeeledCaseProb != BranchProbability::getZero() &&
13113 DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
13114 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
13115 WorkList.push_back(
13116 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
13117
13118 while (!WorkList.empty()) {
13119 SwitchWorkListItem W = WorkList.pop_back_val();
13120 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
13121
13122 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
13123 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
13124 // For optimized builds, lower large range as a balanced binary tree.
13125 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
13126 continue;
13127 }
13128
13129 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
13130 }
13131}
13132
13133void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
13134 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13135 auto DL = getCurSDLoc();
13136 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13137 setValue(&I, DAG.getStepVector(DL, ResultVT));
13138}
13139
13140void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
13141 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13142 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13143
13144 SDLoc DL = getCurSDLoc();
13145 SDValue V = getValue(I.getOperand(0));
13146 assert(VT == V.getValueType() && "Malformed vector.reverse!");
13147
13148 if (VT.isScalableVector()) {
13149 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
13150 return;
13151 }
13152
13153 // Use VECTOR_SHUFFLE for the fixed-length vector
13154 // to maintain existing behavior.
13155 SmallVector<int, 8> Mask;
13156 unsigned NumElts = VT.getVectorMinNumElements();
13157 for (unsigned i = 0; i != NumElts; ++i)
13158 Mask.push_back(NumElts - 1 - i);
13159
13160 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
13161}
13162
13163void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I,
13164 unsigned Factor) {
13165 auto DL = getCurSDLoc();
13166 SDValue InVec = getValue(I.getOperand(0));
13167
13168 SmallVector<EVT, 4> ValueVTs;
13169 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13170 ValueVTs);
13171
13172 EVT OutVT = ValueVTs[0];
13173 unsigned OutNumElts = OutVT.getVectorMinNumElements();
13174
13175 SmallVector<SDValue, 4> SubVecs(Factor);
13176 for (unsigned i = 0; i != Factor; ++i) {
13177 assert(ValueVTs[i] == OutVT && "Expected VTs to be the same");
13178 SubVecs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
13179 DAG.getVectorIdxConstant(OutNumElts * i, DL));
13180 }
13181
13182 SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
13183 DAG.getVTList(ValueVTs), SubVecs);
13184 setValue(&I, Res);
13185}
13186
13187void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I,
13188 unsigned Factor) {
13189 auto DL = getCurSDLoc();
13190 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13191 EVT InVT = getValue(I.getOperand(0)).getValueType();
13192 EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13193
13194 SmallVector<SDValue, 8> InVecs(Factor);
13195 for (unsigned i = 0; i < Factor; ++i) {
13196 InVecs[i] = getValue(I.getOperand(i));
13197 assert(InVecs[i].getValueType() == InVecs[0].getValueType() &&
13198 "Expected VTs to be the same");
13199 }
13200
13201 SmallVector<EVT, 8> ValueVTs(Factor, InVT);
13202 SDValue Res =
13203 DAG.getNode(ISD::VECTOR_INTERLEAVE, DL, DAG.getVTList(ValueVTs), InVecs);
13204
13206 for (unsigned i = 0; i < Factor; ++i)
13207 Results[i] = Res.getValue(i);
13208
13209 Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Results);
13210 setValue(&I, Res);
13211}
13212
13213void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
13214 SmallVector<EVT, 4> ValueVTs;
13215 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
13216 ValueVTs);
13217 unsigned NumValues = ValueVTs.size();
13218 if (NumValues == 0) return;
13219
13221 SDValue Op = getValue(I.getOperand(0));
13222
13223 for (unsigned i = 0; i != NumValues; ++i)
13224 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
13225 SDValue(Op.getNode(), Op.getResNo() + i));
13226
13228 DAG.getVTList(ValueVTs), Values));
13229}
13230
13231void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
13232 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13233 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
13234
13235 SDLoc DL = getCurSDLoc();
13236 SDValue V1 = getValue(I.getOperand(0));
13237 SDValue V2 = getValue(I.getOperand(1));
13238 const bool IsLeft = I.getIntrinsicID() == Intrinsic::vector_splice_left;
13239
13240 // VECTOR_SHUFFLE doesn't support a scalable or non-constant mask.
13241 if (VT.isScalableVector() || !isa<ConstantInt>(I.getOperand(2))) {
13242 SDValue Offset = DAG.getZExtOrTrunc(
13243 getValue(I.getOperand(2)), DL, TLI.getVectorIdxTy(DAG.getDataLayout()));
13244 setValue(&I, DAG.getNode(IsLeft ? ISD::VECTOR_SPLICE_LEFT
13246 DL, VT, V1, V2, Offset));
13247 return;
13248 }
13249 uint64_t Imm = cast<ConstantInt>(I.getOperand(2))->getZExtValue();
13250
13251 unsigned NumElts = VT.getVectorNumElements();
13252
13253 uint64_t Idx = IsLeft ? Imm : NumElts - Imm;
13254
13255 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
13256 SmallVector<int, 8> Mask;
13257 for (unsigned i = 0; i < NumElts; ++i)
13258 Mask.push_back(Idx + i);
13259 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
13260}
13261
13262// Consider the following MIR after SelectionDAG, which produces output in
13263// phyregs in the first case or virtregs in the second case.
13264//
13265// INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
13266// %5:gr32 = COPY $ebx
13267// %6:gr32 = COPY $edx
13268// %1:gr32 = COPY %6:gr32
13269// %0:gr32 = COPY %5:gr32
13270//
13271// INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
13272// %1:gr32 = COPY %6:gr32
13273// %0:gr32 = COPY %5:gr32
13274//
13275// Given %0, we'd like to return $ebx in the first case and %5 in the second.
13276// Given %1, we'd like to return $edx in the first case and %6 in the second.
13277//
13278// If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
13279// to a single virtreg (such as %0). The remaining outputs monotonically
13280// increase in virtreg number from there. If a callbr has no outputs, then it
13281// should not have a corresponding callbr landingpad; in fact, the callbr
13282// landingpad would not even be able to refer to such a callbr.
13284 MachineInstr *MI = MRI.def_begin(Reg)->getParent();
13285 // There is definitely at least one copy.
13286 assert(MI->getOpcode() == TargetOpcode::COPY &&
13287 "start of copy chain MUST be COPY");
13288 Reg = MI->getOperand(1).getReg();
13289
13290 // If the copied register in the first copy must be virtual.
13291 assert(Reg.isVirtual() && "expected COPY of virtual register");
13292 MI = MRI.def_begin(Reg)->getParent();
13293
13294 // There may be an optional second copy.
13295 if (MI->getOpcode() == TargetOpcode::COPY) {
13296 assert(Reg.isVirtual() && "expected COPY of virtual register");
13297 Reg = MI->getOperand(1).getReg();
13298 assert(Reg.isPhysical() && "expected COPY of physical register");
13299 } else {
13300 // The start of the chain must be an INLINEASM_BR.
13301 assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
13302 "end of copy chain MUST be INLINEASM_BR");
13303 }
13304
13305 return Reg;
13306}
13307
13308// We must do this walk rather than the simpler
13309// setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
13310// otherwise we will end up with copies of virtregs only valid along direct
13311// edges.
13312void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
13313 SmallVector<EVT, 8> ResultVTs;
13314 SmallVector<SDValue, 8> ResultValues;
13315 const auto *CBR =
13316 cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
13317
13318 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13319 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
13320 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
13321
13322 Register InitialDef = FuncInfo.ValueMap[CBR];
13323 SDValue Chain = DAG.getRoot();
13324
13325 // Re-parse the asm constraints string.
13326 TargetLowering::AsmOperandInfoVector TargetConstraints =
13327 TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
13328 for (auto &T : TargetConstraints) {
13329 SDISelAsmOperandInfo OpInfo(T);
13330 if (OpInfo.Type != InlineAsm::isOutput)
13331 continue;
13332
13333 // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
13334 // individual constraint.
13335 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
13336
13337 switch (OpInfo.ConstraintType) {
13340 // Fill in OpInfo.AssignedRegs.Regs.
13341 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
13342
13343 // getRegistersForValue may produce 1 to many registers based on whether
13344 // the OpInfo.ConstraintVT is legal on the target or not.
13345 for (Register &Reg : OpInfo.AssignedRegs.Regs) {
13346 Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
13347 if (OriginalDef.isPhysical())
13348 FuncInfo.MBB->addLiveIn(OriginalDef);
13349 // Update the assigned registers to use the original defs.
13350 Reg = OriginalDef;
13351 }
13352
13353 SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
13354 DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
13355 ResultValues.push_back(V);
13356 ResultVTs.push_back(OpInfo.ConstraintVT);
13357 break;
13358 }
13360 SDValue Flag;
13361 SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
13362 OpInfo, DAG);
13363 ++InitialDef;
13364 ResultValues.push_back(V);
13365 ResultVTs.push_back(OpInfo.ConstraintVT);
13366 break;
13367 }
13368 default:
13369 break;
13370 }
13371 }
13372 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
13373 DAG.getVTList(ResultVTs), ResultValues);
13374 setValue(&I, V);
13375}
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)
uint64_t uint64_t
uint64_t Imm
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
Function Alias Analysis Results
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI)
Returns an AttributeList representing the attributes applied to the return value of the given call.
Definition FastISel.cpp:947
#define Check(C,...)
static Value * getCondition(Instruction *I)
Hexagon Common GEP
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static void getRegistersForValue(MachineFunction &MF, MachineIRBuilder &MIRBuilder, GISelAsmOperandInfo &OpInfo, GISelAsmOperandInfo &RefOpInfo)
Assign virtual/physical registers for the specified register operand.
static void computeConstraintToUse(const TargetLowering *TLI, TargetLowering::AsmOperandInfo &OpInfo)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static const Function * getCalledFunction(const Value *V)
This file provides utility analysis objects describing memory locations.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
#define T
#define T1
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t High
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file contains some templates that are useful if you are working with the STL at all.
static bool hasOnlySelectUsers(const Value *Cond)
static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, SDValue &Chain)
Create a LOAD_STACK_GUARD node, and let it carry the target specific global variable if there exists ...
static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, SDValue &Scale, SelectionDAGBuilder *SDB, const BasicBlock *CurBB, uint64_t ElemSize)
static void failForInvalidBundles(const CallBase &I, StringRef Name, ArrayRef< uint32_t > AllowedBundles)
static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, const SDLoc &DL, SmallVectorImpl< SDValue > &Ops, SelectionDAGBuilder &Builder)
Add a stack map intrinsic call's live variable operands to a stackmap or patchpoint target node's ope...
static const unsigned MaxParallelChains
static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
visitPow - Lower a pow intrinsic.
static const CallBase * FindPreallocatedCall(const Value *PreallocatedSetup)
Given a @llvm.call.preallocated.setup, return the corresponding preallocated call.
static cl::opt< unsigned > SwitchPeelThreshold("switch-peel-threshold", cl::Hidden, cl::init(66), cl::desc("Set the case probability threshold for peeling the case from a " "switch statement. A value greater than 100 will void this " "optimization"))
static cl::opt< bool > InsertAssertAlign("insert-assert-align", cl::init(true), cl::desc("Insert the experimental `assertalign` node."), cl::ReallyHidden)
static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin)
static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG, DILocalVariable *Variable, DebugLoc DL, unsigned Order, SmallVectorImpl< Value * > &Values, DIExpression *Expression)
static bool prepareDAGLevelOperands(ConstraintDecisionInfo &Info, const CallBase &Call, SelectionDAGBuilder &Builder, const TargetLowering &TLI, SelectionDAG &DAG)
Prepare DAG-level operands.
static unsigned findMatchingInlineAsmOperand(unsigned OperandNo, const std::vector< SDValue > &AsmNodeOperands)
static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, SDISelAsmOperandInfo &MatchingOpInfo, SelectionDAG &DAG)
Make sure that the output operand OpInfo and its corresponding input operand MatchingOpInfo have comp...
static void findUnwindDestinations(FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, BranchProbability Prob, SmallVectorImpl< std::pair< MachineBasicBlock *, BranchProbability > > &UnwindDests)
When an invoke or a cleanupret unwinds to the next EH pad, there are many places it could ultimately ...
static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic)
static BranchProbability scaleCaseProbality(BranchProbability CaseProb, BranchProbability PeeledCaseProb)
static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandExp2 - Lower an exp2 intrinsic.
static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue Scale, SelectionDAG &DAG, const TargetLowering &TLI)
static const GlobalValue * getGlobalAddressDbgOperand(const Value *V, DIExpression *&Expr, unsigned OpIdx, const MachineFunction &MF)
If V is the address of a describable global, possibly displaced by a constant, return the global and ...
static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, const SDLoc &dl)
getF32Constant - Get 32-bit floating point constant.
static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val, const SDLoc &DL, EVT PartVT)
static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog10 - Lower a log10 intrinsic.
DenseMap< const Argument *, std::pair< const AllocaInst *, const StoreInst * > > ArgCopyElisionMapTy
static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, const Value *V, std::optional< CallingConv::ID > CallConv)
getCopyToPartsVector - Create a series of nodes that contain the specified value split into legal par...
static void getUnderlyingArgRegs(SmallVectorImpl< std::pair< Register, TypeSize > > &Regs, const SDValue &N)
static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, const Value *V, std::optional< CallingConv::ID > CallConv=std::nullopt, ISD::NodeType ExtendKind=ISD::ANY_EXTEND)
getCopyToParts - Create a series of nodes that contain the specified value split into legal parts.
static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, SelectionDAGBuilder &Builder)
static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog2 - Lower a log2 intrinsic.
static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, SDISelAsmOperandInfo &OpInfo, SelectionDAG &DAG)
Get a direct memory input to behave well as an indirect operand.
static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel)
isOnlyUsedInEntryBlock - If the specified argument is only used in the entry block,...
static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, const Twine &ErrMsg)
static bool collectInstructionDeps(SmallMapVector< const Instruction *, bool, 8 > *Deps, const Value *V, SmallMapVector< const Instruction *, bool, 8 > *Necessary=nullptr, unsigned Depth=0)
static void findArgumentCopyElisionCandidates(const DataLayout &DL, FunctionLoweringInfo *FuncInfo, ArgCopyElisionMapTy &ArgCopyElisionCandidates)
Scan the entry block of the function in FuncInfo for arguments that look like copies into a local all...
static bool isFunction(SDValue Op)
static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, const SDLoc &dl)
GetExponent - Get the exponent:
static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg)
static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, SelectionDAG &DAG)
ExpandPowI - Expand a llvm.powi intrinsic.
static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandLog - Lower a log intrinsic.
static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, SDValue InChain, std::optional< CallingConv::ID > CC=std::nullopt, std::optional< ISD::NodeType > AssertOp=std::nullopt)
getCopyFromParts - Create a value that contains the specified legal parts combined into the value the...
static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, SelectionDAG &DAG)
static bool determineConstraints(ConstraintDecisionInfo &Info, TargetLowering::AsmOperandInfoVector &TargetConstraints, const CallBase &Call, SelectionDAGBuilder &Builder, const TargetLowering &TLI, const TargetMachine &TM, SelectionDAG &DAG, const BasicBlock *EHPadBB)
DetermineConstraints - Find the constraints to use for inline asm operands.
static bool constructOperandInfo(ConstraintDecisionInfo &Info, TargetLowering::AsmOperandInfoVector &TargetConstraints, SelectionDAGBuilder &Builder, const TargetLowering &TLI, ExtraFlags &ExtraInfo)
Construct operand info objects.
static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl)
GetSignificand - Get the significand and build it into a floating-point number with exponent of 1:
static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, const TargetLowering &TLI, SDNodeFlags Flags)
expandExp - Lower an exp intrinsic.
static const MDNode * getRangeMetadata(const Instruction &I)
static cl::opt< unsigned, true > LimitFPPrecision("limit-float-precision", cl::desc("Generate low-precision inline sequences " "for some float libcalls"), cl::location(LimitFloatPrecision), cl::Hidden, cl::init(0))
static void tryToElideArgumentCopy(FunctionLoweringInfo &FuncInfo, SmallVectorImpl< SDValue > &Chains, DenseMap< int, int > &ArgCopyElisionFrameIndexMap, SmallPtrSetImpl< const Instruction * > &ElidedArgCopyInstrs, ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, ArrayRef< SDValue > ArgVals, bool &ArgHasUses)
Try to elide argument copies from memory into a local alloca.
static unsigned LimitFloatPrecision
LimitFloatPrecision - Generate low-precision inline sequences for some float libcalls (6,...
static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V, SDValue InChain, std::optional< CallingConv::ID > CC)
getCopyFromPartsVector - Create a value that contains the specified legal parts combined into the val...
static bool InBlock(const Value *V, const BasicBlock *BB)
static FPClassTest getNoFPClass(const Instruction &I)
static LLVM_ATTRIBUTE_ALWAYS_INLINE MVT::SimpleValueType getSimpleVT(const uint8_t *MatcherTable, size_t &MatcherIndex)
getSimpleVT - Decode a value in MatcherTable, if it's a VBR encoded value, use GetVBR to decode it.
This file defines the SmallPtrSet class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
TTI::PartialReductionExtendKind ExtendKind
uint16_t RegSizeInBits(const MCRegisterInfo &MRI, MCRegister RegNo)
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static LLVM_ABI Semantics SemanticsToEnum(const llvm::fltSemantics &Sem)
Definition APFloat.cpp:184
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:6165
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Check if an argument has a given attribute.
Definition Function.cpp:332
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
Definition Argument.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
A cache of @llvm.assume calls within a function.
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
This class represents a no-op cast from one type to another.
The address of a basic block.
Definition Constants.h:1088
Analysis providing branch probability information.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
static constexpr BranchProbability getOne()
static uint32_t getDenominator()
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
LLVM_ABI uint64_t scale(uint64_t Num) const
Scale a large integer.
BranchProbability getCompl() const
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
CallingConv::ID getCallingConv() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
LLVM_ABI bool isTailCall() const
Tests if this call site is marked as a tail call.
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Conditional Branch instruction.
Class for constant bytes.
Definition Constants.h:281
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1316
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A signed pointer, in the ptrauth sense.
Definition Constants.h:1223
uint64_t getZExtValue() const
Constant Vector Declarations.
Definition Constants.h:674
This is an important base class in LLVM.
Definition Constant.h:44
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
static LLVM_ABI const DIExpression * convertToUndefExpression(const DIExpression *Expr)
Removes all elements from Expr that do not apply to an undef debug value, which includes every operat...
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
Base class for variables.
LLVM_ABI std::optional< uint64_t > getSizeInBits() const
Determines the size of the variable's type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isBigEndian() const
Definition DataLayout.h:218
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
A debug info location.
Definition DebugLoc.h:126
LLVM_ABI DILocation * getInlinedAt() const
Definition DebugLoc.cpp:58
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:679
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:721
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Diagnostic information for inline asm reporting.
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
This instruction compares its operands according to the predicate given to the constructor.
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
bool allowReassoc() const
Flag queries.
Definition FMF.h:64
An instruction for ordering other memory operations.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
This class represents a freeze function that returns random concrete value if an operand is either a ...
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
BranchProbabilityInfo * BPI
MachineBasicBlock * getMBB(const BasicBlock *BB) const
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
const LiveOutInfo * GetLiveOutRegInfo(Register Reg)
GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the register is a PHI destinat...
MachineBasicBlock * MBB
MBB - The current block.
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
Data structure describing the variable locations in a function.
const BasicBlock & getEntryBlock() const
Definition Function.h: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:743
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
Constant * getPersonalityFn() const
Get the personality function associated with this function.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
size_t arg_size() const
Definition Function.h:886
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Garbage collection metadata for a single function.
Definition GCMetadata.h:80
bool hasNoUnsignedSignedWrap() const
bool hasNoUnsignedWrap() const
bool isInBounds() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void setMemConstraint(ConstraintCode C)
setMemConstraint - Augment an existing flag with the constraint code for a memory constraint.
Definition InlineAsm.h:414
This instruction inserts a struct field of array element value into an aggregate value.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
A helper class to return the specified delimiter string after the first invocation of operator String...
An instruction for reading from memory.
static LocationSize precise(uint64_t Value)
static constexpr LocationSize beforeOrAfterPointer()
Any location before or after the base pointer (but still within the underlying object).
static LocationSize upperBound(uint64_t Value)
bool usesPerInvokeEHLabels(ExceptionHandling EH) const
Returns true if the exception tables reference the per-invoke EH labels emitted around invokes.
Definition MCAsmInfo.h:679
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
LLVM_ABI MCSymbol * getOrCreateFrameAllocSymbol(const Twine &FuncName, unsigned Idx)
Gets a symbol that will be defined to the final stack offset of a local variable after codegen.
const MCAsmInfo & getAsmInfo() const
Definition MCContext.h:411
unsigned getID() const
getID() - Return the register class ID number.
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.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void setIsEHContTarget(bool V=true)
Indicates if this is a target of Windows EH Continuation Guard.
void setIsEHFuncletEntry(bool V=true)
Indicates if this is the entry block of an EH funclet.
MachineInstrBundleIterator< MachineInstr > iterator
void setIsEHScopeEntry(bool V=true)
Indicates if this is the entry block of an EH scope, i.e., the block that that used to have a catchpa...
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setIsImmutableObjectIndex(int ObjectIdx, bool IsImmutable)
Marks the immutability of an object.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
bool hasOpaqueSPAdjustment() const
Returns true if the function contains opaque dynamic stack adjustments.
int getStackProtectorIndex() const
Return the index for the stack protector object.
void setIsAliasedObjectIndex(int ObjectIdx, bool IsAliased)
Set "maybe pointed to by an LLVM IR value" for an object.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
void setFunctionContextIndex(int I)
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
bool useDebugInstrRef() const
Returns true if the function's variable locations are tracked with instruction referencing.
void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site)
Map the begin label for a call site.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD)
Record annotations associated with a particular label.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
void setHasEHContTarget(bool V)
void addInvoke(MachineBasicBlock *LandingPad, MCSymbol *BeginLabel, MCSymbol *EndLabel)
Provide the begin and end labels of an invoke style call and associate it with a try landing pad bloc...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
Representation of each machine instruction.
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MONonTemporal
The memory access is non-temporal.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
An SDNode that represents everything that will be needed to construct a MachineInstr.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h: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
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Resume the propagation of an exception.
Return a value (possibly void), from a function.
Holds the information from a dbg_label node through SDISel.
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
static SDDbgOperand fromGlobalAddr(const GlobalValue *GV)
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getOpcode() const
SelectionDAGBuilder - This is the common target-independent lowering implementation that is parameter...
SDValue getValue(const Value *V)
getValue - Return an SDValue for the given Value.
bool shouldKeepJumpConditionsTogether(const FunctionLoweringInfo &FuncInfo, const CondBrInst &I, Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, TargetLoweringBase::CondMergingParams Params) const
DenseMap< const Constant *, Register > ConstantsOut
void addDanglingDebugInfo(SmallVectorImpl< Value * > &Values, DILocalVariable *Var, DIExpression *Expr, bool IsVariadic, DebugLoc DL, unsigned Order)
Register a dbg_value which relies on a Value which we have not yet seen.
void visitDbgInfo(const Instruction &I)
void clearDanglingDebugInfo()
Clear the dangling debug information map.
SDValue lowerStartEH(SDValue Chain, const BasicBlock *EHPadBB, MCSymbol *&BeginLabel)
void LowerCallTo(const CallBase &CB, SDValue Callee, bool IsTailCall, bool IsMustTailCall, const BasicBlock *EHPadBB=nullptr, const TargetLowering::PtrAuthInfo *PAI=nullptr)
void clear()
Clear out the current SelectionDAG and the associated state and prepare this SelectionDAGBuilder obje...
void visitBitTestHeader(SwitchCG::BitTestBlock &B, MachineBasicBlock *SwitchBB)
visitBitTestHeader - This function emits necessary code to produce value suitable for "bit tests"
void LowerStatepoint(const GCStatepointInst &I, const BasicBlock *EHPadBB=nullptr)
std::unique_ptr< SDAGSwitchLowering > SL
SDValue lowerRangeToAssertZExt(SelectionDAG &DAG, const Instruction &I, SDValue Op)
bool HasTailCall
This is set to true if a call in the current block has been translated as a tail call.
bool ShouldEmitAsBranches(const std::vector< SwitchCG::CaseBlock > &Cases)
If the set of cases should be emitted as a series of branches, return true.
void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
EmitBranchForMergedCondition - Helper method for FindMergedConditions.
void LowerDeoptimizeCall(const CallInst *CI)
void LowerCallSiteWithDeoptBundle(const CallBase *Call, SDValue Callee, const BasicBlock *EHPadBB)
SwiftErrorValueTracking & SwiftError
Information about the swifterror values used throughout the function.
SDValue getNonRegisterValue(const Value *V)
getNonRegisterValue - Return an SDValue for the given Value, but don't look in FuncInfo....
const TargetTransformInfo * TTI
DenseMap< MachineBasicBlock *, SmallVector< unsigned, 4 > > LPadToCallSiteMap
Map a landing pad to the call site indexes.
SDValue lowerNoFPClassToAssertNoFPClass(SelectionDAG &DAG, const Instruction &I, SDValue Op)
void handleDebugDeclare(Value *Address, DILocalVariable *Variable, DIExpression *Expression, DebugLoc DL)
StatepointLoweringState StatepointLowering
State used while lowering a statepoint sequence (gc_statepoint, gc_relocate, and gc_result).
void setValueToPoison(const Value *V, const SDLoc &dl)
void visitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB, BranchProbability BranchProbToNext, Register Reg, SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB)
visitBitTestCase - this function produces one "bit test"
bool canTailCall(const CallBase &CB) const
void populateCallLoweringInfo(TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, AttributeSet RetAttrs, bool IsPatchPoint)
Populate a CallLowerinInfo (into CLI) based on the properties of the call being lowered.
void CopyValueToVirtualRegister(const Value *V, Register Reg, ISD::NodeType ExtendType=ISD::ANY_EXTEND)
void salvageUnresolvedDbgValue(const Value *V, DanglingDebugInfo &DDI)
For the given dangling debuginfo record, perform last-ditch efforts to resolve the debuginfo to somet...
SmallVector< SDValue, 8 > PendingLoads
Loads are not emitted to the program immediately.
GCFunctionInfo * GFI
Garbage collection metadata for the function.
void init(GCFunctionInfo *gfi, BatchAAResults *BatchAA, AssumptionCache *AC, const TargetLibraryInfo *li, const TargetTransformInfo &TTI)
SDValue getRoot()
Similar to getMemoryRoot, but also flushes PendingConstrainedFP(Strict) items.
void ExportFromCurrentBlock(const Value *V)
ExportFromCurrentBlock - If this condition isn't known to be exported from the current basic block,...
void resolveOrClearDbgInfo()
Evict any dangling debug information, attempting to salvage it first.
std::pair< SDValue, SDValue > lowerInvokable(TargetLowering::CallLoweringInfo &CLI, const BasicBlock *EHPadBB=nullptr)
SDValue getMemoryRoot()
Return the current virtual root of the Selection DAG, flushing any PendingLoad items.
void resolveDanglingDebugInfo(const Value *V, SDValue Val)
If we saw an earlier dbg_value referring to V, generate the debug data structures now that we've seen...
void visit(const Instruction &I)
void dropDanglingDebugInfo(const DILocalVariable *Variable, const DIExpression *Expr)
If we have dangling debug info that describes Variable, or an overlapping part of variable considerin...
SDValue getCopyFromRegs(const Value *V, Type *Ty)
If there was virtual register allocated for the value V emit CopyFromReg of the specified type Ty.
void CopyToExportRegsIfNeeded(const Value *V)
CopyToExportRegsIfNeeded - If the given value has virtual registers created for it,...
void handleKillDebugValue(DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order)
Create a record for a kill location debug intrinsic.
void visitJumpTable(SwitchCG::JumpTable &JT)
visitJumpTable - Emit JumpTable node in the current MBB
SDValue getFPOperationRoot(fp::ExceptionBehavior EB)
Return the current virtual root of the Selection DAG, flushing PendingConstrainedFP or PendingConstra...
void visitJumpTableHeader(SwitchCG::JumpTable &JT, SwitchCG::JumpTableHeader &JTH, MachineBasicBlock *SwitchBB)
visitJumpTableHeader - This function emits necessary code to produce index in the JumpTable from swit...
void LowerCallSiteWithPtrAuthBundle(const CallBase &CB, const BasicBlock *EHPadBB)
static const unsigned LowestSDNodeOrder
Lowest valid SDNodeOrder.
FunctionLoweringInfo & FuncInfo
Information about the function as a whole.
void setValue(const Value *V, SDValue NewN)
void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, Instruction::BinaryOps Opc, BranchProbability TProb, BranchProbability FProb, bool InvertCond)
const TargetLibraryInfo * LibInfo
bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB)
void visitSPDescriptorParent(StackProtectorDescriptor &SPD, MachineBasicBlock *ParentBB)
Codegen a new tail for a stack protector check ParentMBB which has had its tail spliced into a stack ...
bool handleDebugValue(ArrayRef< const Value * > Values, DILocalVariable *Var, DIExpression *Expr, DebugLoc DbgLoc, unsigned Order, bool IsVariadic)
For a given list of Values, attempt to create and record a SDDbgValue in the SelectionDAG.
SDValue getControlRoot()
Similar to getRoot, but instead of flushing all the PendingLoad items, flush all the PendingExports (...
void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last)
When an MBB was split during scheduling, update the references that need to refer to the last resulti...
SDValue getValueImpl(const Value *V)
getValueImpl - Helper function for getValue and getNonRegisterValue.
void visitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB)
visitSwitchCase - Emits the necessary code to represent a single node in the binary search tree resul...
void visitSPDescriptorFailure(StackProtectorDescriptor &SPD)
Codegen the failure basic block for a stack protector check.
std::unique_ptr< FunctionLoweringInfo > FuncInfo
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
const TargetLowering * TLI
MachineRegisterInfo * RegInfo
std::unique_ptr< SwiftErrorValueTracking > SwiftError
virtual void emitFunctionEntryCode()
std::unique_ptr< SelectionDAGBuilder > SDB
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemccpy(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI) const
Emit target-specific code that performs a memccpy, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrnlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, SDValue MaxLength, MachinePointerInfo SrcPtrInfo) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrlen(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Src, const CallInst *CI) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrstr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, const CallInst *CI) const
Emit target-specific code that performs a strstr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemchr(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Src, SDValue Char, SDValue Length, MachinePointerInfo SrcPtrInfo) const
Emit target-specific code that performs a memchr, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, MachinePointerInfo Op1PtrInfo, MachinePointerInfo Op2PtrInfo, const CallInst *CI) const
Emit target-specific code that performs a strcmp, in cases where that is faster than a libcall.
virtual std::pair< SDValue, SDValue > EmitTargetCodeForMemcmp(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Op1, SDValue Op2, SDValue Op3, const CallInst *CI) const
Emit target-specific code that performs a memcmp/bcmp, in cases where that is faster than a libcall.
virtual SDValue EmitTargetCodeForSetTag(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Addr, SDValue Size, MachinePointerInfo DstPtrInfo, bool ZeroData) const
virtual std::pair< SDValue, SDValue > EmitTargetCodeForStrcpy(SelectionDAG &DAG, const SDLoc &DL, SDValue Chain, SDValue Dest, SDValue Src, MachinePointerInfo DestPtrInfo, MachinePointerInfo SrcPtrInfo, bool isStpcpy, const CallInst *CI) const
Emit target-specific code that performs a strcpy or stpcpy, in cases where that is faster than a libc...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVMContext * getContext() const
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void swap(SmallVectorImpl &RHS)
void resize(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
MachineBasicBlock * getSuccessMBB()
MachineBasicBlock * getFailureMBB()
MachineBasicBlock * getParentMBB()
bool shouldEmitFunctionBasedCheckStackProtector() const
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Multiway switch.
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Provides information about what library functions are available for the current target.
virtual Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const
Returns the desired alignment for ByVal or InAlloca aggregate function arguments in the caller parame...
virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
EVT getMemValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
virtual bool isAtomicAlignmentSupported(Align Alignment, uint64_t SizeInBytes) const
Return true if the target supports an atomic access of SizeInBytes bytes at the given Alignment.
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:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:170
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Unconditional Branch instruction.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_iterator op_begin()
Definition User.h:259
unsigned getNumOperands() const
Definition User.h:229
op_iterator op_end()
Definition User.h:261
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
This is the common base class for vector predication intrinsics.
static LLVM_ABI std::optional< unsigned > getVectorLengthParamPos(Intrinsic::ID IntrinsicID)
LLVM_ABI MaybeAlign getPointerAlignment() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
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:315
Base class of all SIMD vector types.
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
const ParentTy * getParent() const
Definition ilist_node.h:34
A raw_ostream that writes to an std::string.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ CONVERGENCECTRL_ANCHOR
The llvm.experimental.convergence.* intrinsics.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ SET_FPENV
Sets the current floating-point environment.
@ ATOMIC_LOAD_FMINIMUMNUM
@ LOOP_DEPENDENCE_RAW_MASK
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ COND_LOOP
COND_LOOP is a conditional branch to self, used for implementing efficient conditional traps.
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ VECREDUCE_FMINIMUMNUM
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ STACKADDRESS
STACKADDRESS - Represents the llvm.stackaddress intrinsic.
Definition ISDOpcodes.h:129
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ SMULFIX
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition ISDOpcodes.h:397
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ RESET_FPENV
Set floating-point environment to default state.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SMULFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:403
@ SET_FPMODE
Sets the current dynamic floating-point control modes.
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ CTTZ_ELTS
Returns the number of number of trailing (least significant) zero elements in a vector.
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ VECTOR_FIND_LAST_ACTIVE
Finds the index of the last active mask element Operands: Mask.
@ FMODF
FMODF - Decomposes the operand into integral and fractional parts, each having the same type and sign...
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ FSINCOSPI
FSINCOSPI - Compute both the sine and cosine times pi more accurately than FSINCOS(pi*x),...
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ EH_SJLJ_SETUP_DISPATCH
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here.
Definition ISDOpcodes.h:174
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:906
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:765
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ RESET_FPMODE
Sets default dynamic floating-point control modes.
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ FPTRUNC_ROUND
FPTRUNC_ROUND - This corresponds to the fptrunc_round intrinsic.
Definition ISDOpcodes.h:520
@ FAKE_USE
FAKE_USE represents a use of the operand but does not do anything.
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:796
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ SDIVFIX
RESULT = [US]DIVFIX(LHS, RHS, SCALE) - Perform fixed point division on 2 integers with the same width...
Definition ISDOpcodes.h:410
@ CONVERT_FROM_ARBITRARY_FP
CONVERT_FROM_ARBITRARY_FP - This operator converts from an arbitrary floating-point represented as an...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:814
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:158
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ SET_ROUNDING
Set rounding mode.
@ CONVERGENCECTRL_GLUE
This does not correspond to any convergence control intrinsic.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ PREALLOCATED_SETUP
PREALLOCATED_SETUP - This has 2 operands: an input chain and a SRCVALUE with the preallocated call Va...
@ READSTEADYCOUNTER
READSTEADYCOUNTER - This corresponds to the readfixedcounter intrinsic.
@ ADDROFRETURNADDR
ADDROFRETURNADDR - Represents the llvm.addressofreturnaddress intrinsic.
Definition ISDOpcodes.h:119
@ CONVERGENCECTRL_ENTRY
@ BR
Control flow instructions. These all have token chains.
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ VECREDUCE_FMAXIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM nodes do not propagate NaNs and order signed zeroes using the llvm....
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ PREALLOCATED_ARG
PREALLOCATED_ARG - This has 3 operands: an input chain, a SRCVALUE with the preallocated call Value,...
@ BRIND
BRIND - Indirect branch.
@ BR_JT
BR_JT - Jumptable branch.
@ VECTOR_INTERLEAVE
VECTOR_INTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor to...
Definition ISDOpcodes.h:640
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:996
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ 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:787
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ PtrAuthGlobalAddress
A ptrauth constant.
Definition ISDOpcodes.h:102
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ READ_REGISTER
READ_REGISTER, WRITE_REGISTER - This node represents llvm.register on the DAG, which implements the n...
Definition ISDOpcodes.h:141
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ DEBUGTRAP
DEBUGTRAP - Trap intended to get the attention of a debugger.
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
@ LOCAL_RECOVER
LOCAL_RECOVER - Represents the llvm.localrecover intrinsic.
Definition ISDOpcodes.h:137
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ UBSANTRAP
UBSANTRAP - Trap with an immediate describing the kind of sanitizer failure.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ PATCHPOINT
The llvm.experimental.patchpoint.
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ ATOMIC_LOAD_FMINIMUM
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:663
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ VECTOR_REVERSE
VECTOR_REVERSE(VECTOR) - Returns a vector, of the same type as VECTOR, whose elements are shuffled us...
Definition ISDOpcodes.h:650
@ SDIVFIXSAT
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition ISDOpcodes.h:416
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:831
@ PCMARKER
PCMARKER - This corresponds to the pcmarker intrinsic.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ ATOMIC_LOAD_FMAXIMUMNUM
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:801
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:952
@ 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:757
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:753
@ 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:667
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ STACKMAP
The llvm.experimental.stackmap intrinsic.
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:813
@ 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:985
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:709
@ SPONENTRY
SPONENTRY - Represents the llvm.sponentry intrinsic.
Definition ISDOpcodes.h:124
@ CLEAR_CACHE
llvm.clear_cache intrinsic Operands: Input Chain, Start Addres, End Address Outputs: Output Chain
@ CONVERGENCECTRL_LOOP
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:971
@ VECREDUCE_FMINIMUM
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ BRCOND
BRCOND - Conditional branch.
@ VECREDUCE_SEQ_FMUL
@ CONVERT_TO_ARBITRARY_FP
CONVERT_TO_ARBITRARY_FP - Converts a native FP value to an arbitrary floating-point format,...
@ CATCHRET
CATCHRET - Represents a return from a catch block funclet.
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:645
@ VECTOR_DEINTERLEAVE
VECTOR_DEINTERLEAVE(VEC1, VEC2, ...) - Returns N vectors from N input vectors, where N is the factor ...
Definition ISDOpcodes.h:629
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ CTTZ_ELTS_ZERO_POISON
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:769
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
@ LOOP_DEPENDENCE_WAR_MASK
The llvm.loop.dependence.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_VScale()
Matches a call to llvm.vscale().
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
Offsets
Offsets in bytes from the start of the input buffer.
std::pair< JumpTableHeader, JumpTable > JumpTableBlock
LLVM_ABI void sortAndRangeify(CaseClusterVector &Clusters)
Sort Clusters and merge adjacent cases.
std::vector< CaseCluster > CaseClusterVector
@ CC_Range
A cluster of adjacent case labels with the same destination, or just one case.
@ CC_JumpTable
A cluster of cases suitable for jump table lowering.
@ CC_BitTests
A cluster of cases suitable for bit test lowering.
SmallVector< SwitchWorkListItem, 4 > SwitchWorkList
CaseClusterVector::iterator CaseClusterIt
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
ExceptionBehavior
Exception behavior used for floating point operations.
Definition FPEnv.h:39
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
@ ebMayTrap
This corresponds to "fpexcept.maytrap".
Definition FPEnv.h:41
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:694
constexpr float log2ef
Definition MathExtras.h:52
constexpr double e
constexpr float ln2f
Definition MathExtras.h:50
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
Type * getValueType(Value *V, bool ReVec, bool LookThroughCmp)
Returns the "element type" of the given value/instruction V.
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
LLVM_ABI bool canDescribeGlobalAddressInLocationList(const MachineFunction &MF)
Test if the debug info for MF can name a describable global address in a location list too,...
Definition Analysis.cpp:642
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:248
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
SDValue peekThroughFreeze(SDValue V)
Return the non-frozen source operand of V if it exists.
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Unknown
Not known to have no common set bits.
LLVM_ABI void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs=nullptr, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition Analysis.cpp:121
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void diagnoseDontCall(const CallInst &CI)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isExceptionPointerAndSelectorType(Type *Ty)
Return true if landingpad result type Ty is a struct of an exception pointer (pointer or integer) and...
Definition Analysis.cpp:201
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
auto cast_or_null(const Y &Val)
Definition Casting.h:714
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1167
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI void ComputeValueTypes(const DataLayout &DL, Type *Ty, SmallVectorImpl< Type * > &Types, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
Given an LLVM IR type, compute non-aggregate subtypes.
Definition Analysis.cpp:74
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_FMINNUM
Unsigned maximum.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&...args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest.
Definition STLExtras.h:869
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
generic_gep_type_iterator<> gep_type_iterator
auto succ_size(const MachineBasicBlock *BB)
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:300
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:214
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2303
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
LLVM_ABI bool isAssignmentTrackingEnabled(const Module &M)
Return true if assignment tracking is enabled for module M.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
@ Dynamic
Denotes mode unknown at compile time.
LLVM_ABI ISD::CondCode getFCmpCodeWithoutNaN(ISD::CondCode CC)
getFCmpCodeWithoutNaN - Given an ISD condition code comparing floats, return the equivalent code if w...
Definition Analysis.cpp:236
LLVM_ABI const GlobalValue * getDescribableGlobalAddress(const Constant *C, int64_t &Offset, const MachineFunction &MF)
If C is the address of a global, possibly displaced by a constant, return that global and set Offset ...
Definition Analysis.cpp:623
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
LLVM_ABI GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:183
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI unsigned ComputeLinearIndex(Type *Ty, const unsigned *Indices, const unsigned *IndicesEnd, unsigned CurIndex=0)
Compute the linearized index of a member in a nested aggregate/struct/array.
Definition Analysis.cpp:35
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h: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:82
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h: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)