LLVM 24.0.0git
SelectionDAGBuilder.cpp
Go to the documentation of this file.
1//===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements routines for translating from LLVM IR into SelectionDAG IR.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SelectionDAGBuilder.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
26#include "llvm/Analysis/Loads.h"
58#include "llvm/IR/Argument.h"
59#include "llvm/IR/Attributes.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/CallingConv.h"
63#include "llvm/IR/Constant.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
67#include "llvm/IR/DebugInfo.h"
72#include "llvm/IR/Function.h"
74#include "llvm/IR/InlineAsm.h"
75#include "llvm/IR/InstrTypes.h"
78#include "llvm/IR/Intrinsics.h"
79#include "llvm/IR/IntrinsicsAArch64.h"
80#include "llvm/IR/IntrinsicsAMDGPU.h"
81#include "llvm/IR/IntrinsicsWebAssembly.h"
82#include "llvm/IR/LLVMContext.h"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/Module.h"
86#include "llvm/IR/Operator.h"
88#include "llvm/IR/Statepoint.h"
89#include "llvm/IR/Type.h"
90#include "llvm/IR/User.h"
91#include "llvm/IR/Value.h"
92#include "llvm/MC/MCContext.h"
97#include "llvm/Support/Debug.h"
105#include <cstddef>
106#include <limits>
107#include <optional>
108#include <tuple>
109
110using namespace llvm;
111using namespace PatternMatch;
112using namespace SwitchCG;
113
114#define DEBUG_TYPE "isel"
115
116/// LimitFloatPrecision - Generate low-precision inline sequences for
117/// some float libcalls (6, 8 or 12 bits).
118static unsigned LimitFloatPrecision;
119
120static cl::opt<bool>
121 InsertAssertAlign("insert-assert-align", cl::init(true),
122 cl::desc("Insert the experimental `assertalign` node."),
124
126 LimitFPPrecision("limit-float-precision",
127 cl::desc("Generate low-precision inline sequences "
128 "for some float libcalls"),
130 cl::init(0));
131
133 "switch-peel-threshold", cl::Hidden, cl::init(66),
134 cl::desc("Set the case probability threshold for peeling the case from a "
135 "switch statement. A value greater than 100 will void this "
136 "optimization"));
137
138// Limit the width of DAG chains. This is important in general to prevent
139// DAG-based analysis from blowing up. For example, alias analysis and
140// load clustering may not complete in reasonable time. It is difficult to
141// recognize and avoid this situation within each individual analysis, and
142// future analyses are likely to have the same behavior. Limiting DAG width is
143// the safe approach and will be especially important with global DAGs.
144//
145// MaxParallelChains default is arbitrarily high to avoid affecting
146// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147// sequence over this should have been converted to llvm.memcpy by the
148// frontend. It is easy to induce this behavior with .ll code such as:
149// %buffer = alloca [4096 x i8]
150// %data = load [4096 x i8]* %argPtr
151// store [4096 x i8] %data, [4096 x i8]* %buffer
152static const unsigned MaxParallelChains = 64;
153
155 const SDValue *Parts, unsigned NumParts,
156 MVT PartVT, EVT ValueVT, const Value *V,
157 SDValue InChain,
158 std::optional<CallingConv::ID> CC);
159
160/// getCopyFromParts - Create a value that contains the specified legal parts
161/// combined into the value they represent. If the parts combine to a type
162/// larger than ValueVT then AssertOp can be used to specify whether the extra
163/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164/// (ISD::AssertSext).
165static SDValue
166getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168 SDValue InChain,
169 std::optional<CallingConv::ID> CC = std::nullopt,
170 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171 // Let the target assemble the parts if it wants to
172 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174 PartVT, ValueVT, CC))
175 return Val;
176
177 if (ValueVT.isVector())
178 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179 InChain, CC);
180
181 assert(NumParts > 0 && "No parts to assemble!");
182 SDValue Val = Parts[0];
183
184 if (NumParts > 1) {
185 // Assemble the value from multiple parts.
186 if (ValueVT.isInteger()) {
187 unsigned PartBits = PartVT.getSizeInBits();
188 unsigned ValueBits = ValueVT.getSizeInBits();
189
190 // Assemble the power of 2 part.
191 unsigned RoundParts = llvm::bit_floor(NumParts);
192 unsigned RoundBits = PartBits * RoundParts;
193 EVT RoundVT = RoundBits == ValueBits ?
194 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195 SDValue Lo, Hi;
196
197 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198
199 if (RoundParts > 2) {
200 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
201 InChain);
202 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
203 PartVT, HalfVT, V, InChain);
204 } else {
205 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207 }
208
209 if (DAG.getDataLayout().isBigEndian())
210 std::swap(Lo, Hi);
211
212 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213
214 if (RoundParts < NumParts) {
215 // Assemble the trailing non-power-of-2 part.
216 unsigned OddParts = NumParts - RoundParts;
217 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219 OddVT, V, InChain, CC);
220
221 // Combine the round and odd parts.
222 Lo = Val;
223 if (DAG.getDataLayout().isBigEndian())
224 std::swap(Lo, Hi);
225 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227 Hi = DAG.getNode(
228 ISD::SHL, DL, TotalVT, Hi,
229 DAG.getShiftAmountConstant(Lo.getValueSizeInBits(), TotalVT, DL));
230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232 }
233 } else if (PartVT.isFloatingPoint()) {
234 // FP split into multiple FP parts (for ppcf128)
235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236 "Unexpected split");
237 SDValue Lo, Hi;
238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241 std::swap(Lo, Hi);
242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243 } else {
244 // FP split into integer parts (soft fp)
245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246 !PartVT.isVector() && "Unexpected split");
247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
249 InChain, CC);
250 }
251 }
252
253 // There is now one part, held in Val. Correct it to match ValueVT.
254 // PartEVT is the type of the register class that holds the value.
255 // ValueVT is the type of the inline asm operation.
256 EVT PartEVT = Val.getValueType();
257
258 if (PartEVT == ValueVT)
259 return Val;
260
261 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262 ValueVT.bitsLT(PartEVT)) {
263 // For an FP value in an integer part, we need to truncate to the right
264 // width first.
265 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
266 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267 }
268
269 // Handle types that have the same size.
270 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272
273 // Handle types with different sizes.
274 if (PartEVT.isInteger() && ValueVT.isInteger()) {
275 if (ValueVT.bitsLT(PartEVT)) {
276 // For a truncate, see if we have any information to
277 // indicate whether the truncated bits will always be
278 // zero or sign-extension.
279 if (AssertOp)
280 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281 DAG.getValueType(ValueVT));
282 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283 }
284 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285 }
286
287 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288 // FP_ROUND's are always exact here.
289 if (ValueVT.bitsLT(Val.getValueType())) {
290
291 SDValue NoChange =
293
294 if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
295 llvm::Attribute::StrictFP)) {
296 return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
297 DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
298 NoChange);
299 }
300
301 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
302 }
303
304 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
305 }
306
307 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
308 // then truncating.
309 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
310 ValueVT.bitsLT(PartEVT)) {
311 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
313 }
314
315 report_fatal_error("Unknown mismatch in getCopyFromParts!");
316}
317
319 const Twine &ErrMsg) {
321 if (!I)
322 return Ctx.emitError(ErrMsg);
323
324 if (const CallInst *CI = dyn_cast<CallInst>(I))
325 if (CI->isInlineAsm()) {
326 return Ctx.diagnose(DiagnosticInfoInlineAsm(
327 *CI, ErrMsg + ", possible invalid constraint for vector type"));
328 }
329
330 return Ctx.emitError(I, ErrMsg);
331}
332
333/// getCopyFromPartsVector - Create a value that contains the specified legal
334/// parts combined into the value they represent. If the parts combine to a
335/// type larger than ValueVT then AssertOp can be used to specify whether the
336/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
337/// ValueVT (ISD::AssertSext).
339 const SDValue *Parts, unsigned NumParts,
340 MVT PartVT, EVT ValueVT, const Value *V,
341 SDValue InChain,
342 std::optional<CallingConv::ID> CallConv) {
343 assert(ValueVT.isVector() && "Not a vector value");
344 assert(NumParts > 0 && "No parts to assemble!");
345 const bool IsABIRegCopy = CallConv.has_value();
346
347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
348 SDValue Val = Parts[0];
349
350 // Handle a multi-element vector.
351 if (NumParts > 1) {
352 EVT IntermediateVT;
353 MVT RegisterVT;
354 unsigned NumIntermediates;
355 unsigned NumRegs;
356
357 if (IsABIRegCopy) {
359 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
360 NumIntermediates, RegisterVT);
361 } else {
362 NumRegs =
363 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
364 NumIntermediates, RegisterVT);
365 }
366
367 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
368 NumParts = NumRegs; // Silence a compiler warning.
369 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
370 assert(RegisterVT.getSizeInBits() ==
371 Parts[0].getSimpleValueType().getSizeInBits() &&
372 "Part type sizes don't match!");
373
374 // Assemble the parts into intermediate operands.
375 SmallVector<SDValue, 8> Ops(NumIntermediates);
376 if (NumIntermediates == NumParts) {
377 // If the register was not expanded, truncate or copy the value,
378 // as appropriate.
379 for (unsigned i = 0; i != NumParts; ++i)
380 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
381 V, InChain, CallConv);
382 } else if (NumParts > 0) {
383 // If the intermediate type was expanded, build the intermediate
384 // operands from the parts.
385 assert(NumParts % NumIntermediates == 0 &&
386 "Must expand into a divisible number of parts!");
387 unsigned Factor = NumParts / NumIntermediates;
388 for (unsigned i = 0; i != NumIntermediates; ++i)
389 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
390 IntermediateVT, V, InChain, CallConv);
391 }
392
393 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
394 // intermediate operands.
395 EVT BuiltVectorTy =
396 IntermediateVT.isVector()
398 *DAG.getContext(), IntermediateVT.getScalarType(),
399 IntermediateVT.getVectorElementCount() * NumParts)
401 IntermediateVT.getScalarType(),
402 NumIntermediates);
403 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
405 DL, BuiltVectorTy, Ops);
406 }
407
408 // There is now one part, held in Val. Correct it to match ValueVT.
409 EVT PartEVT = Val.getValueType();
410
411 if (PartEVT == ValueVT)
412 return Val;
413
414 if (PartEVT.isVector()) {
415 // Vector/Vector bitcast.
416 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
417 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
418
419 // If the parts vector has more elements than the value vector, then we
420 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
421 // Extract the elements we want.
422 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
425 (PartEVT.getVectorElementCount().isScalable() ==
426 ValueVT.getVectorElementCount().isScalable()) &&
427 "Cannot narrow, it would be a lossy transformation");
428 PartEVT =
430 ValueVT.getVectorElementCount());
431 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
432 DAG.getVectorIdxConstant(0, DL));
433 if (PartEVT == ValueVT)
434 return Val;
435 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437
438 // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
439 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
440 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441 }
442
443 // Promoted vector extract
444 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
445 }
446
447 // Trivial bitcast if the types are the same size and the destination
448 // vector type is legal.
449 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
450 TLI.isTypeLegal(ValueVT))
451 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
452
453 if (ValueVT.getVectorNumElements() != 1) {
454 // Certain ABIs require that vectors are passed as integers. For vectors
455 // are the same size, this is an obvious bitcast.
456 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
458 } else if (ValueVT.bitsLT(PartEVT)) {
459 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
461 // Drop the extra bits.
462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
463 return DAG.getBitcast(ValueVT, Val);
464 }
465
467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
468 return DAG.getUNDEF(ValueVT);
469 }
470
471 // Handle cases such as i8 -> <1 x i1>
472 EVT ValueSVT = ValueVT.getVectorElementType();
473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
474 unsigned ValueSize = ValueSVT.getSizeInBits();
475 if (ValueSize == PartEVT.getSizeInBits()) {
476 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
477 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
478 // It's possible a scalar floating point type gets softened to integer and
479 // then promoted to a larger integer. If PartEVT is the larger integer
480 // we need to truncate it and then bitcast to the FP type.
481 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
482 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
483 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
484 Val = DAG.getBitcast(ValueSVT, Val);
485 } else {
486 Val = ValueVT.isFloatingPoint()
487 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
488 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
489 }
490 }
491
492 return DAG.getBuildVector(ValueVT, DL, Val);
493}
494
495static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
496 SDValue Val, SDValue *Parts, unsigned NumParts,
497 MVT PartVT, const Value *V,
498 std::optional<CallingConv::ID> CallConv);
499
500/// getCopyToParts - Create a series of nodes that contain the specified value
501/// split into legal parts. If the parts contain more bits than Val, then, for
502/// integers, ExtendKind can be used to specify how to generate the extra bits.
503static void
505 unsigned NumParts, MVT PartVT, const Value *V,
506 std::optional<CallingConv::ID> CallConv = std::nullopt,
507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508 // Let the target split the parts if it wants to
509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
510 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
511 CallConv))
512 return;
513 EVT ValueVT = Val.getValueType();
514
515 // Handle the vector case separately.
516 if (ValueVT.isVector())
517 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
518 CallConv);
519
520 unsigned OrigNumParts = NumParts;
522 "Copying to an illegal type!");
523
524 if (NumParts == 0)
525 return;
526
527 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
528 EVT PartEVT = PartVT;
529 if (PartEVT == ValueVT) {
530 assert(NumParts == 1 && "No-op copy with multiple parts!");
531 Parts[0] = Val;
532 return;
533 }
534
535 unsigned PartBits = PartVT.getSizeInBits();
536 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
537 // If the parts cover more bits than the value has, promote the value.
538 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
539 assert(NumParts == 1 && "Do not know what to promote to!");
540 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
541 } else {
542 if (ValueVT.isFloatingPoint()) {
543 // FP values need to be bitcast, then extended if they are being put
544 // into a larger container.
545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
546 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
547 }
548 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
549 ValueVT.isInteger() &&
550 "Unknown mismatch!");
551 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
552 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
553 if (PartVT == MVT::x86mmx)
554 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
555 }
556 } else if (PartBits == ValueVT.getSizeInBits()) {
557 // Different types of the same size.
558 assert(NumParts == 1 && PartEVT != ValueVT);
559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561 // If the parts cover less bits than value has, truncate the value.
562 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
563 ValueVT.isInteger() &&
564 "Unknown mismatch!");
565 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
566 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
567 if (PartVT == MVT::x86mmx)
568 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
569 }
570
571 // The value may have changed - recompute ValueVT.
572 ValueVT = Val.getValueType();
573 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
574 "Failed to tile the value with PartVT!");
575
576 if (NumParts == 1) {
577 if (PartEVT != ValueVT) {
579 "scalar-to-vector conversion failed");
580 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
581 }
582
583 Parts[0] = Val;
584 return;
585 }
586
587 // Expand the value into multiple parts.
588 if (NumParts & (NumParts - 1)) {
589 // The number of parts is not a power of 2. Split off and copy the tail.
590 assert(PartVT.isInteger() && ValueVT.isInteger() &&
591 "Do not know what to expand to!");
592 unsigned RoundParts = llvm::bit_floor(NumParts);
593 unsigned RoundBits = RoundParts * PartBits;
594 unsigned OddParts = NumParts - RoundParts;
595 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
596 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
597
598 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
599 CallConv);
600
601 if (DAG.getDataLayout().isBigEndian())
602 // The odd parts were reversed by getCopyToParts - unreverse them.
603 std::reverse(Parts + RoundParts, Parts + NumParts);
604
605 NumParts = RoundParts;
606 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
607 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
608 }
609
610 // The number of parts is a power of 2. Repeatedly bisect the value using
611 // EXTRACT_ELEMENT.
612 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
614 ValueVT.getSizeInBits()),
615 Val);
616
617 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
618 for (unsigned i = 0; i < NumParts; i += StepSize) {
619 unsigned ThisBits = StepSize * PartBits / 2;
620 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
621 SDValue &Part0 = Parts[i];
622 SDValue &Part1 = Parts[i+StepSize/2];
623
624 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
625 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
626 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
628
629 if (ThisBits == PartBits && ThisVT != PartVT) {
630 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
631 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
632 }
633 }
634 }
635
636 if (DAG.getDataLayout().isBigEndian())
637 std::reverse(Parts, Parts + OrigNumParts);
638}
639
641 const SDLoc &DL, EVT PartVT) {
642 if (!PartVT.isVector())
643 return SDValue();
644
645 EVT ValueVT = Val.getValueType();
646 EVT PartEVT = PartVT.getVectorElementType();
647 EVT ValueEVT = ValueVT.getVectorElementType();
648 ElementCount PartNumElts = PartVT.getVectorElementCount();
649 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
650
651 // We only support widening vectors with equivalent element types and
652 // fixed/scalable properties. If a target needs to widen a fixed-length type
653 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
654 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
655 PartNumElts.isScalable() != ValueNumElts.isScalable())
656 return SDValue();
657
658 // Have a try for bf16 because some targets share its ABI with fp16.
659 if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
661 "Cannot widen to illegal type");
662 Val = DAG.getNode(
664 ValueVT.changeVectorElementType(*DAG.getContext(), MVT::f16), Val);
665 } else if (PartEVT != ValueEVT) {
666 return SDValue();
667 }
668
669 // Widening a scalable vector to another scalable vector is done by inserting
670 // the vector into a larger undef one.
671 if (PartNumElts.isScalable())
672 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
673 Val, DAG.getVectorIdxConstant(0, DL));
674
675 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
676 // undef elements.
678 DAG.ExtractVectorElements(Val, Ops);
679 SDValue EltUndef = DAG.getUNDEF(PartEVT);
680 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
681
682 // FIXME: Use CONCAT for 2x -> 4x.
683 return DAG.getBuildVector(PartVT, DL, Ops);
684}
685
686/// getCopyToPartsVector - Create a series of nodes that contain the specified
687/// value split into legal parts.
688static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689 SDValue Val, SDValue *Parts, unsigned NumParts,
690 MVT PartVT, const Value *V,
691 std::optional<CallingConv::ID> CallConv) {
692 EVT ValueVT = Val.getValueType();
693 assert(ValueVT.isVector() && "Not a vector");
694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695 const bool IsABIRegCopy = CallConv.has_value();
696
697 if (NumParts == 1) {
698 EVT PartEVT = PartVT;
699 if (PartEVT == ValueVT) {
700 // Nothing to do.
701 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702 // Bitconvert vector->vector case.
703 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
704 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705 Val = Widened;
706 } else if (PartVT.isVector() &&
708 ValueVT.getVectorElementType()) &&
709 PartEVT.getVectorElementCount() ==
710 ValueVT.getVectorElementCount()) {
711
712 // Promoted vector extract
713 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
714 } else if (PartEVT.isVector() &&
715 PartEVT.getVectorElementType() !=
716 ValueVT.getVectorElementType() &&
717 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
719 // Combination of widening and promotion.
720 EVT WidenVT =
722 PartVT.getVectorElementCount());
723 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
724 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
725 } else {
726 // Don't extract an integer from a float vector. This can happen if the
727 // FP type gets softened to integer and then promoted. The promotion
728 // prevents it from being picked up by the earlier bitcast case.
729 if (ValueVT.getVectorElementCount().isScalar() &&
730 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731 // If we reach this condition and PartVT is FP, this means that
732 // ValueVT is also FP and both have a different size, otherwise we
733 // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
734 // would be invalid since that would mean the smaller FP type has to
735 // be extended to the larger one.
736 if (PartVT.isFloatingPoint()) {
737 Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
738 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
739 } else
740 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
741 DAG.getVectorIdxConstant(0, DL));
742 } else {
743 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
744 assert(PartVT.getFixedSizeInBits() > ValueSize &&
745 "lossy conversion of vector to scalar type");
746 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
747 Val = DAG.getBitcast(IntermediateType, Val);
748 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
749 }
750 }
751
752 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
753 Parts[0] = Val;
754 return;
755 }
756
757 // Handle a multi-element vector.
758 EVT IntermediateVT;
759 MVT RegisterVT;
760 unsigned NumIntermediates;
761 unsigned NumRegs;
762 if (IsABIRegCopy) {
764 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
765 RegisterVT);
766 } else {
767 NumRegs =
768 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
769 NumIntermediates, RegisterVT);
770 }
771
772 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
773 NumParts = NumRegs; // Silence a compiler warning.
774 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775
776 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
777 "Mixing scalable and fixed vectors when copying in parts");
778
779 std::optional<ElementCount> DestEltCnt;
780
781 if (IntermediateVT.isVector())
782 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
783 else
784 DestEltCnt = ElementCount::getFixed(NumIntermediates);
785
786 EVT BuiltVectorTy = EVT::getVectorVT(
787 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
788
789 if (ValueVT == BuiltVectorTy) {
790 // Nothing to do.
791 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
792 // Bitconvert vector->vector case.
793 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
794 } else {
795 if (BuiltVectorTy.getVectorElementType().bitsGT(
796 ValueVT.getVectorElementType())) {
797 // Integer promotion.
798 ValueVT = EVT::getVectorVT(*DAG.getContext(),
799 BuiltVectorTy.getVectorElementType(),
800 ValueVT.getVectorElementCount());
801 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
802 }
803
804 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
805 Val = Widened;
806 }
807 }
808
809 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
810
811 // Split the vector into intermediate operands.
812 SmallVector<SDValue, 8> Ops(NumIntermediates);
813 for (unsigned i = 0; i != NumIntermediates; ++i) {
814 if (IntermediateVT.isVector()) {
815 // This does something sensible for scalable vectors - see the
816 // definition of EXTRACT_SUBVECTOR for further details.
817 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
818 Ops[i] =
819 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
820 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
821 } else {
822 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
823 DAG.getVectorIdxConstant(i, DL));
824 }
825 }
826
827 // Split the intermediate operands into legal parts.
828 if (NumParts == NumIntermediates) {
829 // If the register was not expanded, promote or copy the value,
830 // as appropriate.
831 for (unsigned i = 0; i != NumParts; ++i)
832 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
833 } else if (NumParts > 0) {
834 // If the intermediate type was expanded, split each the value into
835 // legal parts.
836 assert(NumIntermediates != 0 && "division by zero");
837 assert(NumParts % NumIntermediates == 0 &&
838 "Must expand into a divisible number of parts!");
839 unsigned Factor = NumParts / NumIntermediates;
840 for (unsigned i = 0; i != NumIntermediates; ++i)
841 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
842 CallConv);
843 }
844}
845
846static void failForInvalidBundles(const CallBase &I, StringRef Name,
847 ArrayRef<uint32_t> AllowedBundles) {
848 if (I.hasOperandBundlesOtherThan(AllowedBundles)) {
849 ListSeparator LS;
850 std::string Error;
852 for (unsigned i = 0, e = I.getNumOperandBundles(); i != e; ++i) {
853 OperandBundleUse U = I.getOperandBundleAt(i);
854 if (!is_contained(AllowedBundles, U.getTagID()))
855 OS << LS << U.getTagName();
856 }
858 Twine("cannot lower ", Name)
859 .concat(Twine(" with arbitrary operand bundles: ", Error)));
860 }
861}
862
864 EVT valuevt, std::optional<CallingConv::ID> CC)
865 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
866 RegCount(1, regs.size()), CallConv(CC) {}
867
869 const DataLayout &DL, Register Reg, Type *Ty,
870 std::optional<CallingConv::ID> CC) {
871 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
872
873 CallConv = CC;
874
875 for (EVT ValueVT : ValueVTs) {
876 unsigned NumRegs =
878 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
879 : TLI.getNumRegisters(Context, ValueVT);
880 MVT RegisterVT =
882 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
883 : TLI.getRegisterType(Context, ValueVT);
884 for (unsigned i = 0; i != NumRegs; ++i)
885 Regs.push_back(Reg + i);
886 RegVTs.push_back(RegisterVT);
887 RegCount.push_back(NumRegs);
888 Reg = Reg.id() + NumRegs;
889 }
890}
891
893 FunctionLoweringInfo &FuncInfo,
894 const SDLoc &dl, SDValue &Chain,
895 SDValue *Glue, const Value *V) const {
896 // A Value with type {} or [0 x %t] needs no registers.
897 if (ValueVTs.empty())
898 return SDValue();
899
900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
901
902 // Assemble the legal parts into the final values.
905 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
906 // Copy the legal parts from the registers.
907 EVT ValueVT = ValueVTs[Value];
908 unsigned NumRegs = RegCount[Value];
909 MVT RegisterVT = isABIMangled()
911 *DAG.getContext(), *CallConv, RegVTs[Value])
912 : RegVTs[Value];
913
914 Parts.resize(NumRegs);
915 for (unsigned i = 0; i != NumRegs; ++i) {
916 SDValue P;
917 if (!Glue) {
918 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
919 } else {
920 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
921 *Glue = P.getValue(2);
922 }
923
924 Chain = P.getValue(1);
925 Parts[i] = P;
926
927 // If the source register was virtual and if we know something about it,
928 // add an assert node.
929 if (!Regs[Part + i].isVirtual() || !RegisterVT.isInteger())
930 continue;
931
933 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
934 if (!LOI)
935 continue;
936
937 unsigned RegSize = RegisterVT.getScalarSizeInBits();
938 unsigned NumSignBits = LOI->NumSignBits;
939 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
940
941 if (NumZeroBits == RegSize) {
942 // The current value is a zero.
943 // Explicitly express that as it would be easier for
944 // optimizations to kick in.
945 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
946 continue;
947 }
948
949 // FIXME: We capture more information than the dag can represent. For
950 // now, just use the tightest assertzext/assertsext possible.
951 bool isSExt;
952 EVT FromVT(MVT::Other);
953 if (NumZeroBits) {
954 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
955 isSExt = false;
956 } else if (NumSignBits > 1) {
957 FromVT =
958 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
959 isSExt = true;
960 } else {
961 continue;
962 }
963 // Add an assertion node.
964 assert(FromVT != MVT::Other);
965 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
966 RegisterVT, P, DAG.getValueType(FromVT));
967 }
968
969 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
970 RegisterVT, ValueVT, V, Chain, CallConv);
971 Part += NumRegs;
972 Parts.clear();
973 }
974
975 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
976}
977
979 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
980 const Value *V,
981 ISD::NodeType PreferredExtendType) const {
982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
983 ISD::NodeType ExtendKind = PreferredExtendType;
984
985 // Get the list of the values's legal parts.
986 unsigned NumRegs = Regs.size();
987 SmallVector<SDValue, 8> Parts(NumRegs);
988 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
989 unsigned NumParts = RegCount[Value];
990
991 MVT RegisterVT = isABIMangled()
993 *DAG.getContext(), *CallConv, RegVTs[Value])
994 : RegVTs[Value];
995
996 if (ExtendKind == ISD::ANY_EXTEND)
997 if (TLI.isZExtFree(peekThroughFreeze(Val), RegisterVT))
998 ExtendKind = ISD::ZERO_EXTEND;
999
1000 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
1001 NumParts, RegisterVT, V, CallConv, ExtendKind);
1002 Part += NumParts;
1003 }
1004
1005 // Copy the parts into the registers.
1006 SmallVector<SDValue, 8> Chains(NumRegs);
1007 for (unsigned i = 0; i != NumRegs; ++i) {
1008 SDValue Part;
1009 if (!Glue) {
1010 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
1011 } else {
1012 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
1013 *Glue = Part.getValue(1);
1014 }
1015
1016 Chains[i] = Part.getValue(0);
1017 }
1018
1019 if (NumRegs == 1 || Glue)
1020 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1021 // flagged to it. That is the CopyToReg nodes and the user are considered
1022 // a single scheduling unit. If we create a TokenFactor and return it as
1023 // chain, then the TokenFactor is both a predecessor (operand) of the
1024 // user as well as a successor (the TF operands are flagged to the user).
1025 // c1, f1 = CopyToReg
1026 // c2, f2 = CopyToReg
1027 // c3 = TokenFactor c1, c2
1028 // ...
1029 // = op c3, ..., f2
1030 Chain = Chains[NumRegs-1];
1031 else
1032 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1033}
1034
1036 unsigned MatchingIdx, const SDLoc &dl,
1037 SelectionDAG &DAG,
1038 std::vector<SDValue> &Ops) const {
1039 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1040
1041 InlineAsm::Flag Flag(Code, Regs.size());
1042 if (HasMatching)
1043 Flag.setMatchingOp(MatchingIdx);
1044 else if (!Regs.empty() && Regs.front().isVirtual()) {
1045 // Put the register class of the virtual registers in the flag word. That
1046 // way, later passes can recompute register class constraints for inline
1047 // assembly as well as normal instructions.
1048 // Don't do this for tied operands that can use the regclass information
1049 // from the def.
1051 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1052 Flag.setRegClass(RC->getID());
1053 }
1054
1055 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1056 Ops.push_back(Res);
1057
1058 if (Code == InlineAsm::Kind::Clobber) {
1059 // Clobbers should always have a 1:1 mapping with registers, and may
1060 // reference registers that have illegal (e.g. vector) types. Hence, we
1061 // shouldn't try to apply any sort of splitting logic to them.
1062 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1063 "No 1:1 mapping from clobbers to regs?");
1065 (void)SP;
1066 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1067 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1068 assert(
1069 (Regs[I] != SP ||
1071 "If we clobbered the stack pointer, MFI should know about it.");
1072 }
1073 return;
1074 }
1075
1076 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1077 MVT RegisterVT = RegVTs[Value];
1078 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1079 RegisterVT);
1080 for (unsigned i = 0; i != NumRegs; ++i) {
1081 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1082 Register TheReg = Regs[Reg++];
1083 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1084 }
1085 }
1086}
1087
1091 unsigned I = 0;
1092 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1093 unsigned RegCount = std::get<0>(CountAndVT);
1094 MVT RegisterVT = std::get<1>(CountAndVT);
1095 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1096 for (unsigned E = I + RegCount; I != E; ++I)
1097 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1098 }
1099 return OutVec;
1100}
1101
1103 AssumptionCache *ac, const TargetLibraryInfo *li,
1104 const TargetTransformInfo &TTI) {
1105 BatchAA = aa;
1106 AC = ac;
1107 GFI = gfi;
1108 LibInfo = li;
1109 Context = DAG.getContext();
1110 LPadToCallSiteMap.clear();
1111 this->TTI = &TTI;
1112 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1113 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1114 *DAG.getMachineFunction().getFunction().getParent());
1115}
1116
1118 NodeMap.clear();
1119 UnusedArgNodeMap.clear();
1120 PendingLoads.clear();
1121 PendingExports.clear();
1122 PendingConstrainedFP.clear();
1123 PendingConstrainedFPStrict.clear();
1124 CurInst = nullptr;
1125 HasTailCall = false;
1126 SDNodeOrder = LowestSDNodeOrder;
1127 StatepointLowering.clear();
1128}
1129
1131 DanglingDebugInfoMap.clear();
1132}
1133
1134// Update DAG root to include dependencies on Pending chains.
1135SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1136 SDValue Root = DAG.getRoot();
1137
1138 if (Pending.empty())
1139 return Root;
1140
1141 // Add current root to PendingChains, unless we already indirectly
1142 // depend on it.
1143 if (Root.getOpcode() != ISD::EntryToken) {
1144 unsigned i = 0, e = Pending.size();
1145 for (; i != e; ++i) {
1146 assert(Pending[i].getNode()->getNumOperands() > 1);
1147 if (Pending[i].getNode()->getOperand(0) == Root)
1148 break; // Don't add the root if we already indirectly depend on it.
1149 }
1150
1151 if (i == e)
1152 Pending.push_back(Root);
1153 }
1154
1155 if (Pending.size() == 1)
1156 Root = Pending[0];
1157 else
1158 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1159
1160 DAG.setRoot(Root);
1161 Pending.clear();
1162 return Root;
1163}
1164
1168
1170 // If the new exception behavior differs from that of the pending
1171 // ones, chain up them and update the root.
1172 switch (EB) {
1175 // Floating-point exceptions produced by such operations are not intended
1176 // to be observed, so the sequence of these operations does not need to be
1177 // preserved.
1178 //
1179 // They however must not be mixed with the instructions that have strict
1180 // exception behavior. Placing an operation with 'ebIgnore' behavior between
1181 // 'ebStrict' operations could distort the observed exception behavior.
1182 if (!PendingConstrainedFPStrict.empty()) {
1183 assert(PendingConstrainedFP.empty());
1184 updateRoot(PendingConstrainedFPStrict);
1185 }
1186 break;
1188 // Floating-point exception produced by these operations may be observed, so
1189 // they must be correctly chained. If trapping on FP exceptions is
1190 // disabled, the exceptions can be observed only by functions that read
1191 // exception flags, like 'llvm.get_fpenv' or 'fetestexcept'. It means that
1192 // the order of operations is not significant between barriers.
1193 //
1194 // If trapping is enabled, each operation becomes an implicit observation
1195 // point, so the operations must be sequenced according their original
1196 // source order.
1197 if (!PendingConstrainedFP.empty()) {
1198 assert(PendingConstrainedFPStrict.empty());
1199 updateRoot(PendingConstrainedFP);
1200 }
1201 // TODO: Add support for trapping-enabled scenarios.
1202 }
1203 return DAG.getRoot();
1204}
1205
1207 // Chain up all pending constrained intrinsics together with all
1208 // pending loads, by simply appending them to PendingLoads and
1209 // then calling getMemoryRoot().
1210 PendingLoads.reserve(PendingLoads.size() +
1211 PendingConstrainedFP.size() +
1212 PendingConstrainedFPStrict.size());
1213 PendingLoads.append(PendingConstrainedFP.begin(),
1214 PendingConstrainedFP.end());
1215 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1216 PendingConstrainedFPStrict.end());
1217 PendingConstrainedFP.clear();
1218 PendingConstrainedFPStrict.clear();
1219 return getMemoryRoot();
1220}
1221
1223 // We need to emit pending fpexcept.strict constrained intrinsics,
1224 // so append them to the PendingExports list.
1225 PendingExports.append(PendingConstrainedFPStrict.begin(),
1226 PendingConstrainedFPStrict.end());
1227 PendingConstrainedFPStrict.clear();
1228 return updateRoot(PendingExports);
1229}
1230
1232 DILocalVariable *Variable,
1234 DebugLoc DL) {
1235 assert(Variable && "Missing variable");
1236
1237 // Check if address has undef value.
1238 if (!Address || isa<UndefValue>(Address) ||
1239 (Address->use_empty() && !isa<Argument>(Address))) {
1240 LLVM_DEBUG(
1241 dbgs()
1242 << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1243 return;
1244 }
1245
1246 bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1247
1248 SDValue &N = NodeMap[Address];
1249 if (!N.getNode() && isa<Argument>(Address))
1250 // Check unused arguments map.
1251 N = UnusedArgNodeMap[Address];
1252 SDDbgValue *SDV;
1253 if (N.getNode()) {
1254 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1255 Address = BCI->getOperand(0);
1256 // Parameters are handled specially.
1257 auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1258 if (IsParameter && FINode) {
1259 // Byval parameter. We have a frame index at this point.
1260 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1261 /*IsIndirect*/ true, DL, SDNodeOrder);
1262 } else if (isa<Argument>(Address)) {
1263 // Address is an argument, so try to emit its dbg value using
1264 // virtual register info from the FuncInfo.ValueMap.
1265 EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1266 FuncArgumentDbgValueKind::Declare, N);
1267 return;
1268 } else {
1269 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1270 true, DL, SDNodeOrder);
1271 }
1272 DAG.AddDbgValue(SDV, IsParameter);
1273 } else {
1274 // If Address is an argument then try to emit its dbg value using
1275 // virtual register info from the FuncInfo.ValueMap.
1276 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1277 FuncArgumentDbgValueKind::Declare, N)) {
1278 LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1279 << " (could not emit func-arg dbg_value)\n");
1280 }
1281 }
1282}
1283
1285 // Add SDDbgValue nodes for any var locs here. Do so before updating
1286 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1287 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1288 // Add SDDbgValue nodes for any var locs here. Do so before updating
1289 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1290 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1291 It != End; ++It) {
1292 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1293 dropDanglingDebugInfo(Var, It->Expr);
1294 if (It->Values.isKillLocation(It->Expr)) {
1295 handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1296 continue;
1297 }
1298 SmallVector<Value *> Values(It->Values.location_ops());
1299 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1300 It->Values.hasArgList())) {
1301 SmallVector<Value *, 4> Vals(It->Values.location_ops());
1303 FnVarLocs->getDILocalVariable(It->VariableID),
1304 It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1305 }
1306 }
1307 }
1308
1309 // We must skip DbgVariableRecords if they've already been processed above as
1310 // we have just emitted the debug values resulting from assignment tracking
1311 // analysis, making any existing DbgVariableRecords redundant (and probably
1312 // less correct). We still need to process DbgLabelRecords. This does sink
1313 // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1314 // be important as it does so deterministcally and ordering between
1315 // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1316 // printing).
1317 bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1318 // Is there is any debug-info attached to this instruction, in the form of
1319 // DbgRecord non-instruction debug-info records.
1320 for (DbgRecord &DR : I.getDbgRecordRange()) {
1321 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1322 assert(DLR->getLabel() && "Missing label");
1323 SDDbgLabel *SDV =
1324 DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1325 DAG.AddDbgLabel(SDV);
1326 continue;
1327 }
1328
1329 if (SkipDbgVariableRecords)
1330 continue;
1332 DILocalVariable *Variable = DVR.getVariable();
1335
1337 if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1338 continue;
1339 LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1340 << "\n");
1342 DVR.getDebugLoc());
1343 continue;
1344 }
1345
1346 // A DbgVariableRecord with no locations is a kill location.
1348 if (Values.empty()) {
1350 SDNodeOrder);
1351 continue;
1352 }
1353
1354 // A DbgVariableRecord with an undef or absent location is also a kill
1355 // location.
1356 if (llvm::any_of(Values,
1357 [](Value *V) { return !V || isa<UndefValue>(V); })) {
1359 SDNodeOrder);
1360 continue;
1361 }
1362
1363 bool IsVariadic = DVR.hasArgList();
1364 if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1365 SDNodeOrder, IsVariadic)) {
1366 addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1367 DVR.getDebugLoc(), SDNodeOrder);
1368 }
1369 }
1370}
1371
1373 visitDbgInfo(I);
1374
1375 // Set up outgoing PHI node register values before emitting the terminator.
1376 if (I.isTerminator()) {
1377 HandlePHINodesInSuccessorBlocks(I.getParent());
1378 }
1379
1380 ++SDNodeOrder;
1381 CurInst = &I;
1382
1383 // Set inserted listener only if required.
1384 bool NodeInserted = false;
1385 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1386 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1387 MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1388 if (PCSectionsMD || MMRA) {
1389 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1390 DAG, [&](SDNode *) { NodeInserted = true; });
1391 }
1392
1393 visit(I.getOpcode(), I);
1394
1395 if (!I.isTerminator() && !HasTailCall &&
1396 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1398
1399 // Handle metadata.
1400 if (PCSectionsMD || MMRA) {
1401 auto It = NodeMap.find(&I);
1402 if (It != NodeMap.end()) {
1403 if (PCSectionsMD)
1404 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1405 if (MMRA)
1406 DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1407 } else if (NodeInserted) {
1408 // This should not happen; if it does, don't let it go unnoticed so we can
1409 // fix it. Relevant visit*() function is probably missing a setValue().
1410 errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1411 << I.getModule()->getName() << "]\n";
1412 LLVM_DEBUG(I.dump());
1413 assert(false);
1414 }
1415 }
1416
1417 CurInst = nullptr;
1418}
1419
1420void SelectionDAGBuilder::visitPHI(const PHINode &) {
1421 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1422}
1423
1424void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1425 // Note: this doesn't use InstVisitor, because it has to work with
1426 // ConstantExpr's in addition to instructions.
1427 switch (Opcode) {
1428 default: llvm_unreachable("Unknown instruction type encountered!");
1429 // Build the switch statement using the Instruction.def file.
1430#define HANDLE_INST(NUM, OPCODE, CLASS) \
1431 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1432#include "llvm/IR/Instruction.def"
1433 }
1434}
1435
1437 DILocalVariable *Variable,
1438 DebugLoc DL, unsigned Order,
1441 // For variadic dbg_values we will now insert poison.
1442 // FIXME: We can potentially recover these!
1444 for (const Value *V : Values) {
1445 auto *Poison = PoisonValue::get(V->getType());
1447 }
1448 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1449 /*IsIndirect=*/false, DL, Order,
1450 /*IsVariadic=*/true);
1451 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1452 return true;
1453}
1454
1456 DILocalVariable *Var,
1457 DIExpression *Expr,
1458 bool IsVariadic, DebugLoc DL,
1459 unsigned Order) {
1460 if (IsVariadic) {
1461 handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1462 return;
1463 }
1464 // TODO: Dangling debug info will eventually either be resolved or produce
1465 // a poison DBG_VALUE. However in the resolution case, a gap may appear
1466 // between the original dbg.value location and its resolved DBG_VALUE,
1467 // which we should ideally fill with an extra poison DBG_VALUE.
1468 assert(Values.size() == 1);
1469 DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1470}
1471
1473 const DIExpression *Expr) {
1474 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1475 DIVariable *DanglingVariable = DDI.getVariable();
1476 DIExpression *DanglingExpr = DDI.getExpression();
1477 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1478 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1479 << printDDI(nullptr, DDI) << "\n");
1480 return true;
1481 }
1482 return false;
1483 };
1484
1485 for (auto &DDIMI : DanglingDebugInfoMap) {
1486 DanglingDebugInfoVector &DDIV = DDIMI.second;
1487
1488 // If debug info is to be dropped, run it through final checks to see
1489 // whether it can be salvaged.
1490 for (auto &DDI : DDIV)
1491 if (isMatchingDbgValue(DDI))
1492 salvageUnresolvedDbgValue(DDIMI.first, DDI);
1493
1494 erase_if(DDIV, isMatchingDbgValue);
1495 }
1496}
1497
1498// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1499// generate the debug data structures now that we've seen its definition.
1501 SDValue Val) {
1502 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1503 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1504 return;
1505
1506 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1507 for (auto &DDI : DDIV) {
1508 DebugLoc DL = DDI.getDebugLoc();
1509 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1510 DILocalVariable *Variable = DDI.getVariable();
1511 DIExpression *Expr = DDI.getExpression();
1512 assert(Variable->isValidLocationForIntrinsic(DL) &&
1513 "Expected inlined-at fields to agree");
1514 SDDbgValue *SDV;
1515 if (Val.getNode()) {
1516 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1517 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1518 // we couldn't resolve it directly when examining the DbgValue intrinsic
1519 // in the first place we should not be more successful here). Unless we
1520 // have some test case that prove this to be correct we should avoid
1521 // calling EmitFuncArgumentDbgValue here.
1522 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1523 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1524 FuncArgumentDbgValueKind::Value, Val)) {
1525 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1526 << printDDI(V, DDI) << "\n");
1527 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1528 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1529 // inserted after the definition of Val when emitting the instructions
1530 // after ISel. An alternative could be to teach
1531 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1532 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1533 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1534 << ValSDNodeOrder << "\n");
1535 SDV = getDbgValue(Val, Variable, Expr, DL,
1536 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1537 DAG.AddDbgValue(SDV, false);
1538 } else
1539 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1540 << printDDI(V, DDI)
1541 << " in EmitFuncArgumentDbgValue\n");
1542 } else {
1543 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1544 << "\n");
1545 auto Poison = PoisonValue::get(V->getType());
1546 auto SDV =
1547 DAG.getConstantDbgValue(Variable, Expr, Poison, DL, DbgSDNodeOrder);
1548 DAG.AddDbgValue(SDV, false);
1549 }
1550 }
1551 DDIV.clear();
1552}
1553
1555 DanglingDebugInfo &DDI) {
1556 // TODO: For the variadic implementation, instead of only checking the fail
1557 // state of `handleDebugValue`, we need know specifically which values were
1558 // invalid, so that we attempt to salvage only those values when processing
1559 // a DIArgList.
1560 const Value *OrigV = V;
1561 DILocalVariable *Var = DDI.getVariable();
1562 DIExpression *Expr = DDI.getExpression();
1563 DebugLoc DL = DDI.getDebugLoc();
1564 unsigned SDOrder = DDI.getSDNodeOrder();
1565
1566 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1567 // that DW_OP_stack_value is desired.
1568 bool StackValue = true;
1569
1570 // Can this Value can be encoded without any further work?
1571 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1572 return;
1573
1574 // Attempt to salvage back through as many instructions as possible. Bail if
1575 // a non-instruction is seen, such as a constant expression or global
1576 // variable. FIXME: Further work could recover those too.
1577 while (isa<Instruction>(V)) {
1578 const Instruction &VAsInst = *cast<const Instruction>(V);
1579 // Temporary "0", awaiting real implementation.
1581 SmallVector<Value *, 4> AdditionalValues;
1582 V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1583 Expr->getNumLocationOperands(), Ops,
1584 AdditionalValues);
1585 // If we cannot salvage any further, and haven't yet found a suitable debug
1586 // expression, bail out.
1587 if (!V)
1588 break;
1589
1590 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1591 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1592 // here for variadic dbg_values, remove that condition.
1593 if (!AdditionalValues.empty())
1594 break;
1595
1596 // New value and expr now represent this debuginfo.
1597 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1598
1599 // Some kind of simplification occurred: check whether the operand of the
1600 // salvaged debug expression can be encoded in this DAG.
1601 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1602 LLVM_DEBUG(
1603 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1604 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1605 return;
1606 }
1607 }
1608
1609 // This was the final opportunity to salvage this debug information, and it
1610 // couldn't be done. Place a poison DBG_VALUE at this location to terminate
1611 // any earlier variable location.
1612 assert(OrigV && "V shouldn't be null");
1613 auto *Poison = PoisonValue::get(OrigV->getType());
1614 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Poison, DL, SDNodeOrder);
1615 DAG.AddDbgValue(SDV, false);
1616 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n "
1617 << printDDI(OrigV, DDI) << "\n");
1618}
1619
1621 DIExpression *Expr,
1622 DebugLoc DbgLoc,
1623 unsigned Order) {
1627 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1628 /*IsVariadic*/ false);
1629}
1630
1632 DILocalVariable *Var,
1633 DIExpression *Expr, DebugLoc DbgLoc,
1634 unsigned Order, bool IsVariadic) {
1635 if (Values.empty())
1636 return true;
1637
1638 // Filter EntryValue locations out early.
1639 if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1640 return true;
1641
1642 SmallVector<SDDbgOperand> LocationOps;
1643 SmallVector<SDNode *> Dependencies;
1644 for (const Value *V : Values) {
1645 // Constant value.
1648 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1649 continue;
1650 }
1651
1652 // Look through IntToPtr constants.
1653 if (auto *CE = dyn_cast<ConstantExpr>(V))
1654 if (CE->getOpcode() == Instruction::IntToPtr) {
1655 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1656 continue;
1657 }
1658
1659 // If the Value is a frame index, we can create a FrameIndex debug value
1660 // without relying on the DAG at all.
1661 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1662 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1663 if (SI != FuncInfo.StaticAllocaMap.end()) {
1664 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1665 continue;
1666 }
1667 }
1668
1669 // Do not use getValue() in here; we don't want to generate code at
1670 // this point if it hasn't been done yet.
1671 SDValue N = NodeMap[V];
1672 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1673 N = UnusedArgNodeMap[V];
1674
1675 if (N.getNode()) {
1676 // Only emit func arg dbg value for non-variadic dbg.values for now.
1677 if (!IsVariadic &&
1678 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1679 FuncArgumentDbgValueKind::Value, N))
1680 return true;
1681 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1682 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1683 // describe stack slot locations.
1684 //
1685 // Consider "int x = 0; int *px = &x;". There are two kinds of
1686 // interesting debug values here after optimization:
1687 //
1688 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1689 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1690 //
1691 // Both describe the direct values of their associated variables.
1692 Dependencies.push_back(N.getNode());
1693 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1694 continue;
1695 }
1696 LocationOps.emplace_back(
1697 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1698 continue;
1699 }
1700
1701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1702 // Special rules apply for the first dbg.values of parameter variables in a
1703 // function. Identify them by the fact they reference Argument Values, that
1704 // they're parameters, and they are parameters of the current function. We
1705 // need to let them dangle until they get an SDNode.
1706 bool IsParamOfFunc =
1707 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1708 if (IsParamOfFunc)
1709 return false;
1710
1711 // The value is not used in this block yet (or it would have an SDNode).
1712 // We still want the value to appear for the user if possible -- if it has
1713 // an associated VReg, we can refer to that instead.
1714 auto VMI = FuncInfo.ValueMap.find(V);
1715 if (VMI != FuncInfo.ValueMap.end()) {
1716 Register Reg = VMI->second;
1717 // If this is a PHI node, it may be split up into several MI PHI nodes
1718 // (in FunctionLoweringInfo::set).
1719 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1720 V->getType(), std::nullopt);
1721 if (RFV.occupiesMultipleRegs()) {
1722 // FIXME: We could potentially support variadic dbg_values here.
1723 if (IsVariadic)
1724 return false;
1725 unsigned Offset = 0;
1726 unsigned BitsToDescribe = 0;
1727 if (auto VarSize = Var->getSizeInBits())
1728 BitsToDescribe = *VarSize;
1729 if (auto Fragment = Expr->getFragmentInfo())
1730 BitsToDescribe = Fragment->SizeInBits;
1731 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1732 // Bail out if all bits are described already.
1733 if (Offset >= BitsToDescribe)
1734 break;
1735 // TODO: handle scalable vectors.
1736 unsigned RegisterSize = RegAndSize.second;
1737 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1738 ? BitsToDescribe - Offset
1739 : RegisterSize;
1740 auto FragmentExpr = DIExpression::createFragmentExpression(
1741 Expr, Offset, FragmentSize);
1742 if (!FragmentExpr)
1743 continue;
1744 SDDbgValue *SDV = DAG.getVRegDbgValue(
1745 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1746 DAG.AddDbgValue(SDV, false);
1747 Offset += RegisterSize;
1748 }
1749 return true;
1750 }
1751 // We can use simple vreg locations for variadic dbg_values as well.
1752 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1753 continue;
1754 }
1755 // We failed to create a SDDbgOperand for V.
1756 return false;
1757 }
1758
1759 // We have created a SDDbgOperand for each Value in Values.
1760 assert(!LocationOps.empty());
1761 SDDbgValue *SDV =
1762 DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1763 /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1764 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1765 return true;
1766}
1767
1769 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1770 for (auto &Pair : DanglingDebugInfoMap)
1771 for (auto &DDI : Pair.second)
1772 salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1774}
1775
1776/// getCopyFromRegs - If there was virtual register allocated for the value V
1777/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1779 auto It = FuncInfo.ValueMap.find(V);
1780 SDValue Result;
1781
1782 if (It != FuncInfo.ValueMap.end()) {
1783 Register InReg = It->second;
1784
1785 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1786 DAG.getDataLayout(), InReg, Ty,
1787 std::nullopt); // This is not an ABI copy.
1788 SDValue Chain = DAG.getEntryNode();
1789 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1790 V);
1791 resolveDanglingDebugInfo(V, Result);
1792 }
1793
1794 return Result;
1795}
1796
1797/// getValue - Return an SDValue for the given Value.
1799 // If we already have an SDValue for this value, use it. It's important
1800 // to do this first, so that we don't create a CopyFromReg if we already
1801 // have a regular SDValue.
1802 SDValue &N = NodeMap[V];
1803 if (N.getNode()) return N;
1804
1805 // If there's a virtual register allocated and initialized for this
1806 // value, use it.
1807 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1808 return copyFromReg;
1809
1810 // Otherwise create a new SDValue and remember it.
1811 SDValue Val = getValueImpl(V);
1812 NodeMap[V] = Val;
1814 return Val;
1815}
1816
1817void SelectionDAGBuilder::setValueToPoison(const Value *V, const SDLoc &dl) {
1818 if (V->getType()->isVoidTy())
1819 return;
1820
1821 SmallVector<EVT, 4> ValueVTs;
1822 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
1823 V->getType(), ValueVTs);
1824 setValue(V, DAG.getErrorMergeValues(ValueVTs, SDValue(), dl));
1825}
1826
1827/// getNonRegisterValue - Return an SDValue for the given Value, but
1828/// don't look in FuncInfo.ValueMap for a virtual register.
1830 // If we already have an SDValue for this value, use it.
1831 SDValue &N = NodeMap[V];
1832 if (N.getNode()) {
1833 if (isIntOrFPConstant(N)) {
1834 // Remove the debug location from the node as the node is about to be used
1835 // in a location which may differ from the original debug location. This
1836 // is relevant to Constant and ConstantFP nodes because they can appear
1837 // as constant expressions inside PHI nodes.
1838 N->setDebugLoc(DebugLoc());
1839 }
1840 return N;
1841 }
1842
1843 // Otherwise create a new SDValue and remember it.
1844 SDValue Val = getValueImpl(V);
1845 NodeMap[V] = Val;
1847 return Val;
1848}
1849
1850/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1851/// Create an SDValue for the given value.
1853 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1854
1855 if (const Constant *C = dyn_cast<Constant>(V)) {
1856 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1857
1858 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1859 SDLoc DL = getCurSDLoc();
1860
1861 // DAG.getConstant() may attempt to legalise the vector constant which can
1862 // significantly change the combines applied to the DAG. To reduce the
1863 // divergence when enabling ConstantInt based vectors we try to construct
1864 // the DAG in the same way as shufflevector based splats. TODO: The
1865 // divergence sometimes leads to better optimisations. Ideally we should
1866 // prevent DAG.getConstant() from legalising too early but there are some
1867 // degradations preventing this.
1868 if (VT.isScalableVector())
1869 return DAG.getNode(
1870 ISD::SPLAT_VECTOR, DL, VT,
1871 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1872 if (VT.isFixedLengthVector())
1873 return DAG.getSplatBuildVector(
1874 VT, DL,
1875 DAG.getConstant(CI->getValue(), DL, VT.getVectorElementType()));
1876 return DAG.getConstant(*CI, DL, VT);
1877 }
1878
1879 if (const ConstantByte *CB = dyn_cast<ConstantByte>(C))
1880 return DAG.getConstant(CB->getValue(), getCurSDLoc(), VT);
1881
1882 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1883 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1884
1885 if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1886 return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1887 getValue(CPA->getPointer()), getValue(CPA->getKey()),
1888 getValue(CPA->getAddrDiscriminator()),
1889 getValue(CPA->getDiscriminator()));
1890 }
1891
1893 return DAG.getConstant(0, getCurSDLoc(), VT);
1894
1895 if (match(C, m_VScale()))
1896 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1897
1898 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1899 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1900
1901 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1902 return isa<PoisonValue>(C) ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
1903
1904 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1905 visit(CE->getOpcode(), *CE);
1906 SDValue N1 = NodeMap[V];
1907 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1908 return N1;
1909 }
1910
1912 SmallVector<SDValue, 4> Constants;
1913 for (const Use &U : C->operands()) {
1914 SDNode *Val = getValue(U).getNode();
1915 // If the operand is an empty aggregate, there are no values.
1916 if (!Val) continue;
1917 // Add each leaf value from the operand to the Constants list
1918 // to form a flattened list of all the values.
1919 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1920 Constants.push_back(SDValue(Val, i));
1921 }
1922
1923 return DAG.getMergeValues(Constants, getCurSDLoc());
1924 }
1925
1926 if (const ConstantDataSequential *CDS =
1929 for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) {
1930 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1931 // Add each leaf value from the operand to the Constants list
1932 // to form a flattened list of all the values.
1933 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1934 Ops.push_back(SDValue(Val, i));
1935 }
1936
1937 if (isa<ArrayType>(CDS->getType()))
1938 return DAG.getMergeValues(Ops, getCurSDLoc());
1939 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1940 }
1941
1942 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1944 "Unknown struct or array constant!");
1945
1946 SmallVector<EVT, 4> ValueVTs;
1947 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1948 unsigned NumElts = ValueVTs.size();
1949 if (NumElts == 0)
1950 return SDValue(); // empty struct
1951 SmallVector<SDValue, 4> Constants(NumElts);
1952 for (unsigned i = 0; i != NumElts; ++i) {
1953 EVT EltVT = ValueVTs[i];
1954 if (isa<UndefValue>(C))
1955 Constants[i] = DAG.getUNDEF(EltVT);
1956 else if (EltVT.isFloatingPoint())
1957 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1958 else
1959 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1960 }
1961
1962 return DAG.getMergeValues(Constants, getCurSDLoc());
1963 }
1964
1965 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1966 return DAG.getBlockAddress(BA, VT);
1967
1968 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1969 return getValue(Equiv->getGlobalValue());
1970
1971 if (const auto *NC = dyn_cast<NoCFIValue>(C))
1972 return getValue(NC->getGlobalValue());
1973
1974 if (VT == MVT::aarch64svcount) {
1975 assert(C->isNullValue() && "Can only zero this target type!");
1976 return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1977 DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1978 }
1979
1980 if (VT.isRISCVVectorTuple()) {
1981 assert(C->isNullValue() && "Can only zero this target type!");
1982 return DAG.getNode(
1984 DAG.getNode(
1986 EVT::getVectorVT(*DAG.getContext(), MVT::i8,
1987 VT.getSizeInBits().getKnownMinValue() / 8, true),
1988 DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
1989 }
1990
1991 if (VT == MVT::externref || VT == MVT::funcref) {
1992 assert(C->isNullValue() && "Can only zero this target type!");
1993 // The zero value of a WebAssembly reference type is the null reference,
1994 // materialized with ref.null.
1995 Intrinsic::ID IID = VT == MVT::externref ? Intrinsic::wasm_ref_null_extern
1996 : Intrinsic::wasm_ref_null_func;
1997 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VT,
1998 DAG.getTargetConstant(IID, getCurSDLoc(), MVT::i32));
1999 }
2000
2001 VectorType *VecTy = cast<VectorType>(V->getType());
2002
2003 // Now that we know the number and type of the elements, get that number of
2004 // elements into the Ops array based on what kind of constant it is.
2005 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
2007 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
2008 for (unsigned i = 0; i != NumElements; ++i)
2009 Ops.push_back(getValue(CV->getOperand(i)));
2010
2011 return DAG.getBuildVector(VT, getCurSDLoc(), Ops);
2012 }
2013
2015 EVT EltVT =
2016 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
2017
2018 SDValue Op;
2019 if (EltVT.isFloatingPoint())
2020 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
2021 else
2022 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
2023
2024 return DAG.getSplat(VT, getCurSDLoc(), Op);
2025 }
2026
2027 llvm_unreachable("Unknown vector constant");
2028 }
2029
2030 // If this is a static alloca, generate it as the frameindex instead of
2031 // computation.
2032 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
2033 auto SI = FuncInfo.StaticAllocaMap.find(AI);
2034 if (SI != FuncInfo.StaticAllocaMap.end())
2035 return DAG.getFrameIndex(
2036 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
2037 }
2038
2039 // If this is an instruction which fast-isel has deferred, select it now.
2040 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2041 Register InReg = FuncInfo.InitializeRegForValue(Inst);
2042 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
2043 Inst->getType(), std::nullopt);
2044 SDValue Chain = DAG.getEntryNode();
2045 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
2046 }
2047
2048 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
2049 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
2050
2051 if (const auto *BB = dyn_cast<BasicBlock>(V))
2052 return DAG.getBasicBlock(FuncInfo.getMBB(BB));
2053
2054 llvm_unreachable("Can't get register for value!");
2055}
2056
2057void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
2059 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
2060 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
2061 bool IsSEH = isAsynchronousEHPersonality(Pers);
2062 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
2063 if (IsSEH) {
2064 // For SEH, EHCont Guard needs to know that this catchpad is a target.
2065 CatchPadMBB->setIsEHContTarget(true);
2067 } else
2068 CatchPadMBB->setIsEHScopeEntry();
2069 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
2070 if (IsMSVCCXX || IsCoreCLR)
2071 CatchPadMBB->setIsEHFuncletEntry();
2072}
2073
2074void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
2075 // Update machine-CFG edge.
2076 MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
2077 FuncInfo.MBB->addSuccessor(TargetMBB);
2078
2079 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2080 bool IsSEH = isAsynchronousEHPersonality(Pers);
2081 if (IsSEH) {
2082 // If this is not a fall-through branch or optimizations are switched off,
2083 // emit the branch.
2084 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
2085 TM.getOptLevel() == CodeGenOptLevel::None)
2086 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2087 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
2088 return;
2089 }
2090
2091 // For non-SEH, EHCont Guard needs to know that this catchret is a target.
2092 TargetMBB->setIsEHContTarget(true);
2093 DAG.getMachineFunction().setHasEHContTarget(true);
2094
2095 // Figure out the funclet membership for the catchret's successor.
2096 // This will be used by the FuncletLayout pass to determine how to order the
2097 // BB's.
2098 // A 'catchret' returns to the outer scope's color.
2099 Value *ParentPad = I.getCatchSwitchParentPad();
2100 const BasicBlock *SuccessorColor;
2101 if (isa<ConstantTokenNone>(ParentPad))
2102 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2103 else
2104 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2105 assert(SuccessorColor && "No parent funclet for catchret!");
2106 MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2107 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2108
2109 // Create the terminator node.
2110 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2111 getControlRoot(), DAG.getBasicBlock(TargetMBB),
2112 DAG.getBasicBlock(SuccessorColorMBB));
2113 DAG.setRoot(Ret);
2114}
2115
2116void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2117 // Don't emit any special code for the cleanuppad instruction. It just marks
2118 // the start of an EH scope/funclet.
2119 FuncInfo.MBB->setIsEHScopeEntry();
2120 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2121 if (Pers != EHPersonality::Wasm_CXX) {
2122 FuncInfo.MBB->setIsEHFuncletEntry();
2123 FuncInfo.MBB->setIsCleanupFuncletEntry();
2124 }
2125}
2126
2127/// When an invoke or a cleanupret unwinds to the next EH pad, there are
2128/// many places it could ultimately go. In the IR, we have a single unwind
2129/// destination, but in the machine CFG, we enumerate all the possible blocks.
2130/// This function skips over imaginary basic blocks that hold catchswitch
2131/// instructions, and finds all the "real" machine
2132/// basic block destinations. As those destinations may not be successors of
2133/// EHPadBB, here we also calculate the edge probability to those destinations.
2134/// The passed-in Prob is the edge probability to EHPadBB.
2136 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2137 BranchProbability Prob,
2138 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2139 &UnwindDests) {
2140 EHPersonality Personality =
2142 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2143 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2144 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2145 bool IsSEH = isAsynchronousEHPersonality(Personality);
2146
2147 while (EHPadBB) {
2149 BasicBlock *NewEHPadBB = nullptr;
2150 if (isa<LandingPadInst>(Pad)) {
2151 // Stop on landingpads. They are not funclets.
2152 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2153 break;
2154 } else if (isa<CleanupPadInst>(Pad)) {
2155 // Stop on cleanup pads. Cleanups are always funclet entries for all known
2156 // personalities except Wasm. And in Wasm this becomes a catch_all(_ref),
2157 // which always catches an exception.
2158 UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2159 UnwindDests.back().first->setIsEHScopeEntry();
2160 // In Wasm, EH scopes are not funclets
2161 if (!IsWasmCXX)
2162 UnwindDests.back().first->setIsEHFuncletEntry();
2163 break;
2164 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2165 // Add the catchpad handlers to the possible destinations.
2166 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2167 UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2168 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2169 if (IsMSVCCXX || IsCoreCLR)
2170 UnwindDests.back().first->setIsEHFuncletEntry();
2171 if (!IsSEH)
2172 UnwindDests.back().first->setIsEHScopeEntry();
2173 }
2174 NewEHPadBB = CatchSwitch->getUnwindDest();
2175 } else {
2176 continue;
2177 }
2178
2179 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2180 if (BPI && NewEHPadBB)
2181 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2182 EHPadBB = NewEHPadBB;
2183 }
2184}
2185
2186void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2187 // Update successor info.
2189 auto UnwindDest = I.getUnwindDest();
2190 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2191 BranchProbability UnwindDestProb =
2192 (BPI && UnwindDest)
2193 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2195 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2196 for (auto &UnwindDest : UnwindDests) {
2197 UnwindDest.first->setIsEHPad();
2198 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2199 }
2200 FuncInfo.MBB->normalizeSuccProbs();
2201
2202 // Create the terminator node.
2203 MachineBasicBlock *CleanupPadMBB =
2204 FuncInfo.getMBB(I.getCleanupPad()->getParent());
2205 SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2206 getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2207 DAG.setRoot(Ret);
2208}
2209
2210void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2211 report_fatal_error("visitCatchSwitch not yet implemented!");
2212}
2213
2214void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2215 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2216 auto &DL = DAG.getDataLayout();
2217 SDValue Chain = getControlRoot();
2220
2221 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2222 // lower
2223 //
2224 // %val = call <ty> @llvm.experimental.deoptimize()
2225 // ret <ty> %val
2226 //
2227 // differently.
2228 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2230 return;
2231 }
2232
2233 if (!FuncInfo.CanLowerReturn) {
2234 Register DemoteReg = FuncInfo.DemoteRegister;
2235
2236 // Emit a store of the return value through the virtual register.
2237 // Leave Outs empty so that LowerReturn won't try to load return
2238 // registers the usual way.
2239 MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2240 SDValue RetPtr =
2241 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2242 Type *RetTy = I.getOperand(0)->getType();
2243 Align BaseAlign = DL.getPrefTypeAlign(RetTy);
2244 RetPtr =
2245 TLI.annotateStackObjectPointer(RetPtr, DAG, getCurSDLoc(), BaseAlign);
2246 SDValue RetOp = getValue(I.getOperand(0));
2247
2248 SmallVector<EVT, 4> ValueVTs, MemVTs;
2249 SmallVector<uint64_t, 4> Offsets;
2250 ComputeValueVTs(TLI, DL, RetTy, ValueVTs, &MemVTs, &Offsets, 0);
2251 unsigned NumValues = ValueVTs.size();
2252
2253 SmallVector<SDValue, 4> Chains(NumValues);
2254 for (unsigned i = 0; i != NumValues; ++i) {
2255 // An aggregate return value cannot wrap around the address space, so
2256 // offsets to its parts don't wrap either.
2257 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2258 TypeSize::getFixed(Offsets[i]));
2259
2260 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2261 if (MemVTs[i] != ValueVTs[i])
2262 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2263 Chains[i] = DAG.getStore(
2264 Chain, getCurSDLoc(), Val,
2265 // FIXME: better loc info would be nice.
2266 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2267 commonAlignment(BaseAlign, Offsets[i]));
2268 }
2269
2270 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2271 MVT::Other, Chains);
2272 } else if (I.getNumOperands() != 0) {
2274 ComputeValueTypes(DL, I.getOperand(0)->getType(), Types);
2275 unsigned NumValues = Types.size();
2276 if (NumValues) {
2277 SDValue RetOp = getValue(I.getOperand(0));
2278
2279 const Function *F = I.getParent()->getParent();
2280
2281 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2282 I.getOperand(0)->getType(), F->getCallingConv(),
2283 /*IsVarArg*/ false, DL);
2284
2285 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2286 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2287 ExtendKind = ISD::SIGN_EXTEND;
2288 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2289 ExtendKind = ISD::ZERO_EXTEND;
2290
2291 LLVMContext &Context = F->getContext();
2292 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2293
2294 for (unsigned j = 0; j != NumValues; ++j) {
2295 EVT VT = TLI.getValueType(DL, Types[j]);
2296
2297 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2298 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2299
2300 CallingConv::ID CC = F->getCallingConv();
2301
2302 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2303 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2304 SmallVector<SDValue, 4> Parts(NumParts);
2306 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2307 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2308
2309 // 'inreg' on function refers to return value
2310 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2311 if (RetInReg)
2312 Flags.setInReg();
2313
2314 if (I.getOperand(0)->getType()->isPointerTy()) {
2315 Flags.setPointer();
2316 Flags.setPointerAddrSpace(
2317 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2318 }
2319
2320 if (NeedsRegBlock) {
2321 Flags.setInConsecutiveRegs();
2322 if (j == NumValues - 1)
2323 Flags.setInConsecutiveRegsLast();
2324 }
2325
2326 // Propagate extension type if any
2327 if (ExtendKind == ISD::SIGN_EXTEND)
2328 Flags.setSExt();
2329 else if (ExtendKind == ISD::ZERO_EXTEND)
2330 Flags.setZExt();
2331 else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2332 Flags.setNoExt();
2333
2334 for (unsigned i = 0; i < NumParts; ++i) {
2335 Outs.push_back(ISD::OutputArg(Flags,
2336 Parts[i].getValueType().getSimpleVT(),
2337 VT, Types[j], 0, 0));
2338 OutVals.push_back(Parts[i]);
2339 }
2340 }
2341 }
2342 }
2343
2344 // Push in swifterror virtual register as the last element of Outs. This makes
2345 // sure swifterror virtual register will be returned in the swifterror
2346 // physical register.
2347 const Function *F = I.getParent()->getParent();
2348 if (TLI.supportSwiftError() &&
2349 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2350 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2351 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2352 Flags.setSwiftError();
2353 Outs.push_back(ISD::OutputArg(Flags, /*vt=*/TLI.getPointerTy(DL),
2354 /*argvt=*/EVT(TLI.getPointerTy(DL)),
2355 PointerType::getUnqual(*DAG.getContext()),
2356 /*origidx=*/1, /*partOffs=*/0));
2357 // Create SDNode for the swifterror virtual register.
2358 OutVals.push_back(
2359 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2360 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2361 EVT(TLI.getPointerTy(DL))));
2362 }
2363
2364 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2365 CallingConv::ID CallConv =
2366 DAG.getMachineFunction().getFunction().getCallingConv();
2367 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2368 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2369
2370 // Verify that the target's LowerReturn behaved as expected.
2371 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2372 "LowerReturn didn't return a valid chain!");
2373
2374 // Update the DAG with the new chain value resulting from return lowering.
2375 DAG.setRoot(Chain);
2376}
2377
2378/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2379/// created for it, emit nodes to copy the value into the virtual
2380/// registers.
2382 // Skip empty types
2383 if (V->getType()->isEmptyTy())
2384 return;
2385
2386 auto VMI = FuncInfo.ValueMap.find(V);
2387 if (VMI != FuncInfo.ValueMap.end()) {
2388 assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2389 "Unused value assigned virtual registers!");
2390 CopyValueToVirtualRegister(V, VMI->second);
2391 }
2392}
2393
2394/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2395/// the current basic block, add it to ValueMap now so that we'll get a
2396/// CopyTo/FromReg.
2398 // No need to export constants.
2399 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2400
2401 // Already exported?
2402 if (FuncInfo.isExportedInst(V)) return;
2403
2404 Register Reg = FuncInfo.InitializeRegForValue(V);
2406}
2407
2409 const BasicBlock *FromBB) {
2410 // The operands of the setcc have to be in this block. We don't know
2411 // how to export them from some other block.
2412 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2413 // Can export from current BB.
2414 if (VI->getParent() == FromBB)
2415 return true;
2416
2417 // Is already exported, noop.
2418 return FuncInfo.isExportedInst(V);
2419 }
2420
2421 // If this is an argument, we can export it if the BB is the entry block or
2422 // if it is already exported.
2423 if (isa<Argument>(V)) {
2424 if (FromBB->isEntryBlock())
2425 return true;
2426
2427 // Otherwise, can only export this if it is already exported.
2428 return FuncInfo.isExportedInst(V);
2429 }
2430
2431 // Otherwise, constants can always be exported.
2432 return true;
2433}
2434
2435/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2437SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2438 const MachineBasicBlock *Dst) const {
2440 const BasicBlock *SrcBB = Src->getBasicBlock();
2441 const BasicBlock *DstBB = Dst->getBasicBlock();
2442 if (!BPI) {
2443 // If BPI is not available, set the default probability as 1 / N, where N is
2444 // the number of successors.
2445 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2446 return BranchProbability(1, SuccSize);
2447 }
2448 return BPI->getEdgeProbability(SrcBB, DstBB);
2449}
2450
2451void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2452 MachineBasicBlock *Dst,
2453 BranchProbability Prob) {
2454 if (!FuncInfo.BPI)
2455 Src->addSuccessorWithoutProb(Dst);
2456 else {
2457 if (Prob.isUnknown())
2458 Prob = getEdgeProbability(Src, Dst);
2459 Src->addSuccessor(Dst, Prob);
2460 }
2461}
2462
2463static bool InBlock(const Value *V, const BasicBlock *BB) {
2464 if (const Instruction *I = dyn_cast<Instruction>(V))
2465 return I->getParent() == BB;
2466 return true;
2467}
2468
2469/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2470/// This function emits a branch and is used at the leaves of an OR or an
2471/// AND operator tree.
2472void
2475 MachineBasicBlock *FBB,
2476 MachineBasicBlock *CurBB,
2477 MachineBasicBlock *SwitchBB,
2478 BranchProbability TProb,
2479 BranchProbability FProb,
2480 bool InvertCond) {
2481 const BasicBlock *BB = CurBB->getBasicBlock();
2482
2483 // If the leaf of the tree is a comparison, merge the condition into
2484 // the caseblock.
2485 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2486 // The operands of the cmp have to be in this block. We don't know
2487 // how to export them from some other block. If this is the first block
2488 // of the sequence, no exporting is needed.
2489 if (CurBB == SwitchBB ||
2490 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2491 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2492 ISD::CondCode Condition;
2493 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2494 ICmpInst::Predicate Pred =
2495 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2496 Condition = getICmpCondCode(Pred);
2497 } else {
2498 const FCmpInst *FC = cast<FCmpInst>(Cond);
2499 FCmpInst::Predicate Pred =
2500 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2501 Condition = getFCmpCondCode(Pred);
2502 if (FC->hasNoNaNs() ||
2503 (isKnownNeverNaN(FC->getOperand(0),
2504 SimplifyQuery(DAG.getDataLayout(), FC)) &&
2505 isKnownNeverNaN(FC->getOperand(1),
2506 SimplifyQuery(DAG.getDataLayout(), FC))))
2507 Condition = getFCmpCodeWithoutNaN(Condition);
2508 }
2509
2510 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2511 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2512 SL->SwitchCases.push_back(CB);
2513 return;
2514 }
2515 }
2516
2517 // Create a CaseBlock record representing this branch.
2518 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2519 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2520 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2521 SL->SwitchCases.push_back(CB);
2522}
2523
2524// Collect dependencies on V recursively. This is used for the cost analysis in
2525// `shouldKeepJumpConditionsTogether`.
2529 unsigned Depth = 0) {
2530 // Return false if we have an incomplete count.
2532 return false;
2533
2534 auto *I = dyn_cast<Instruction>(V);
2535 if (I == nullptr)
2536 return true;
2537
2538 if (Necessary != nullptr) {
2539 // This instruction is necessary for the other side of the condition so
2540 // don't count it.
2541 if (Necessary->contains(I))
2542 return true;
2543 }
2544
2545 // Already added this dep.
2546 if (!Deps->try_emplace(I, false).second)
2547 return true;
2548
2549 for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2550 if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2551 Depth + 1))
2552 return false;
2553 return true;
2554}
2555
2558 Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2560 if (Params.BaseCost < 0)
2561 return false;
2562
2563 // Baseline cost.
2564 InstructionCost CostThresh = Params.BaseCost;
2565
2566 BranchProbabilityInfo *BPI = nullptr;
2567 if (Params.LikelyBias || Params.UnlikelyBias)
2568 BPI = FuncInfo.BPI;
2569 if (BPI != nullptr) {
2570 // See if we are either likely to get an early out or compute both lhs/rhs
2571 // of the condition.
2572 BasicBlock *IfFalse = I.getSuccessor(0);
2573 BasicBlock *IfTrue = I.getSuccessor(1);
2574
2575 std::optional<bool> Likely;
2576 if (BPI->isEdgeHot(I.getParent(), IfTrue))
2577 Likely = true;
2578 else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2579 Likely = false;
2580
2581 if (Likely) {
2582 if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2583 // Its likely we will have to compute both lhs and rhs of condition
2584 CostThresh += Params.LikelyBias;
2585 else {
2586 if (Params.UnlikelyBias < 0)
2587 return false;
2588 // Its likely we will get an early out.
2589 CostThresh -= Params.UnlikelyBias;
2590 }
2591 }
2592 }
2593
2594 if (CostThresh <= 0)
2595 return false;
2596
2597 // Collect "all" instructions that lhs condition is dependent on.
2598 // Use map for stable iteration (to avoid non-determanism of iteration of
2599 // SmallPtrSet). The `bool` value is just a dummy.
2601 collectInstructionDeps(&LhsDeps, Lhs);
2602 // Collect "all" instructions that rhs condition is dependent on AND are
2603 // dependencies of lhs. This gives us an estimate on which instructions we
2604 // stand to save by splitting the condition.
2605 if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2606 return false;
2607 // Add the compare instruction itself unless its a dependency on the LHS.
2608 if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2609 if (!LhsDeps.contains(RhsI))
2610 RhsDeps.try_emplace(RhsI, false);
2611
2612 InstructionCost CostOfIncluding = 0;
2613 // See if this instruction will need to computed independently of whether RHS
2614 // is.
2615 Value *BrCond = I.getCondition();
2616 auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2617 for (const auto *U : Ins->users()) {
2618 // If user is independent of RHS calculation we don't need to count it.
2619 if (auto *UIns = dyn_cast<Instruction>(U))
2620 if (UIns != BrCond && !RhsDeps.contains(UIns))
2621 return false;
2622 }
2623 return true;
2624 };
2625
2626 // Prune instructions from RHS Deps that are dependencies of unrelated
2627 // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2628 // arbitrary and just meant to cap the how much time we spend in the pruning
2629 // loop. Its highly unlikely to come into affect.
2630 const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2631 // Stop after a certain point. No incorrectness from including too many
2632 // instructions.
2633 for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2634 const Instruction *ToDrop = nullptr;
2635 for (const auto &InsPair : RhsDeps) {
2636 if (!ShouldCountInsn(InsPair.first)) {
2637 ToDrop = InsPair.first;
2638 break;
2639 }
2640 }
2641 if (ToDrop == nullptr)
2642 break;
2643 RhsDeps.erase(ToDrop);
2644 }
2645
2646 for (const auto &InsPair : RhsDeps) {
2647 // Finally accumulate latency that we can only attribute to computing the
2648 // RHS condition. Use latency because we are essentially trying to calculate
2649 // the cost of the dependency chain.
2650 // Possible TODO: We could try to estimate ILP and make this more precise.
2651 CostOfIncluding += TTI->getInstructionCost(
2652 InsPair.first, TargetTransformInfo::TCK_Latency);
2653
2654 if (CostOfIncluding > CostThresh)
2655 return false;
2656 }
2657 return true;
2658}
2659
2662 MachineBasicBlock *FBB,
2663 MachineBasicBlock *CurBB,
2664 MachineBasicBlock *SwitchBB,
2666 BranchProbability TProb,
2667 BranchProbability FProb,
2668 bool InvertCond) {
2669 // Skip over not part of the tree and remember to invert op and operands at
2670 // next level.
2671 Value *NotCond;
2672 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2673 InBlock(NotCond, CurBB->getBasicBlock())) {
2674 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2675 !InvertCond);
2676 return;
2677 }
2678
2680 const Value *BOpOp0, *BOpOp1;
2681 // Compute the effective opcode for Cond, taking into account whether it needs
2682 // to be inverted, e.g.
2683 // and (not (or A, B)), C
2684 // gets lowered as
2685 // and (and (not A, not B), C)
2687 if (BOp) {
2688 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2689 ? Instruction::And
2690 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2691 ? Instruction::Or
2693 if (InvertCond) {
2694 if (BOpc == Instruction::And)
2695 BOpc = Instruction::Or;
2696 else if (BOpc == Instruction::Or)
2697 BOpc = Instruction::And;
2698 }
2699 }
2700
2701 // If this node is not part of the or/and tree, emit it as a branch.
2702 // Note that all nodes in the tree should have same opcode.
2703 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2704 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2705 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2706 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2707 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2708 TProb, FProb, InvertCond);
2709 return;
2710 }
2711
2712 // Create TmpBB after CurBB.
2713 MachineFunction::iterator BBI(CurBB);
2714 MachineFunction &MF = DAG.getMachineFunction();
2716 CurBB->getParent()->insert(++BBI, TmpBB);
2717
2718 if (Opc == Instruction::Or) {
2719 // Codegen X | Y as:
2720 // BB1:
2721 // jmp_if_X TBB
2722 // jmp TmpBB
2723 // TmpBB:
2724 // jmp_if_Y TBB
2725 // jmp FBB
2726 //
2727
2728 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2729 // The requirement is that
2730 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2731 // = TrueProb for original BB.
2732 // Assuming the original probabilities are A and B, one choice is to set
2733 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2734 // A/(1+B) and 2B/(1+B). This choice assumes that
2735 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2736 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2737 // TmpBB, but the math is more complicated.
2738
2739 auto NewTrueProb = TProb / 2;
2740 auto NewFalseProb = TProb / 2 + FProb;
2741 // Emit the LHS condition.
2742 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2743 NewFalseProb, InvertCond);
2744
2745 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2746 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2748 // Emit the RHS condition into TmpBB.
2749 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2750 Probs[1], InvertCond);
2751 } else {
2752 assert(Opc == Instruction::And && "Unknown merge op!");
2753 // Codegen X & Y as:
2754 // BB1:
2755 // jmp_if_X TmpBB
2756 // jmp FBB
2757 // TmpBB:
2758 // jmp_if_Y TBB
2759 // jmp FBB
2760 //
2761 // This requires creation of TmpBB after CurBB.
2762
2763 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2764 // The requirement is that
2765 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2766 // = FalseProb for original BB.
2767 // Assuming the original probabilities are A and B, one choice is to set
2768 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2769 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2770 // TrueProb for BB1 * FalseProb for TmpBB.
2771
2772 auto NewTrueProb = TProb + FProb / 2;
2773 auto NewFalseProb = FProb / 2;
2774 // Emit the LHS condition.
2775 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2776 NewFalseProb, InvertCond);
2777
2778 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2779 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2781 // Emit the RHS condition into TmpBB.
2782 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2783 Probs[1], InvertCond);
2784 }
2785}
2786
2787/// If the set of cases should be emitted as a series of branches, return true.
2788/// If we should emit this as a bunch of and/or'd together conditions, return
2789/// false.
2790bool
2791SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2792 if (Cases.size() != 2) return true;
2793
2794 // If this is two comparisons of the same values or'd or and'd together, they
2795 // will get folded into a single comparison, so don't emit two blocks.
2796 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2797 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2798 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2799 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2800 return false;
2801 }
2802
2803 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2804 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2805 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2806 Cases[0].CC == Cases[1].CC &&
2807 isa<Constant>(Cases[0].CmpRHS) &&
2808 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2809 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2810 return false;
2811 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2812 return false;
2813 }
2814
2815 return true;
2816}
2817
2818void SelectionDAGBuilder::visitUncondBr(const UncondBrInst &I) {
2820
2821 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2822
2823 // Update machine-CFG edges.
2824 BrMBB->addSuccessor(Succ0MBB);
2825
2826 // If this is not a fall-through branch or optimizations are switched off,
2827 // emit the branch.
2828 if (Succ0MBB != NextBlock(BrMBB) ||
2830 auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2831 DAG.getBasicBlock(Succ0MBB));
2832 setValue(&I, Br);
2833 DAG.setRoot(Br);
2834 }
2835}
2836
2837void SelectionDAGBuilder::visitCondBr(const CondBrInst &I) {
2838 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2839
2840 MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2841
2842 // If this condition is one of the special cases we handle, do special stuff
2843 // now.
2844 const Value *CondVal = I.getCondition();
2845 MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2846
2847 // If this is a series of conditions that are or'd or and'd together, emit
2848 // this as a sequence of branches instead of setcc's with and/or operations.
2849 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2850 // unpredictable branches, and vector extracts because those jumps are likely
2851 // expensive for any target), this should improve performance.
2852 // For example, instead of something like:
2853 // cmp A, B
2854 // C = seteq
2855 // cmp D, E
2856 // F = setle
2857 // or C, F
2858 // jnz foo
2859 // Emit:
2860 // cmp A, B
2861 // je foo
2862 // cmp D, E
2863 // jle foo
2864 bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2865 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2866 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2867 BOp->hasOneUse() && !IsUnpredictable) {
2868 Value *Vec;
2869 const Value *BOp0, *BOp1;
2871 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2872 Opcode = Instruction::And;
2873 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2874 Opcode = Instruction::Or;
2875
2876 if (Opcode &&
2877 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2878 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2880 FuncInfo, I, Opcode, BOp0, BOp1,
2881 DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2882 Opcode, BOp0, BOp1, FuncInfo.Fn))) {
2883 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2884 getEdgeProbability(BrMBB, Succ0MBB),
2885 getEdgeProbability(BrMBB, Succ1MBB),
2886 /*InvertCond=*/false);
2887 // If the compares in later blocks need to use values not currently
2888 // exported from this block, export them now. This block should always
2889 // be the first entry.
2890 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2891
2892 // Allow some cases to be rejected.
2893 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2894 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2895 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2896 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2897 }
2898
2899 // Emit the branch for this block.
2900 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2901 SL->SwitchCases.erase(SL->SwitchCases.begin());
2902 return;
2903 }
2904
2905 // Okay, we decided not to do this, remove any inserted MBB's and clear
2906 // SwitchCases.
2907 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2908 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2909
2910 SL->SwitchCases.clear();
2911 }
2912 }
2913
2914 // Create a CaseBlock record representing this branch.
2915 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2916 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2918 IsUnpredictable);
2919
2920 // Use visitSwitchCase to actually insert the fast branch sequence for this
2921 // cond branch.
2922 visitSwitchCase(CB, BrMBB);
2923}
2924
2925/// visitSwitchCase - Emits the necessary code to represent a single node in
2926/// the binary search tree resulting from lowering a switch instruction.
2928 MachineBasicBlock *SwitchBB) {
2929 SDValue Cond;
2930 SDValue CondLHS = getValue(CB.CmpLHS);
2931 SDLoc dl = CB.DL;
2932
2933 if (CB.CC == ISD::SETTRUE) {
2934 // Branch or fall through to TrueBB.
2935 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2936 SwitchBB->normalizeSuccProbs();
2937 if (CB.TrueBB != NextBlock(SwitchBB)) {
2938 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2939 DAG.getBasicBlock(CB.TrueBB)));
2940 }
2941 return;
2942 }
2943
2944 auto &TLI = DAG.getTargetLoweringInfo();
2945 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2946
2947 // Build the setcc now.
2948 if (!CB.CmpMHS) {
2949 // Fold "(X == true)" to X and "(X == false)" to !X to
2950 // handle common cases produced by branch lowering.
2951 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2952 CB.CC == ISD::SETEQ)
2953 Cond = CondLHS;
2954 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2955 CB.CC == ISD::SETEQ) {
2956 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2957 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2958 } else {
2959 SDValue CondRHS = getValue(CB.CmpRHS);
2960
2961 // If a pointer's DAG type is larger than its memory type then the DAG
2962 // values are zero-extended. This breaks signed comparisons so truncate
2963 // back to the underlying type before doing the compare.
2964 if (CondLHS.getValueType() != MemVT) {
2965 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2966 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2967 }
2968 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2969 }
2970 } else {
2971 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2972
2973 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2974 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2975
2976 SDValue CmpOp = getValue(CB.CmpMHS);
2977 EVT VT = CmpOp.getValueType();
2978
2979 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2980 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2981 ISD::SETLE);
2982 } else {
2983 SDValue SUB = DAG.getNode(ISD::SUB, dl,
2984 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2985 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2986 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2987 }
2988 }
2989
2990 // Update successor info
2991 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2992 // TrueBB and FalseBB are always different unless the incoming IR is
2993 // degenerate. This only happens when running llc on weird IR.
2994 if (CB.TrueBB != CB.FalseBB)
2995 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2996 SwitchBB->normalizeSuccProbs();
2997
2998 // If the lhs block is the next block, invert the condition so that we can
2999 // fall through to the lhs instead of the rhs block.
3000 if (CB.TrueBB == NextBlock(SwitchBB)) {
3001 std::swap(CB.TrueBB, CB.FalseBB);
3002 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
3003 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
3004 }
3005
3006 SDNodeFlags Flags;
3008 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3009 Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
3010
3011 setValue(CurInst, BrCond);
3012
3013 // Insert the false branch. Do this even if it's a fall through branch,
3014 // this makes it easier to do DAG optimizations which require inverting
3015 // the branch condition.
3016 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3017 DAG.getBasicBlock(CB.FalseBB));
3018
3019 DAG.setRoot(BrCond);
3020}
3021
3022/// visitJumpTable - Emit JumpTable node in the current MBB
3024 // Emit the code for the jump table
3025 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3026 assert(JT.Reg && "Should lower JT Header first!");
3027 EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
3028 SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
3029 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
3030 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
3031 Index.getValue(1), Table, Index);
3032 DAG.setRoot(BrJumpTable);
3033}
3034
3035/// visitJumpTableHeader - This function emits necessary code to produce index
3036/// in the JumpTable from switch case.
3038 JumpTableHeader &JTH,
3039 MachineBasicBlock *SwitchBB) {
3040 assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3041 const SDLoc &dl = *JT.SL;
3042
3043 // Subtract the lowest switch case value from the value being switched on.
3044 SDValue SwitchOp = getValue(JTH.SValue);
3045 EVT VT = SwitchOp.getValueType();
3046 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3047 DAG.getConstant(JTH.First, dl, VT));
3048
3049 // The SDNode we just created, which holds the value being switched on minus
3050 // the smallest case value, needs to be copied to a virtual register so it
3051 // can be used as an index into the jump table in a subsequent basic block.
3052 // This value may be smaller or larger than the target's pointer type, and
3053 // therefore require extension or truncating.
3054 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3055 SwitchOp =
3056 DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3057
3058 Register JumpTableReg =
3059 FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3060 SDValue CopyTo =
3061 DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3062 JT.Reg = JumpTableReg;
3063
3064 if (!JTH.FallthroughUnreachable) {
3065 // Emit the range check for the jump table, and branch to the default block
3066 // for the switch statement if the value being switched on exceeds the
3067 // largest case in the switch.
3068 SDValue CMP = DAG.getSetCC(
3069 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3070 Sub.getValueType()),
3071 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3072
3073 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3074 MVT::Other, CopyTo, CMP,
3075 DAG.getBasicBlock(JT.Default));
3076
3077 // Avoid emitting unnecessary branches to the next block.
3078 if (JT.MBB != NextBlock(SwitchBB))
3079 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3080 DAG.getBasicBlock(JT.MBB));
3081
3082 DAG.setRoot(BrCond);
3083 } else {
3084 // Avoid emitting unnecessary branches to the next block.
3085 if (JT.MBB != NextBlock(SwitchBB))
3086 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3087 DAG.getBasicBlock(JT.MBB)));
3088 else
3089 DAG.setRoot(CopyTo);
3090 }
3091}
3092
3093/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3094/// variable if there exists one.
3096 SDValue &Chain) {
3097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3098 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3099 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3101 Value *Global =
3104 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3105 if (Global) {
3106 MachinePointerInfo MPInfo(Global);
3110 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
3111 DAG.setNodeMemRefs(Node, {MemRef});
3112 }
3113 if (PtrTy != PtrMemTy)
3114 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3115 return SDValue(Node, 0);
3116}
3117
3118/// Codegen a new tail for a stack protector check ParentMBB which has had its
3119/// tail spliced into a stack protector check success bb.
3120///
3121/// For a high level explanation of how this fits into the stack protector
3122/// generation see the comment on the declaration of class
3123/// StackProtectorDescriptor.
3125 MachineBasicBlock *ParentBB) {
3126
3127 // First create the loads to the guard/stack slot for the comparison.
3128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3129 auto &DL = DAG.getDataLayout();
3130 EVT PtrTy = TLI.getFrameIndexTy(DL);
3131 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3132
3133 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3134 int FI = MFI.getStackProtectorIndex();
3135
3136 SDValue Guard;
3137 SDLoc dl = getCurSDLoc();
3138 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3139 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3140 Align Align = DL.getPrefTypeAlign(
3141 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3142
3143 // Generate code to load the content of the guard slot.
3144 SDValue GuardVal = DAG.getLoad(
3145 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3146 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3148
3149 // If cookie mixing is enabled, unmix the stored GuardVal to get back the
3150 // original cookie for comparison. The prologue stored (FP - Cookie) or
3151 // (FP XOR Cookie), so we apply the same operation again to unmix:
3152 // FP - (FP - Cookie) = Cookie, or (FP XOR Cookie) XOR FP = Cookie.
3153 if (TLI.useStackGuardMixFP())
3154 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3155
3156 // If we're using function-based instrumentation, call the guard check
3157 // function
3159 // Get the guard check function from the target and verify it exists since
3160 // we're using function-based instrumentation
3161 const Function *GuardCheckFn =
3162 TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3163 assert(GuardCheckFn && "Guard check function is null");
3164
3165 // The target provides a guard check function to validate the guard value.
3166 // Generate a call to that function with the content of the guard slot as
3167 // argument.
3168 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3169 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3170
3172 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3173 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3174 Entry.IsInReg = true;
3175 Args.push_back(Entry);
3176
3179 .setChain(DAG.getEntryNode())
3180 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3181 getValue(GuardCheckFn), std::move(Args));
3182
3183 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3184 DAG.setRoot(Result.second);
3185 return;
3186 }
3187
3188 // Load the fresh guard value for comparison.
3189 // For targets that mix the cookie in LOAD_STACK_GUARD expansion, we need to
3190 // load directly without using LOAD_STACK_GUARD to avoid unwanted mixing.
3191 SDValue Chain = DAG.getEntryNode();
3192 if (TLI.useStackGuardMixFP()) {
3193 // Mixing targets: load cookie directly to avoid mixing in LOAD_STACK_GUARD
3194 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3195 SDValue GuardPtr = getValue(IRGuard);
3196 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3197 MachinePointerInfo(IRGuard, 0), Align,
3199 } else {
3200 LLVMContext &Ctx = *DAG.getContext();
3201 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3202 Guard = DAG.getPOISON(PtrMemTy);
3203 }
3204 } else {
3205 // Non-mixing targets: use LOAD_STACK_GUARD or direct load as usual
3206 if (TLI.useLoadStackGuardNode(M)) {
3207 Guard = getLoadStackGuard(DAG, dl, Chain);
3208 } else {
3209 if (const Value *IRGuard = TLI.getSDagStackGuard(M, DAG.getLibcalls())) {
3210 SDValue GuardPtr = getValue(IRGuard);
3211 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3212 MachinePointerInfo(IRGuard, 0), Align,
3214 } else {
3215 LLVMContext &Ctx = *DAG.getContext();
3216 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
3217 Guard = DAG.getPOISON(PtrMemTy);
3218 }
3219 }
3220 }
3221
3222 // Now both Guard (fresh cookie) and GuardVal (unmixed from stored value)
3223 // contain unmixed cookie values that can be compared directly.
3224
3225 // Perform the comparison via a getsetcc.
3226 SDValue Cmp = DAG.getSetCC(
3227 dl, TLI.getSetCCResultType(DL, *DAG.getContext(), Guard.getValueType()),
3228 Guard, GuardVal, ISD::SETNE);
3229
3230 // If the guard/stackslot do not equal, branch to failure MBB.
3231 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
3232 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3233 // Otherwise branch to success MBB.
3234 SDValue Br = DAG.getNode(ISD::BR, dl,
3235 MVT::Other, BrCond,
3236 DAG.getBasicBlock(SPD.getSuccessMBB()));
3237
3238 DAG.setRoot(Br);
3239}
3240
3241/// Codegen the failure basic block for a stack protector check.
3242///
3243/// A failure stack protector machine basic block consists simply of a call to
3244/// __stack_chk_fail().
3245///
3246/// For a high level explanation of how this fits into the stack protector
3247/// generation see the comment on the declaration of class
3248/// StackProtectorDescriptor.
3251
3252 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3253 MachineBasicBlock *ParentBB = SPD.getParentMBB();
3254 const Module &M = *ParentBB->getParent()->getFunction().getParent();
3255 SDValue Chain;
3256
3257 // For -Oz builds with a guard check function, we use function-based
3258 // instrumentation. Otherwise, if we have a guard check function, we call it
3259 // in the failure block.
3260 auto *GuardCheckFn = TLI.getSSPStackGuardCheck(M, DAG.getLibcalls());
3261 if (GuardCheckFn && !SPD.shouldEmitFunctionBasedCheckStackProtector()) {
3262 // First create the loads to the guard/stack slot for the comparison.
3263 auto &DL = DAG.getDataLayout();
3264 EVT PtrTy = TLI.getFrameIndexTy(DL);
3265 EVT PtrMemTy = TLI.getPointerMemTy(DL, DL.getAllocaAddrSpace());
3266
3267 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3268 int FI = MFI.getStackProtectorIndex();
3269
3270 SDLoc dl = getCurSDLoc();
3271 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3272 Align Align = DL.getPrefTypeAlign(
3273 PointerType::get(M.getContext(), DL.getAllocaAddrSpace()));
3274
3275 // Generate code to load the content of the guard slot.
3276 SDValue GuardVal = DAG.getLoad(
3277 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3278 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3280
3281 if (TLI.useStackGuardMixFP())
3282 GuardVal = TLI.emitStackGuardMixFP(DAG, GuardVal, dl);
3283
3284 // The target provides a guard check function to validate the guard value.
3285 // Generate a call to that function with the content of the guard slot as
3286 // argument.
3287 FunctionType *FnTy = GuardCheckFn->getFunctionType();
3288 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3289
3291 TargetLowering::ArgListEntry Entry(GuardVal, FnTy->getParamType(0));
3292 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3293 Entry.IsInReg = true;
3294 Args.push_back(Entry);
3295
3298 .setChain(DAG.getEntryNode())
3299 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3300 getValue(GuardCheckFn), std::move(Args));
3301
3302 Chain = TLI.LowerCallTo(CLI).second;
3303 } else {
3305 CallOptions.setDiscardResult(true);
3306 Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3307 {}, CallOptions, getCurSDLoc())
3308 .second;
3309 }
3310
3311 // Emit a trap instruction if we are required to do so.
3312 const TargetOptions &TargetOpts = DAG.getTarget().Options;
3313 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3314 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3315
3316 DAG.setRoot(Chain);
3317}
3318
3319/// visitBitTestHeader - This function emits necessary code to produce value
3320/// suitable for "bit tests"
3322 MachineBasicBlock *SwitchBB) {
3323 SDLoc dl = getCurSDLoc();
3324
3325 // Subtract the minimum value.
3326 SDValue SwitchOp = getValue(B.SValue);
3327 EVT VT = SwitchOp.getValueType();
3328 SDValue RangeSub =
3329 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3330
3331 // Determine the type of the test operands.
3332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3333 bool UsePtrType = false;
3334 if (!TLI.isTypeLegal(VT)) {
3335 UsePtrType = true;
3336 } else {
3337 for (const BitTestCase &Case : B.Cases)
3338 if (!isUIntN(VT.getSizeInBits(), Case.Mask)) {
3339 // Switch table case range are encoded into series of masks.
3340 // Just use pointer type, it's guaranteed to fit.
3341 UsePtrType = true;
3342 break;
3343 }
3344 }
3345 SDValue Sub = RangeSub;
3346 if (UsePtrType) {
3347 VT = TLI.getPointerTy(DAG.getDataLayout());
3348 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3349 }
3350
3351 B.RegVT = VT.getSimpleVT();
3352 B.Reg = FuncInfo.CreateReg(B.RegVT);
3353 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3354
3355 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3356
3357 if (!B.FallthroughUnreachable)
3358 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3359 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3360 SwitchBB->normalizeSuccProbs();
3361
3362 SDValue Root = CopyTo;
3363 if (!B.FallthroughUnreachable) {
3364 // Conditional branch to the default block.
3365 SDValue RangeCmp = DAG.getSetCC(dl,
3366 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3367 RangeSub.getValueType()),
3368 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3369 ISD::SETUGT);
3370
3371 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3372 DAG.getBasicBlock(B.Default));
3373 }
3374
3375 // Avoid emitting unnecessary branches to the next block.
3376 if (MBB != NextBlock(SwitchBB))
3377 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3378
3379 DAG.setRoot(Root);
3380}
3381
3382/// visitBitTestCase - this function produces one "bit test"
3384 MachineBasicBlock *NextMBB,
3385 BranchProbability BranchProbToNext,
3386 Register Reg, BitTestCase &B,
3387 MachineBasicBlock *SwitchBB) {
3388 SDLoc dl = getCurSDLoc();
3389 MVT VT = BB.RegVT;
3390 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3391 SDValue Cmp;
3392 unsigned PopCount = llvm::popcount(B.Mask);
3393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3394 if (PopCount == 1) {
3395 // Testing for a single bit; just compare the shift count with what it
3396 // would need to be to shift a 1 bit in that position.
3397 Cmp = DAG.getSetCC(
3398 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3399 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3400 ISD::SETEQ);
3401 } else if (PopCount == BB.Range) {
3402 // There is only one zero bit in the range, test for it directly.
3403 Cmp = DAG.getSetCC(
3404 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3405 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3406 } else {
3407 // Make desired shift
3408 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3409 DAG.getConstant(1, dl, VT), ShiftOp);
3410
3411 // Emit bit tests and jumps
3412 SDValue AndOp = DAG.getNode(ISD::AND, dl,
3413 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3414 Cmp = DAG.getSetCC(
3415 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3416 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3417 }
3418
3419 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3420 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3421 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3422 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3423 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3424 // one as they are relative probabilities (and thus work more like weights),
3425 // and hence we need to normalize them to let the sum of them become one.
3426 SwitchBB->normalizeSuccProbs();
3427
3428 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3429 MVT::Other, getControlRoot(),
3430 Cmp, DAG.getBasicBlock(B.TargetBB));
3431
3432 // Avoid emitting unnecessary branches to the next block.
3433 if (NextMBB != NextBlock(SwitchBB))
3434 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3435 DAG.getBasicBlock(NextMBB));
3436
3437 DAG.setRoot(BrAnd);
3438}
3439
3440void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3441 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3442
3443 // Retrieve successors. Look through artificial IR level blocks like
3444 // catchswitch for successors.
3445 MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3446 const BasicBlock *EHPadBB = I.getSuccessor(1);
3447 MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3448
3449 // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3450 // have to do anything here to lower funclet bundles.
3451 failForInvalidBundles(I, "invokes",
3457
3458 const Value *Callee(I.getCalledOperand());
3459 const Function *Fn = dyn_cast<Function>(Callee);
3460 if (isa<InlineAsm>(Callee))
3461 visitInlineAsm(I, EHPadBB);
3462 else if (Fn && Fn->isIntrinsic()) {
3463 switch (Fn->getIntrinsicID()) {
3464 default:
3465 llvm_unreachable("Cannot invoke this intrinsic");
3466 case Intrinsic::donothing:
3467 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3468 case Intrinsic::seh_try_begin:
3469 case Intrinsic::seh_scope_begin:
3470 case Intrinsic::seh_try_end:
3471 case Intrinsic::seh_scope_end:
3472 if (EHPadMBB)
3473 // a block referenced by EH table
3474 // so dtor-funclet not removed by opts
3475 EHPadMBB->setMachineBlockAddressTaken();
3476 break;
3477 case Intrinsic::experimental_patchpoint_void:
3478 case Intrinsic::experimental_patchpoint:
3479 visitPatchpoint(I, EHPadBB);
3480 break;
3481 case Intrinsic::experimental_gc_statepoint:
3483 break;
3484 // wasm_throw, wasm_rethrow: This is usually done in visitTargetIntrinsic,
3485 // but these intrinsics are special because they can be invoked, so we
3486 // manually lower it to a DAG node here.
3487 case Intrinsic::wasm_throw: {
3489 std::array<SDValue, 4> Ops = {
3490 getControlRoot(), // inchain for the terminator node
3491 DAG.getTargetConstant(Intrinsic::wasm_throw, getCurSDLoc(),
3493 getValue(I.getArgOperand(0)), // tag
3494 getValue(I.getArgOperand(1)) // thrown value
3495 };
3496 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3497 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3498 break;
3499 }
3500 case Intrinsic::wasm_rethrow: {
3501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3502 std::array<SDValue, 2> Ops = {
3503 getControlRoot(), // inchain for the terminator node
3504 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3505 TLI.getPointerTy(DAG.getDataLayout()))};
3506 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3507 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3508 break;
3509 }
3510 }
3511 } else if (I.hasDeoptState()) {
3512 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3513 // Eventually we will support lowering the @llvm.experimental.deoptimize
3514 // intrinsic, and right now there are no plans to support other intrinsics
3515 // with deopt state.
3516 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3517 } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3519 } else {
3520 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3521 }
3522
3523 // If the value of the invoke is used outside of its defining block, make it
3524 // available as a virtual register.
3525 // We already took care of the exported value for the statepoint instruction
3526 // during call to the LowerStatepoint.
3527 if (!isa<GCStatepointInst>(I)) {
3529 }
3530
3532 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3533 BranchProbability EHPadBBProb =
3534 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3536 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3537
3538 // Update successor info.
3539 addSuccessorWithProb(InvokeMBB, Return);
3540 for (auto &UnwindDest : UnwindDests) {
3541 UnwindDest.first->setIsEHPad();
3542 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3543 }
3544 InvokeMBB->normalizeSuccProbs();
3545
3546 // Drop into normal successor.
3547 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3548 DAG.getBasicBlock(Return)));
3549}
3550
3551/// The intrinsics currently supported by callbr are implicit control flow
3552/// intrinsics such as amdgcn.kill.
3553/// - they should be called (no "dontcall-" attributes)
3554/// - they do not touch memory on the target (= !TLI.getTgtMemIntrinsic())
3555/// - they do not need custom argument handling (no
3556/// TLI.CollectTargetIntrinsicOperands())
3557void SelectionDAGBuilder::visitCallBrIntrinsic(const CallBrInst &I) {
3558#ifndef NDEBUG
3560 DAG.getTargetLoweringInfo().getTgtMemIntrinsic(
3561 Infos, I, DAG.getMachineFunction(), I.getIntrinsicID());
3562 assert(Infos.empty() && "Intrinsic touches memory");
3563#endif
3564
3565 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
3566
3568 getTargetIntrinsicOperands(I, HasChain, OnlyLoad);
3569 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
3570
3571 // Create the node.
3572 SDValue Result =
3573 getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
3574 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
3575
3576 setValue(&I, Result);
3577}
3578
3579void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3580 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3581
3582 if (I.isInlineAsm()) {
3583 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3584 // have to do anything here to lower funclet bundles.
3585 failForInvalidBundles(I, "callbrs",
3587 visitInlineAsm(I);
3588 } else {
3589 assert(!I.hasOperandBundles() &&
3590 "Can't have operand bundles for intrinsics");
3591 visitCallBrIntrinsic(I);
3592 }
3594
3595 // Retrieve successors.
3596 SmallPtrSet<BasicBlock *, 8> Dests;
3597 Dests.insert(I.getDefaultDest());
3598 MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3599
3600 // Update successor info.
3601 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3602 // TODO: For most of the cases where there is an intrinsic callbr, we're
3603 // having exactly one indirect target, which will be unreachable. As soon as
3604 // this changes, we might need to enhance
3605 // Target->setIsInlineAsmBrIndirectTarget or add something similar for
3606 // intrinsic indirect branches.
3607 if (I.isInlineAsm()) {
3608 for (BasicBlock *Dest : I.getIndirectDests()) {
3609 MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3610 Target->setIsInlineAsmBrIndirectTarget();
3611 // If we introduce a type of asm goto statement that is permitted to use
3612 // an indirect call instruction to jump to its labels, then we should add
3613 // a call to Target->setMachineBlockAddressTaken() here, to mark the
3614 // target block as requiring a BTI.
3615
3616 Target->setLabelMustBeEmitted();
3617 // Don't add duplicate machine successors.
3618 if (Dests.insert(Dest).second)
3619 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3620 }
3621 }
3622 CallBrMBB->normalizeSuccProbs();
3623
3624 // Drop into default successor.
3625 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3626 MVT::Other, getControlRoot(),
3627 DAG.getBasicBlock(Return)));
3628}
3629
3630void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3631 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3632}
3633
3634void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3635 assert(FuncInfo.MBB->isEHPad() &&
3636 "Call to landingpad not in landing pad!");
3637
3638 // If there aren't registers to copy the values into (e.g., during SjLj
3639 // exceptions), then don't bother to create these DAG nodes.
3640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3641 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3643 TLI.getTargetMachine().getExceptionModel(), PersonalityFn) == 0 &&
3645 TLI.getTargetMachine().getExceptionModel(), PersonalityFn) == 0)
3646 return;
3647
3648 // If landingpad's return type is token type, we don't create DAG nodes
3649 // for its exception pointer and selector value. The extraction of exception
3650 // pointer or selector value from token type landingpads is not currently
3651 // supported.
3652 if (LP.getType()->isTokenTy())
3653 return;
3654
3655 SmallVector<EVT, 2> ValueVTs;
3656 SDLoc dl = getCurSDLoc();
3657 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3658 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3659
3660 // Get the two live-in registers as SDValues. The physregs have already been
3661 // copied into virtual registers.
3662 SDValue Ops[2];
3663 if (FuncInfo.ExceptionPointerVirtReg) {
3664 Ops[0] = DAG.getZExtOrTrunc(
3665 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3666 FuncInfo.ExceptionPointerVirtReg,
3667 TLI.getPointerTy(DAG.getDataLayout())),
3668 dl, ValueVTs[0]);
3669 } else {
3670 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3671 }
3672 Ops[1] = DAG.getZExtOrTrunc(
3673 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3674 FuncInfo.ExceptionSelectorVirtReg,
3675 TLI.getPointerTy(DAG.getDataLayout())),
3676 dl, ValueVTs[1]);
3677
3678 // Merge into one.
3679 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3680 DAG.getVTList(ValueVTs), Ops);
3681 setValue(&LP, Res);
3682}
3683
3686 // Update JTCases.
3687 for (JumpTableBlock &JTB : SL->JTCases)
3688 if (JTB.first.HeaderBB == First)
3689 JTB.first.HeaderBB = Last;
3690
3691 // Update BitTestCases.
3692 for (BitTestBlock &BTB : SL->BitTestCases)
3693 if (BTB.Parent == First)
3694 BTB.Parent = Last;
3695}
3696
3697void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3698 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3699
3700 // Update machine-CFG edges with unique successors.
3702 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3703 BasicBlock *BB = I.getSuccessor(i);
3704 bool Inserted = Done.insert(BB).second;
3705 if (!Inserted)
3706 continue;
3707
3708 MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3709 addSuccessorWithProb(IndirectBrMBB, Succ);
3710 }
3711 IndirectBrMBB->normalizeSuccProbs();
3712
3714 MVT::Other, getControlRoot(),
3715 getValue(I.getAddress())));
3716}
3717
3718void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3719 if (!I.shouldLowerToTrap(DAG.getTarget().Options.TrapUnreachable,
3720 DAG.getTarget().Options.NoTrapAfterNoreturn))
3721 return;
3722
3723 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3724}
3725
3726void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3727 SDNodeFlags Flags;
3728 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3729 Flags.copyFMF(*FPOp);
3730
3731 SDValue Op = getValue(I.getOperand(0));
3732 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3733 Op, Flags);
3734 setValue(&I, UnNodeValue);
3735}
3736
3737void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3738 SDNodeFlags Flags;
3739 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3740 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3741 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3742 }
3743 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3744 Flags.setExact(ExactOp->isExact());
3745 if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3746 Flags.setDisjoint(DisjointOp->isDisjoint());
3747 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3748 Flags.copyFMF(*FPOp);
3749
3750 SDValue Op1 = getValue(I.getOperand(0));
3751 SDValue Op2 = getValue(I.getOperand(1));
3752 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3753 Op1, Op2, Flags);
3754 setValue(&I, BinNodeValue);
3755}
3756
3757void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3758 SDValue Op1 = getValue(I.getOperand(0));
3759 SDValue Op2 = getValue(I.getOperand(1));
3760
3761 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3762 Op1.getValueType(), DAG.getDataLayout());
3763
3764 // Coerce the shift amount to the right type if we can. This exposes the
3765 // truncate or zext to optimization early.
3766 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3768 "Unexpected shift type");
3769 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3770 }
3771
3772 bool nuw = false;
3773 bool nsw = false;
3774 bool exact = false;
3775
3776 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3777
3778 if (const OverflowingBinaryOperator *OFBinOp =
3780 nuw = OFBinOp->hasNoUnsignedWrap();
3781 nsw = OFBinOp->hasNoSignedWrap();
3782 }
3783 if (const PossiblyExactOperator *ExactOp =
3785 exact = ExactOp->isExact();
3786 }
3787 SDNodeFlags Flags;
3788 Flags.setExact(exact);
3789 Flags.setNoSignedWrap(nsw);
3790 Flags.setNoUnsignedWrap(nuw);
3791 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3792 Flags);
3793 setValue(&I, Res);
3794}
3795
3796void SelectionDAGBuilder::visitSDiv(const User &I) {
3797 SDValue Op1 = getValue(I.getOperand(0));
3798 SDValue Op2 = getValue(I.getOperand(1));
3799
3800 SDNodeFlags Flags;
3801 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3802 cast<PossiblyExactOperator>(&I)->isExact());
3803 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3804 Op2, Flags));
3805}
3806
3807void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3808 ICmpInst::Predicate predicate = I.getPredicate();
3809 SDValue Op1 = getValue(I.getOperand(0));
3810 SDValue Op2 = getValue(I.getOperand(1));
3811 ISD::CondCode Opcode = getICmpCondCode(predicate);
3812
3813 auto &TLI = DAG.getTargetLoweringInfo();
3814 EVT MemVT =
3815 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3816
3817 // If a pointer's DAG type is larger than its memory type then the DAG values
3818 // are zero-extended. This breaks signed comparisons so truncate back to the
3819 // underlying type before doing the compare.
3820 if (Op1.getValueType() != MemVT) {
3821 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3822 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3823 }
3824
3825 SDNodeFlags Flags;
3826 Flags.setSameSign(I.hasSameSign());
3827
3828 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3829 I.getType());
3830 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode,
3831 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3832}
3833
3834void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3835 FCmpInst::Predicate predicate = I.getPredicate();
3836 SDValue Op1 = getValue(I.getOperand(0));
3837 SDValue Op2 = getValue(I.getOperand(1));
3838
3839 ISD::CondCode Condition = getFCmpCondCode(predicate);
3840 auto *FPMO = cast<FPMathOperator>(&I);
3841 if (FPMO->hasNoNaNs() ||
3842 (DAG.isKnownNeverNaN(Op1) && DAG.isKnownNeverNaN(Op2)))
3843 Condition = getFCmpCodeWithoutNaN(Condition);
3844
3845 SDNodeFlags Flags;
3846 Flags.copyFMF(*FPMO);
3847
3848 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3849 I.getType());
3850 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition,
3851 /*Chain=*/{}, /*IsSignaling=*/false, Flags));
3852}
3853
3854// Check if the condition of the select has one use or two users that are both
3855// selects with the same condition.
3856static bool hasOnlySelectUsers(const Value *Cond) {
3857 return llvm::all_of(Cond->users(), [](const Value *V) {
3858 return isa<SelectInst>(V);
3859 });
3860}
3861
3862void SelectionDAGBuilder::visitSelect(const User &I) {
3863 SmallVector<EVT, 4> ValueVTs;
3864 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3865 ValueVTs);
3866 unsigned NumValues = ValueVTs.size();
3867 if (NumValues == 0) return;
3868
3870 SDValue Cond = getValue(I.getOperand(0));
3871 SDValue LHSVal = getValue(I.getOperand(1));
3872 SDValue RHSVal = getValue(I.getOperand(2));
3873 SmallVector<SDValue, 1> BaseOps(1, Cond);
3875 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3876
3877 bool IsUnaryAbs = false;
3878 bool Negate = false;
3879
3880 SDNodeFlags Flags;
3881 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3882 Flags.copyFMF(*FPOp);
3883
3884 Flags.setUnpredictable(
3885 cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3886
3887 // Min/max matching is only viable if all output VTs are the same.
3888 if (all_equal(ValueVTs)) {
3889 EVT VT = ValueVTs[0];
3890 LLVMContext &Ctx = *DAG.getContext();
3891 auto &TLI = DAG.getTargetLoweringInfo();
3892
3893 // We care about the legality of the operation after it has been type
3894 // legalized.
3895 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3896 VT = TLI.getTypeToTransformTo(Ctx, VT);
3897
3898 // If the vselect is legal, assume we want to leave this as a vector setcc +
3899 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3900 // min/max is legal on the scalar type.
3901 bool UseScalarMinMax = VT.isVector() &&
3903
3904 // ValueTracking's select pattern matching does not account for -0.0,
3905 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3906 // -0.0 is less than +0.0.
3907 const Value *LHS, *RHS;
3908 auto SPR = matchSelectPattern(&I, LHS, RHS);
3910 switch (SPR.Flavor) {
3911 case SPF_UMAX: Opc = ISD::UMAX; break;
3912 case SPF_UMIN: Opc = ISD::UMIN; break;
3913 case SPF_SMAX: Opc = ISD::SMAX; break;
3914 case SPF_SMIN: Opc = ISD::SMIN; break;
3915 case SPF_FMINNUM:
3917 break;
3918
3919 switch (SPR.NaNBehavior) {
3920 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3921 case SPNB_RETURNS_ANY:
3922 case SPNB_RETURNS_NAN:
3923 break;
3924 case SPNB_RETURNS_OTHER:
3926 Flags.setNoSignedZeros(true);
3927 break;
3928 }
3929 break;
3930 case SPF_FMAXNUM:
3932 break;
3933
3934 switch (SPR.NaNBehavior) {
3935 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3936 case SPNB_RETURNS_NAN:
3937 case SPNB_RETURNS_ANY:
3938 break;
3939 case SPNB_RETURNS_OTHER:
3941 Flags.setNoSignedZeros(true);
3942 break;
3943 }
3944 break;
3945 case SPF_NABS:
3946 Negate = true;
3947 [[fallthrough]];
3948 case SPF_ABS:
3949 IsUnaryAbs = true;
3950 Opc = ISD::ABS;
3951 break;
3952 default: break;
3953 }
3954
3955 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3956 (TLI.isOperationLegalOrCustom(Opc, VT) ||
3957 (UseScalarMinMax &&
3959 // If the underlying comparison instruction is used by any other
3960 // instruction, the consumed instructions won't be destroyed, so it is
3961 // not profitable to convert to a min/max.
3963 OpCode = Opc;
3964 LHSVal = getValue(LHS);
3965 RHSVal = getValue(RHS);
3966 BaseOps.clear();
3967 }
3968
3969 if (IsUnaryAbs) {
3970 OpCode = Opc;
3971 LHSVal = getValue(LHS);
3972 BaseOps.clear();
3973 }
3974 }
3975
3976 if (IsUnaryAbs) {
3977 for (unsigned i = 0; i != NumValues; ++i) {
3978 SDLoc dl = getCurSDLoc();
3979 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3980 Values[i] =
3981 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3982 if (Negate)
3983 Values[i] = DAG.getNegative(Values[i], dl, VT);
3984 }
3985 } else {
3986 for (unsigned i = 0; i != NumValues; ++i) {
3987 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3988 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3989 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3990 Values[i] = DAG.getNode(
3991 OpCode, getCurSDLoc(),
3992 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3993 }
3994 }
3995
3997 DAG.getVTList(ValueVTs), Values));
3998}
3999
4000void SelectionDAGBuilder::visitTrunc(const User &I) {
4001 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
4002 SDValue N = getValue(I.getOperand(0));
4003 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4004 I.getType());
4005 SDNodeFlags Flags;
4006 if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
4007 Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
4008 Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
4009 }
4010
4011 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
4012}
4013
4014void SelectionDAGBuilder::visitZExt(const User &I) {
4015 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4016 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
4017 SDValue N = getValue(I.getOperand(0));
4018 auto &TLI = DAG.getTargetLoweringInfo();
4019 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4020
4021 SDNodeFlags Flags;
4022 if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
4023 Flags.setNonNeg(PNI->hasNonNeg());
4024
4025 // Eagerly use nonneg information to canonicalize towards sign_extend if
4026 // that is the target's preference.
4027 // TODO: Let the target do this later.
4028 if (Flags.hasNonNeg() &&
4029 TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
4030 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4031 return;
4032 }
4033
4034 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4035}
4036
4037void SelectionDAGBuilder::visitSExt(const User &I) {
4038 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
4039 // SExt also can't be a cast to bool for same reason. So, nothing much to do
4040 SDValue N = getValue(I.getOperand(0));
4041 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4042 I.getType());
4043 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
4044}
4045
4046void SelectionDAGBuilder::visitFPTrunc(const User &I) {
4047 // FPTrunc is never a no-op cast, no need to check
4048 SDValue N = getValue(I.getOperand(0));
4049 SDLoc dl = getCurSDLoc();
4050 SDNodeFlags Flags;
4051 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4052 Flags.copyFMF(*FPOp);
4053 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4054 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4055 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
4056 DAG.getTargetConstant(
4057 0, dl, TLI.getPointerTy(DAG.getDataLayout())),
4058 Flags));
4059}
4060
4061void SelectionDAGBuilder::visitFPExt(const User &I) {
4062 // FPExt is never a no-op cast, no need to check
4063 SDValue N = getValue(I.getOperand(0));
4064 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4065 I.getType());
4066 SDNodeFlags Flags;
4067 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
4068 Flags.copyFMF(*FPOp);
4069 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N, Flags));
4070}
4071
4072void SelectionDAGBuilder::visitFPToUI(const User &I) {
4073 // FPToUI is never a no-op cast, no need to check
4074 SDValue N = getValue(I.getOperand(0));
4075 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4076 I.getType());
4077 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
4078}
4079
4080void SelectionDAGBuilder::visitFPToSI(const User &I) {
4081 // FPToSI is never a no-op cast, no need to check
4082 SDValue N = getValue(I.getOperand(0));
4083 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4084 I.getType());
4085 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
4086}
4087
4088void SelectionDAGBuilder::visitUIToFP(const User &I) {
4089 // UIToFP is never a no-op cast, no need to check
4090 SDValue N = getValue(I.getOperand(0));
4091 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4092 I.getType());
4093 SDNodeFlags Flags;
4094 Flags.setNonNeg(cast<PossiblyNonNegInst>(&I)->hasNonNeg());
4095 Flags.copyFMF(*cast<FPMathOperator>(&I));
4096
4097 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4098}
4099
4100void SelectionDAGBuilder::visitSIToFP(const User &I) {
4101 // SIToFP is never a no-op cast, no need to check
4102 SDValue N = getValue(I.getOperand(0));
4103 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4104 I.getType());
4105 SDNodeFlags Flags;
4106 Flags.copyFMF(*cast<FPMathOperator>(&I));
4107
4108 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
4109}
4110
4111void SelectionDAGBuilder::visitPtrToAddr(const User &I) {
4112 SDValue N = getValue(I.getOperand(0));
4113 // By definition the type of the ptrtoaddr must be equal to the address type.
4114 const auto &TLI = DAG.getTargetLoweringInfo();
4115 EVT AddrVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4116 // The address width must be smaller or equal to the pointer representation
4117 // width, so we lower ptrtoaddr as a truncate (possibly folded to a no-op).
4118 N = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), AddrVT, N);
4119 setValue(&I, N);
4120}
4121
4122void SelectionDAGBuilder::visitPtrToInt(const User &I) {
4123 // What to do depends on the size of the integer and the size of the pointer.
4124 // We can either truncate, zero extend, or no-op, accordingly.
4125 SDValue N = getValue(I.getOperand(0));
4126 auto &TLI = DAG.getTargetLoweringInfo();
4127 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4128 I.getType());
4129 EVT PtrMemVT =
4130 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
4131 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4132 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
4133 setValue(&I, N);
4134}
4135
4136void SelectionDAGBuilder::visitIntToPtr(const User &I) {
4137 // What to do depends on the size of the integer and the size of the pointer.
4138 // We can either truncate, zero extend, or no-op, accordingly.
4139 SDValue N = getValue(I.getOperand(0));
4140 auto &TLI = DAG.getTargetLoweringInfo();
4141 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4142 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4143 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
4144 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
4145 setValue(&I, N);
4146}
4147
4148void SelectionDAGBuilder::visitBitCast(const User &I) {
4149 SDValue N = getValue(I.getOperand(0));
4150 SDLoc dl = getCurSDLoc();
4151 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
4152 I.getType());
4153
4154 // BitCast assures us that source and destination are the same size so this is
4155 // either a BITCAST or a no-op.
4156 if (DestVT != N.getValueType())
4157 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
4158 DestVT, N)); // convert types.
4159 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
4160 // might fold any kind of constant expression to an integer constant and that
4161 // is not what we are looking for. Only recognize a bitcast of a genuine
4162 // constant integer as an opaque constant.
4163 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
4164 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
4165 /*isOpaque*/true));
4166 else
4167 setValue(&I, N); // noop cast.
4168}
4169
4170void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
4171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172 const Value *SV = I.getOperand(0);
4173 SDValue N = getValue(SV);
4174 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4175
4176 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
4177 unsigned DestAS = I.getType()->getPointerAddressSpace();
4178
4179 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
4180 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
4181
4182 setValue(&I, N);
4183}
4184
4185void SelectionDAGBuilder::visitInsertElement(const User &I) {
4186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4187 SDValue InVec = getValue(I.getOperand(0));
4188 SDValue InVal = getValue(I.getOperand(1));
4189 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
4190 TLI.getVectorIdxTy(DAG.getDataLayout()));
4192 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4193 InVec, InVal, InIdx));
4194}
4195
4196void SelectionDAGBuilder::visitExtractElement(const User &I) {
4197 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4198 SDValue InVec = getValue(I.getOperand(0));
4199 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4200 TLI.getVectorIdxTy(DAG.getDataLayout()));
4202 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4203 InVec, InIdx));
4204}
4205
4206void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4207 SDValue Src1 = getValue(I.getOperand(0));
4208 SDValue Src2 = getValue(I.getOperand(1));
4209 ArrayRef<int> Mask;
4210 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4211 Mask = SVI->getShuffleMask();
4212 else
4213 Mask = cast<ConstantExpr>(I).getShuffleMask();
4214 SDLoc DL = getCurSDLoc();
4215 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4216 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4217 EVT SrcVT = Src1.getValueType();
4218
4219 if (all_of(Mask, equal_to(0)) && VT.isScalableVector()) {
4220 // Canonical splat form of first element of first input vector.
4221 SDValue FirstElt =
4222 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4223 DAG.getVectorIdxConstant(0, DL));
4224 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4225 return;
4226 }
4227
4228 // For now, we only handle splats for scalable vectors.
4229 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4230 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4231 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4232
4233 unsigned SrcNumElts = SrcVT.getVectorNumElements();
4234 unsigned MaskNumElts = Mask.size();
4235
4236 if (SrcNumElts == MaskNumElts) {
4237 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4238 return;
4239 }
4240
4241 // Normalize the shuffle vector since mask and vector length don't match.
4242 if (SrcNumElts < MaskNumElts) {
4243 // Mask is longer than the source vectors. We can use concatenate vector to
4244 // make the mask and vectors lengths match.
4245
4246 if (MaskNumElts % SrcNumElts == 0) {
4247 // Mask length is a multiple of the source vector length.
4248 // Check if the shuffle is some kind of concatenation of the input
4249 // vectors.
4250 unsigned NumConcat = MaskNumElts / SrcNumElts;
4251 bool IsConcat = true;
4252 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4253 for (unsigned i = 0; i != MaskNumElts; ++i) {
4254 int Idx = Mask[i];
4255 if (Idx < 0)
4256 continue;
4257 // Ensure the indices in each SrcVT sized piece are sequential and that
4258 // the same source is used for the whole piece.
4259 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4260 (ConcatSrcs[i / SrcNumElts] >= 0 &&
4261 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4262 IsConcat = false;
4263 break;
4264 }
4265 // Remember which source this index came from.
4266 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4267 }
4268
4269 // The shuffle is concatenating multiple vectors together. Just emit
4270 // a CONCAT_VECTORS operation.
4271 if (IsConcat) {
4272 SmallVector<SDValue, 8> ConcatOps;
4273 for (auto Src : ConcatSrcs) {
4274 if (Src < 0)
4275 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4276 else if (Src == 0)
4277 ConcatOps.push_back(Src1);
4278 else
4279 ConcatOps.push_back(Src2);
4280 }
4281 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4282 return;
4283 }
4284 }
4285
4286 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4287 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4288 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4289 PaddedMaskNumElts);
4290
4291 // Pad both vectors with undefs to make them the same length as the mask.
4292 SDValue UndefVal = DAG.getUNDEF(SrcVT);
4293
4294 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4295 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4296 MOps1[0] = Src1;
4297 MOps2[0] = Src2;
4298
4299 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4300 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4301
4302 // Readjust mask for new input vector length.
4303 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4304 for (unsigned i = 0; i != MaskNumElts; ++i) {
4305 int Idx = Mask[i];
4306 if (Idx >= (int)SrcNumElts)
4307 Idx -= SrcNumElts - PaddedMaskNumElts;
4308 MappedOps[i] = Idx;
4309 }
4310
4311 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4312
4313 // If the concatenated vector was padded, extract a subvector with the
4314 // correct number of elements.
4315 if (MaskNumElts != PaddedMaskNumElts)
4316 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4317 DAG.getVectorIdxConstant(0, DL));
4318
4319 setValue(&I, Result);
4320 return;
4321 }
4322
4323 assert(SrcNumElts > MaskNumElts);
4324
4325 // Analyze the access pattern of the vector to see if we can extract
4326 // two subvectors and do the shuffle.
4327 int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4328 bool CanExtract = true;
4329 for (int Idx : Mask) {
4330 unsigned Input = 0;
4331 if (Idx < 0)
4332 continue;
4333
4334 if (Idx >= (int)SrcNumElts) {
4335 Input = 1;
4336 Idx -= SrcNumElts;
4337 }
4338
4339 // If all the indices come from the same MaskNumElts sized portion of
4340 // the sources we can use extract. Also make sure the extract wouldn't
4341 // extract past the end of the source.
4342 int NewStartIdx = alignDown(Idx, MaskNumElts);
4343 if (NewStartIdx + MaskNumElts > SrcNumElts ||
4344 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4345 CanExtract = false;
4346 // Make sure we always update StartIdx as we use it to track if all
4347 // elements are undef.
4348 StartIdx[Input] = NewStartIdx;
4349 }
4350
4351 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4352 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4353 return;
4354 }
4355 if (CanExtract) {
4356 // Extract appropriate subvector and generate a vector shuffle
4357 for (unsigned Input = 0; Input < 2; ++Input) {
4358 SDValue &Src = Input == 0 ? Src1 : Src2;
4359 if (StartIdx[Input] < 0)
4360 Src = DAG.getUNDEF(VT);
4361 else {
4362 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4363 DAG.getVectorIdxConstant(StartIdx[Input], DL));
4364 }
4365 }
4366
4367 // Calculate new mask.
4368 SmallVector<int, 8> MappedOps(Mask);
4369 for (int &Idx : MappedOps) {
4370 if (Idx >= (int)SrcNumElts)
4371 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4372 else if (Idx >= 0)
4373 Idx -= StartIdx[0];
4374 }
4375
4376 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4377 return;
4378 }
4379
4380 // We can't use either concat vectors or extract subvectors so fall back to
4381 // replacing the shuffle with extract and build vector.
4382 // to insert and build vector.
4383 EVT EltVT = VT.getVectorElementType();
4385 for (int Idx : Mask) {
4386 SDValue Res;
4387
4388 if (Idx < 0) {
4389 Res = DAG.getUNDEF(EltVT);
4390 } else {
4391 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4392 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4393
4394 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4395 DAG.getVectorIdxConstant(Idx, DL));
4396 }
4397
4398 Ops.push_back(Res);
4399 }
4400
4401 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4402}
4403
4404void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4405 ArrayRef<unsigned> Indices = I.getIndices();
4406 const Value *Op0 = I.getOperand(0);
4407 const Value *Op1 = I.getOperand(1);
4408 Type *AggTy = I.getType();
4409 Type *ValTy = Op1->getType();
4410 bool IntoUndef = isa<UndefValue>(Op0);
4411 bool FromUndef = isa<UndefValue>(Op1);
4412
4413 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4414
4415 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4416 SmallVector<EVT, 4> AggValueVTs;
4417 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4418 SmallVector<EVT, 4> ValValueVTs;
4419 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4420
4421 unsigned NumAggValues = AggValueVTs.size();
4422 unsigned NumValValues = ValValueVTs.size();
4423 SmallVector<SDValue, 4> Values(NumAggValues);
4424
4425 // Ignore an insertvalue that produces an empty object
4426 if (!NumAggValues) {
4427 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4428 return;
4429 }
4430
4431 SDValue Agg = getValue(Op0);
4432 unsigned i = 0;
4433 // Copy the beginning value(s) from the original aggregate.
4434 for (; i != LinearIndex; ++i)
4435 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4436 SDValue(Agg.getNode(), Agg.getResNo() + i);
4437 // Copy values from the inserted value(s).
4438 if (NumValValues) {
4439 SDValue Val = getValue(Op1);
4440 for (; i != LinearIndex + NumValValues; ++i)
4441 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4442 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4443 }
4444 // Copy remaining value(s) from the original aggregate.
4445 for (; i != NumAggValues; ++i)
4446 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4447 SDValue(Agg.getNode(), Agg.getResNo() + i);
4448
4450 DAG.getVTList(AggValueVTs), Values));
4451}
4452
4453void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4454 ArrayRef<unsigned> Indices = I.getIndices();
4455 const Value *Op0 = I.getOperand(0);
4456 Type *AggTy = Op0->getType();
4457 Type *ValTy = I.getType();
4458 bool OutOfUndef = isa<UndefValue>(Op0);
4459
4460 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4461
4462 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4463 SmallVector<EVT, 4> ValValueVTs;
4464 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4465
4466 unsigned NumValValues = ValValueVTs.size();
4467
4468 // Ignore a extractvalue that produces an empty object
4469 if (!NumValValues) {
4470 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4471 return;
4472 }
4473
4474 SmallVector<SDValue, 4> Values(NumValValues);
4475
4476 SDValue Agg = getValue(Op0);
4477 // Copy out the selected value(s).
4478 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4479 Values[i - LinearIndex] =
4480 OutOfUndef ?
4481 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4482 SDValue(Agg.getNode(), Agg.getResNo() + i);
4483
4485 DAG.getVTList(ValValueVTs), Values));
4486}
4487
4488void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4489 Value *Op0 = I.getOperand(0);
4490 // Note that the pointer operand may be a vector of pointers. Take the scalar
4491 // element which holds a pointer.
4492 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4493 SDValue N = getValue(Op0);
4494 SDLoc dl = getCurSDLoc();
4495 auto &TLI = DAG.getTargetLoweringInfo();
4496 GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4497
4498 // For a vector GEP, keep the prefix scalar as long as possible, then
4499 // convert any scalars encountered after the first vector operand to vectors.
4500 bool IsVectorGEP = I.getType()->isVectorTy();
4501 ElementCount VectorElementCount =
4502 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4504
4506 GTI != E; ++GTI) {
4507 const Value *Idx = GTI.getOperand();
4508 if (StructType *StTy = GTI.getStructTypeOrNull()) {
4509 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4510 if (Field) {
4511 // N = N + Offset
4513 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4514
4515 // In an inbounds GEP with an offset that is nonnegative even when
4516 // interpreted as signed, assume there is no unsigned overflow.
4517 SDNodeFlags Flags;
4518 if (NW.hasNoUnsignedWrap() ||
4519 (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4521 Flags.setInBounds(NW.isInBounds());
4522
4523 N = DAG.getMemBasePlusOffset(
4524 N, DAG.getConstant(Offset, dl, N.getValueType()), dl, Flags);
4525 }
4526 } else {
4527 // IdxSize is the width of the arithmetic according to IR semantics.
4528 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4529 // (and fix up the result later).
4530 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4531 MVT IdxTy = MVT::getIntegerVT(IdxSize);
4532 TypeSize ElementSize =
4533 GTI.getSequentialElementStride(DAG.getDataLayout());
4534 // We intentionally mask away the high bits here; ElementSize may not
4535 // fit in IdxTy.
4536 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4537 /*isSigned=*/false, /*implicitTrunc=*/true);
4538 bool ElementScalable = ElementSize.isScalable();
4539
4540 // If this is a scalar constant or a splat vector of constants,
4541 // handle it quickly.
4542 const auto *C = dyn_cast<Constant>(Idx);
4543 if (C && isa<VectorType>(C->getType()))
4544 C = C->getSplatValue();
4545
4546 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4547 if (CI && CI->isZero())
4548 continue;
4549 if (CI && !ElementScalable) {
4550 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4551 LLVMContext &Context = *DAG.getContext();
4552 SDValue OffsVal;
4553 if (N.getValueType().isVector())
4554 OffsVal = DAG.getConstant(
4555 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4556 else
4557 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4558
4559 // In an inbounds GEP with an offset that is nonnegative even when
4560 // interpreted as signed, assume there is no unsigned overflow.
4561 SDNodeFlags Flags;
4562 if (NW.hasNoUnsignedWrap() ||
4563 (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4564 Flags.setNoUnsignedWrap(true);
4565 Flags.setInBounds(NW.isInBounds());
4566
4567 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4568
4569 N = DAG.getMemBasePlusOffset(N, OffsVal, dl, Flags);
4570 continue;
4571 }
4572
4573 // N = N + Idx * ElementMul;
4574 SDValue IdxN = getValue(Idx);
4575
4576 if (IdxN.getValueType().isVector() != N.getValueType().isVector()) {
4577 if (N.getValueType().isVector()) {
4578 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4579 VectorElementCount);
4580 IdxN = DAG.getSplat(VT, dl, IdxN);
4581 } else {
4582 EVT VT =
4583 EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4584 N = DAG.getSplat(VT, dl, N);
4585 }
4586 }
4587
4588 // If the index is smaller or larger than intptr_t, truncate or extend
4589 // it.
4590 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4591
4592 SDNodeFlags ScaleFlags;
4593 // The multiplication of an index by the type size does not wrap the
4594 // pointer index type in a signed sense (mul nsw).
4596
4597 // The multiplication of an index by the type size does not wrap the
4598 // pointer index type in an unsigned sense (mul nuw).
4599 ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4600
4601 if (ElementScalable) {
4602 EVT VScaleTy = N.getValueType().getScalarType();
4603 SDValue VScale = DAG.getNode(
4604 ISD::VSCALE, dl, VScaleTy,
4605 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4606 if (N.getValueType().isVector())
4607 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4608 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4609 ScaleFlags);
4610 } else {
4611 // If this is a multiply by a power of two, turn it into a shl
4612 // immediately. This is a very common case.
4613 if (ElementMul != 1) {
4614 if (ElementMul.isPowerOf2()) {
4615 unsigned Amt = ElementMul.logBase2();
4616 IdxN = DAG.getNode(
4617 ISD::SHL, dl, N.getValueType(), IdxN,
4618 DAG.getShiftAmountConstant(Amt, N.getValueType(), dl),
4619 ScaleFlags);
4620 } else {
4621 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4622 IdxN.getValueType());
4623 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4624 ScaleFlags);
4625 }
4626 }
4627 }
4628
4629 // The successive addition of the current address, truncated to the
4630 // pointer index type and interpreted as an unsigned number, and each
4631 // offset, also interpreted as an unsigned number, does not wrap the
4632 // pointer index type (add nuw).
4633 SDNodeFlags AddFlags;
4634 AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4635 AddFlags.setInBounds(NW.isInBounds());
4636
4637 N = DAG.getMemBasePlusOffset(N, IdxN, dl, AddFlags);
4638 }
4639 }
4640
4641 if (IsVectorGEP && !N.getValueType().isVector()) {
4642 EVT VT = EVT::getVectorVT(*Context, N.getValueType(), VectorElementCount);
4643 N = DAG.getSplat(VT, dl, N);
4644 }
4645
4646 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4647 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4648 if (IsVectorGEP) {
4649 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4650 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4651 }
4652
4653 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4654 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4655
4656 setValue(&I, N);
4657}
4658
4659void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4660 // If this is a fixed sized alloca in the entry block of the function,
4661 // allocate it statically on the stack.
4662 if (FuncInfo.StaticAllocaMap.count(&I))
4663 return; // getValue will auto-populate this.
4664
4665 SDLoc dl = getCurSDLoc();
4666 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4667 auto &DL = DAG.getDataLayout();
4668 TypeSize TySize = I.getAllocationBaseSize(DL);
4669 MaybeAlign Alignment = I.getAlign();
4670
4671 SDValue AllocSize = getValue(I.getArraySize());
4672
4673 EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4674 if (AllocSize.getValueType() != IntPtr)
4675 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4676
4677 AllocSize = DAG.getNode(
4678 ISD::MUL, dl, IntPtr, AllocSize,
4679 DAG.getZExtOrTrunc(DAG.getTypeSize(dl, MVT::i64, TySize), dl, IntPtr));
4680
4681 // Handle alignment. If the requested alignment is less than or equal to
4682 // the stack alignment, ignore it. If the size is greater than or equal to
4683 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4684 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4685 if (*Alignment <= StackAlign)
4686 Alignment = std::nullopt;
4687
4688 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4689 // Round the size of the allocation up to the stack alignment size
4690 // by add SA-1 to the size. This doesn't overflow because we're computing
4691 // an address inside an alloca.
4692 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4693 DAG.getConstant(StackAlignMask, dl, IntPtr),
4695
4696 // Mask out the low bits for alignment purposes.
4697 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4698 DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4699
4700 SDValue Ops[] = {
4701 getRoot(), AllocSize,
4702 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4703 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4704 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4705 setValue(&I, DSA);
4706 DAG.setRoot(DSA.getValue(1));
4707
4708 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4709}
4710
4711static const MDNode *getRangeMetadata(const Instruction &I) {
4712 return I.getMetadata(LLVMContext::MD_range);
4713}
4714
4715static std::optional<ConstantRange> getRange(const Instruction &I) {
4716 if (const auto *CB = dyn_cast<CallBase>(&I))
4717 if (std::optional<ConstantRange> CR = CB->getRange())
4718 return CR;
4719 if (const MDNode *Range = getRangeMetadata(I))
4721 return std::nullopt;
4722}
4723
4725 if (const auto *CB = dyn_cast<CallBase>(&I))
4726 return CB->getRetNoFPClass();
4727 return fcNone;
4728}
4729
4730void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4731 if (I.isAtomic())
4732 return visitAtomicLoad(I);
4733
4734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4735 const Value *SV = I.getOperand(0);
4736 if (TLI.supportSwiftError()) {
4737 // Swifterror values can come from either a function parameter with
4738 // swifterror attribute or an alloca with swifterror attribute.
4739 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4740 if (Arg->hasSwiftErrorAttr())
4741 return visitLoadFromSwiftError(I);
4742 }
4743
4744 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4745 if (Alloca->isSwiftError())
4746 return visitLoadFromSwiftError(I);
4747 }
4748 }
4749
4750 SDValue Ptr = getValue(SV);
4751
4752 Type *Ty = I.getType();
4753 SmallVector<EVT, 4> ValueVTs, MemVTs;
4755 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4756 unsigned NumValues = ValueVTs.size();
4757 if (NumValues == 0)
4758 return;
4759
4760 Align Alignment = I.getAlign();
4761 AAMDNodes AAInfo = I.getAAMetadata();
4762 const MDNode *Ranges = getRangeMetadata(I);
4763 const MDNode *MemCacheHint = getMemCacheHintMetadata(I);
4764 bool isVolatile = I.isVolatile();
4765 MachineMemOperand::Flags MMOFlags =
4766 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4767
4768 SDValue Root;
4769 bool ConstantMemory = false;
4770 if (isVolatile)
4771 // Serialize volatile loads with other side effects.
4772 Root = getRoot();
4773 else if (NumValues > MaxParallelChains)
4774 Root = getMemoryRoot();
4775 else if (BatchAA &&
4776 BatchAA->pointsToConstantMemory(MemoryLocation(
4777 SV,
4778 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4779 AAInfo))) {
4780 // Do not serialize (non-volatile) loads of constant memory with anything.
4781 Root = DAG.getEntryNode();
4782 ConstantMemory = true;
4784 } else {
4785 // Do not serialize non-volatile loads against each other.
4786 Root = DAG.getRoot();
4787 }
4788
4789 SDLoc dl = getCurSDLoc();
4790
4791 if (isVolatile)
4792 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4793
4795 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4796
4797 unsigned ChainI = 0;
4798 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4799 // Serializing loads here may result in excessive register pressure, and
4800 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4801 // could recover a bit by hoisting nodes upward in the chain by recognizing
4802 // they are side-effect free or do not alias. The optimizer should really
4803 // avoid this case by converting large object/array copies to llvm.memcpy
4804 // (MaxParallelChains should always remain as failsafe).
4805 if (ChainI == MaxParallelChains) {
4806 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4807 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4808 ArrayRef(Chains.data(), ChainI));
4809 Root = Chain;
4810 ChainI = 0;
4811 }
4812
4813 // TODO: MachinePointerInfo only supports a fixed length offset.
4814 MachinePointerInfo PtrInfo =
4815 !Offsets[i].isScalable() || Offsets[i].isZero()
4816 ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4817 : MachinePointerInfo();
4818
4819 SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4820 SDValue L =
4821 DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment, MMOFlags,
4822 MMOMetadata(AAInfo, Ranges, MemCacheHint));
4823 Chains[ChainI] = L.getValue(1);
4824
4825 if (MemVTs[i] != ValueVTs[i])
4826 L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4827
4828 if (MDNode *NoFPClassMD = I.getMetadata(LLVMContext::MD_nofpclass)) {
4829 uint64_t FPTestInt =
4830 cast<ConstantInt>(
4831 cast<ConstantAsMetadata>(NoFPClassMD->getOperand(0))->getValue())
4832 ->getZExtValue();
4833 if (FPTestInt != fcNone) {
4834 SDValue FPTestConst =
4835 DAG.getTargetConstant(FPTestInt, SDLoc(), MVT::i32);
4836 L = DAG.getNode(ISD::AssertNoFPClass, dl, L.getValueType(), L,
4837 FPTestConst);
4838 }
4839 }
4840 Values[i] = L;
4841 }
4842
4843 if (!ConstantMemory) {
4844 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4845 ArrayRef(Chains.data(), ChainI));
4846 if (isVolatile)
4847 DAG.setRoot(Chain);
4848 else
4849 PendingLoads.push_back(Chain);
4850 }
4851
4852 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4853 DAG.getVTList(ValueVTs), Values));
4854}
4855
4856void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4857 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4858 "call visitStoreToSwiftError when backend supports swifterror");
4859
4860 SmallVector<EVT, 4> ValueVTs;
4861 SmallVector<uint64_t, 4> Offsets;
4862 const Value *SrcV = I.getOperand(0);
4863 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4864 SrcV->getType(), ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
4865 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4866 "expect a single EVT for swifterror");
4867
4868 SDValue Src = getValue(SrcV);
4869 // Create a virtual register, then update the virtual register.
4870 Register VReg =
4871 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4872 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4873 // Chain can be getRoot or getControlRoot.
4874 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4875 SDValue(Src.getNode(), Src.getResNo()));
4876 DAG.setRoot(CopyNode);
4877}
4878
4879void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4880 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4881 "call visitLoadFromSwiftError when backend supports swifterror");
4882
4883 assert(!I.isVolatile() &&
4884 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4885 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4886 "Support volatile, non temporal, invariant for load_from_swift_error");
4887
4888 const Value *SV = I.getOperand(0);
4889 Type *Ty = I.getType();
4890 assert(
4891 (!BatchAA ||
4892 !BatchAA->pointsToConstantMemory(MemoryLocation(
4893 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4894 I.getAAMetadata()))) &&
4895 "load_from_swift_error should not be constant memory");
4896
4897 SmallVector<EVT, 4> ValueVTs;
4898 SmallVector<uint64_t, 4> Offsets;
4899 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4900 ValueVTs, /*MemVTs=*/nullptr, &Offsets, 0);
4901 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4902 "expect a single EVT for swifterror");
4903
4904 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4905 SDValue L = DAG.getCopyFromReg(
4906 getRoot(), getCurSDLoc(),
4907 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4908
4909 setValue(&I, L);
4910}
4911
4912void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4913 if (I.isAtomic())
4914 return visitAtomicStore(I);
4915
4916 const Value *SrcV = I.getOperand(0);
4917 const Value *PtrV = I.getOperand(1);
4918
4919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4920 if (TLI.supportSwiftError()) {
4921 // Swifterror values can come from either a function parameter with
4922 // swifterror attribute or an alloca with swifterror attribute.
4923 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4924 if (Arg->hasSwiftErrorAttr())
4925 return visitStoreToSwiftError(I);
4926 }
4927
4928 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4929 if (Alloca->isSwiftError())
4930 return visitStoreToSwiftError(I);
4931 }
4932 }
4933
4934 SmallVector<EVT, 4> ValueVTs, MemVTs;
4936 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4937 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4938 unsigned NumValues = ValueVTs.size();
4939 if (NumValues == 0)
4940 return;
4941
4942 // Get the lowered operands. Note that we do this after
4943 // checking if NumResults is zero, because with zero results
4944 // the operands won't have values in the map.
4945 SDValue Src = getValue(SrcV);
4946 SDValue Ptr = getValue(PtrV);
4947
4948 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4949 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4950 SDLoc dl = getCurSDLoc();
4951 Align Alignment = I.getAlign();
4952 AAMDNodes AAInfo = I.getAAMetadata();
4953 const MDNode *MemCacheHint =
4954 getMemCacheHintMetadata(I, I.getPointerOperandIndex());
4955
4956 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4957
4958 unsigned ChainI = 0;
4959 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4960 // See visitLoad comments.
4961 if (ChainI == MaxParallelChains) {
4962 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4963 ArrayRef(Chains.data(), ChainI));
4964 Root = Chain;
4965 ChainI = 0;
4966 }
4967
4968 // TODO: MachinePointerInfo only supports a fixed length offset.
4969 MachinePointerInfo PtrInfo =
4970 !Offsets[i].isScalable() || Offsets[i].isZero()
4971 ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4972 : MachinePointerInfo();
4973
4974 SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4975 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4976 if (MemVTs[i] != ValueVTs[i])
4977 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4978 SDValue St =
4979 DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags,
4980 MMOMetadata(AAInfo, /*Ranges=*/nullptr, MemCacheHint));
4981 Chains[ChainI] = St;
4982 }
4983
4984 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4985 ArrayRef(Chains.data(), ChainI));
4986 setValue(&I, StoreNode);
4987 DAG.setRoot(StoreNode);
4988}
4989
4990void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4991 bool IsCompressing) {
4992 SDLoc sdl = getCurSDLoc();
4993
4994 Value *Src0Operand = I.getArgOperand(0);
4995 Value *PtrOperand = I.getArgOperand(1);
4996 Value *MaskOperand = I.getArgOperand(2);
4997 Align Alignment = I.getParamAlign(1).valueOrOne();
4998
4999 SDValue Ptr = getValue(PtrOperand);
5000 SDValue Src0 = getValue(Src0Operand);
5001 SDValue Mask = getValue(MaskOperand);
5002 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5003
5004 EVT VT = Src0.getValueType();
5005
5006 const auto &TLI = DAG.getTargetLoweringInfo();
5007
5008 auto MMOFlags = MachineMemOperand::MOStore;
5009 MMOFlags |= TLI.getTargetMMOFlags(I);
5010 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5012
5013 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5014 MachinePointerInfo(PtrOperand), MMOFlags,
5015 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5016 I.getAAMetadata());
5017
5018 SDValue StoreNode =
5019 !IsCompressing && TTI->hasConditionalLoadStoreForType(
5020 I.getArgOperand(0)->getType(), /*IsStore=*/true)
5021 ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
5022 Mask)
5023 : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
5024 VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
5025 IsCompressing);
5026 DAG.setRoot(StoreNode);
5027 setValue(&I, StoreNode);
5028}
5029
5030// Get a uniform base for the Gather/Scatter intrinsic.
5031// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
5032// We try to represent it as a base pointer + vector of indices.
5033// Usually, the vector of pointers comes from a 'getelementptr' instruction.
5034// The first operand of the GEP may be a single pointer or a vector of pointers
5035// Example:
5036// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
5037// or
5038// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
5039// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
5040//
5041// When the first GEP operand is a single pointer - it is the uniform base we
5042// are looking for. If first operand of the GEP is a splat vector - we
5043// extract the splat value and use it as a uniform base.
5044// In all other cases the function returns 'false'.
5045static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
5046 SDValue &Scale, SelectionDAGBuilder *SDB,
5047 const BasicBlock *CurBB, uint64_t ElemSize) {
5048 SelectionDAG& DAG = SDB->DAG;
5049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5050 const DataLayout &DL = DAG.getDataLayout();
5051
5052 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
5053
5054 // Handle splat constant pointer.
5055 if (auto *C = dyn_cast<Constant>(Ptr)) {
5056 C = C->getSplatValue();
5057 if (!C)
5058 return false;
5059
5060 Base = SDB->getValue(C);
5061
5062 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5063 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
5064 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
5065 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5066 return true;
5067 }
5068
5070 if (!GEP || GEP->getParent() != CurBB)
5071 return false;
5072
5073 if (GEP->getNumOperands() != 2)
5074 return false;
5075
5076 const Value *BasePtr = GEP->getPointerOperand();
5077 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
5078
5079 // Make sure the base is scalar and the index is a vector.
5080 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
5081 return false;
5082
5083 TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
5084 if (ScaleVal.isScalable())
5085 return false;
5086
5087 // Target may not support the required addressing mode.
5088 if (ScaleVal != 1 &&
5089 !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
5090 return false;
5091
5092 Base = SDB->getValue(BasePtr);
5093 Index = SDB->getValue(IndexVal);
5094
5095 Scale =
5096 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
5097 return true;
5098}
5099
5100void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
5101 SDLoc sdl = getCurSDLoc();
5102
5103 // llvm.masked.scatter.*(Src0, Ptrs, Mask)
5104 const Value *Ptr = I.getArgOperand(1);
5105 SDValue Src0 = getValue(I.getArgOperand(0));
5106 SDValue Mask = getValue(I.getArgOperand(2));
5107 EVT VT = Src0.getValueType();
5108 Align Alignment = I.getParamAlign(1).valueOrOne();
5109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5110
5111 SDValue Base;
5112 SDValue Index;
5113 SDValue Scale;
5114 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5115 I.getParent(), VT.getScalarStoreSize());
5116
5117 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5118 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5119 MachinePointerInfo(AS), MachineMemOperand::MOStore,
5120 LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
5121 if (!UniformBase) {
5122 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5123 Index = getValue(Ptr);
5124 Scale =
5125 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5126 }
5127
5128 EVT IdxVT = Index.getValueType();
5129 EVT EltTy = IdxVT.getVectorElementType();
5130 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5131 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5132 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5133 }
5134
5135 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
5136 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
5137 Ops, MMO, ISD::SIGNED_SCALED, false);
5138 DAG.setRoot(Scatter);
5139 setValue(&I, Scatter);
5140}
5141
5142void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
5143 SDLoc sdl = getCurSDLoc();
5144
5145 Value *PtrOperand = I.getArgOperand(0);
5146 Value *MaskOperand = I.getArgOperand(1);
5147 Value *Src0Operand = I.getArgOperand(2);
5148 Align Alignment = I.getParamAlign(0).valueOrOne();
5149
5150 SDValue Ptr = getValue(PtrOperand);
5151 SDValue Src0 = getValue(Src0Operand);
5152 SDValue Mask = getValue(MaskOperand);
5153 SDValue Offset = DAG.getPOISON(Ptr.getValueType());
5154
5155 EVT VT = Src0.getValueType();
5156 AAMDNodes AAInfo = I.getAAMetadata();
5157 const MDNode *Ranges = getRangeMetadata(I);
5158
5159 // Do not serialize masked loads of constant memory with anything.
5160 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5161 bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5162
5163 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5164
5165 const auto &TLI = DAG.getTargetLoweringInfo();
5166
5167 auto MMOFlags = MachineMemOperand::MOLoad;
5168 MMOFlags |= TLI.getTargetMMOFlags(I);
5169 if (I.hasMetadata(LLVMContext::MD_nontemporal))
5171 if (I.hasMetadata(LLVMContext::MD_invariant_load))
5173
5174 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5175 MachinePointerInfo(PtrOperand), MMOFlags,
5176 LocationSize::upperBound(VT.getStoreSize()), Alignment,
5177 MMOMetadata(AAInfo, Ranges));
5178
5179 // The Load/Res may point to different values and both of them are output
5180 // variables.
5181 SDValue Load;
5182 SDValue Res;
5183 if (!IsExpanding &&
5184 TTI->hasConditionalLoadStoreForType(Src0Operand->getType(),
5185 /*IsStore=*/false))
5186 Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5187 else
5188 Res = Load =
5189 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5190 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5191 if (AddToChain)
5192 PendingLoads.push_back(Load.getValue(1));
5193 setValue(&I, Res);
5194}
5195
5196void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5197 SDLoc sdl = getCurSDLoc();
5198
5199 // @llvm.masked.gather.*(Ptrs, Mask, Src0)
5200 const Value *Ptr = I.getArgOperand(0);
5201 SDValue Src0 = getValue(I.getArgOperand(2));
5202 SDValue Mask = getValue(I.getArgOperand(1));
5203
5204 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5205 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5206 Align Alignment = I.getParamAlign(0).valueOrOne();
5207
5208 const MDNode *Ranges = getRangeMetadata(I);
5209
5210 SDValue Root = DAG.getRoot();
5211 SDValue Base;
5212 SDValue Index;
5213 SDValue Scale;
5214 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
5215 I.getParent(), VT.getScalarStoreSize());
5216 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5217 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5218 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5220 MMOMetadata(I.getAAMetadata(), Ranges));
5221
5222 if (!UniformBase) {
5223 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5224 Index = getValue(Ptr);
5225 Scale =
5226 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5227 }
5228
5229 EVT IdxVT = Index.getValueType();
5230 EVT EltTy = IdxVT.getVectorElementType();
5231 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5232 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
5233 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5234 }
5235
5236 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5237 SDValue Gather =
5238 DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, Ops, MMO,
5240
5241 PendingLoads.push_back(Gather.getValue(1));
5242 setValue(&I, Gather);
5243}
5244
5245void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5246 SDLoc dl = getCurSDLoc();
5247 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5248 AtomicOrdering FailureOrdering = I.getFailureOrdering();
5249 SyncScope::ID SSID = I.getSyncScopeID();
5250
5251 SDValue InChain = getRoot();
5252
5253 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5254 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5255
5256 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5257 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5258
5259 MachineFunction &MF = DAG.getMachineFunction();
5260 MachineMemOperand *MMO = MF.getMachineMemOperand(
5261 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5262 I.getAlign(), MMOMetadata(), SSID, SuccessOrdering, FailureOrdering);
5263
5265 dl, MemVT, VTs, InChain,
5266 getValue(I.getPointerOperand()),
5267 getValue(I.getCompareOperand()),
5268 getValue(I.getNewValOperand()), MMO);
5269
5270 SDValue OutChain = L.getValue(2);
5271
5272 setValue(&I, L);
5273 DAG.setRoot(OutChain);
5274}
5275
5276void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5277 SDLoc dl = getCurSDLoc();
5279 switch (I.getOperation()) {
5280 default: llvm_unreachable("Unknown atomicrmw operation");
5298 break;
5301 break;
5304 break;
5307 break;
5310 break;
5313 break;
5316 break;
5319 break;
5320 }
5321 AtomicOrdering Ordering = I.getOrdering();
5322 SyncScope::ID SSID = I.getSyncScopeID();
5323
5324 SDValue InChain = getRoot();
5325
5326 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5327 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5328 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5329
5330 MachineFunction &MF = DAG.getMachineFunction();
5331 MachineMemOperand *MMO = MF.getMachineMemOperand(
5332 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5333 I.getAlign(), MMOMetadata(), SSID, Ordering);
5334
5335 SDValue L =
5336 DAG.getAtomic(NT, dl, MemVT, InChain,
5337 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5338 MMO);
5339
5340 SDValue OutChain = L.getValue(1);
5341
5342 setValue(&I, L);
5343 DAG.setRoot(OutChain);
5344}
5345
5346void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5347 SDLoc dl = getCurSDLoc();
5348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5349 SDValue Ops[3];
5350 Ops[0] = getRoot();
5351 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5352 TLI.getFenceOperandTy(DAG.getDataLayout()));
5353 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5354 TLI.getFenceOperandTy(DAG.getDataLayout()));
5355 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5356 setValue(&I, N);
5357 DAG.setRoot(N);
5358}
5359
5360void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5361 SDLoc dl = getCurSDLoc();
5362 AtomicOrdering Order = I.getOrdering();
5363 SyncScope::ID SSID = I.getSyncScopeID();
5364
5365 SDValue InChain = getRoot();
5366
5367 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5368 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5369 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5370
5371 if (!TLI.supportsUnalignedAtomics() &&
5372 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5373 report_fatal_error("Cannot generate unaligned atomic load");
5374
5375 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5376
5377 const MDNode *Ranges = getRangeMetadata(I);
5378 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5379 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5380 I.getAlign(), MMOMetadata(AAMDNodes(), Ranges), SSID, Order);
5381
5382 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5383
5384 SDValue Ptr = getValue(I.getPointerOperand());
5385 SDValue L =
5386 DAG.getAtomicLoad(ISD::NON_EXTLOAD, dl, MemVT, MemVT, InChain, Ptr, MMO);
5387
5388 SDValue OutChain = L.getValue(1);
5389 if (MemVT != VT)
5390 L = DAG.getPtrExtOrTrunc(L, dl, VT);
5391
5392 setValue(&I, L);
5393 DAG.setRoot(OutChain);
5394}
5395
5396void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5397 SDLoc dl = getCurSDLoc();
5398
5399 AtomicOrdering Ordering = I.getOrdering();
5400 SyncScope::ID SSID = I.getSyncScopeID();
5401
5402 SDValue InChain = getRoot();
5403
5404 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5405 EVT MemVT =
5406 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5407
5408 if (!TLI.supportsUnalignedAtomics() &&
5409 I.getAlign().value() < MemVT.getSizeInBits() / 8)
5410 report_fatal_error("Cannot generate unaligned atomic store");
5411
5412 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5413
5414 MachineFunction &MF = DAG.getMachineFunction();
5415 MachineMemOperand *MMO = MF.getMachineMemOperand(
5416 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
5417 I.getAlign(), MMOMetadata(), SSID, Ordering);
5418
5419 SDValue Val = getValue(I.getValueOperand());
5420 if (Val.getValueType() != MemVT)
5421 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5422 SDValue Ptr = getValue(I.getPointerOperand());
5423
5424 SDValue OutChain =
5425 DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5426
5427 setValue(&I, OutChain);
5428 DAG.setRoot(OutChain);
5429}
5430
5431/// Check if this intrinsic call depends on the chain (1st return value)
5432/// and if it only *loads* memory.
5433/// Ignore the callsite's attributes. A specific call site may be marked with
5434/// readnone, but the lowering code will expect the chain based on the
5435/// definition.
5436std::pair<bool, bool>
5437SelectionDAGBuilder::getTargetIntrinsicCallProperties(const CallBase &I) {
5438 const Function *F = I.getCalledFunction();
5439 bool HasChain = !F->doesNotAccessMemory();
5440 bool OnlyLoad =
5441 HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5442
5443 return {HasChain, OnlyLoad};
5444}
5445
5446SmallVector<SDValue, 8> SelectionDAGBuilder::getTargetIntrinsicOperands(
5447 const CallBase &I, bool HasChain, bool OnlyLoad,
5448 TargetLowering::IntrinsicInfo *TgtMemIntrinsicInfo) {
5449 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5450
5451 // Build the operand list.
5453 if (HasChain) { // If this intrinsic has side-effects, chainify it.
5454 if (OnlyLoad) {
5455 // We don't need to serialize loads against other loads.
5456 Ops.push_back(DAG.getRoot());
5457 } else {
5458 Ops.push_back(getRoot());
5459 }
5460 }
5461
5462 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5463 if (!TgtMemIntrinsicInfo || TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_VOID ||
5464 TgtMemIntrinsicInfo->opc == ISD::INTRINSIC_W_CHAIN)
5465 Ops.push_back(DAG.getTargetConstant(I.getIntrinsicID(), getCurSDLoc(),
5466 TLI.getPointerTy(DAG.getDataLayout())));
5467
5468 // Add all operands of the call to the operand list.
5469 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5470 const Value *Arg = I.getArgOperand(i);
5471 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5472 Ops.push_back(getValue(Arg));
5473 continue;
5474 }
5475
5476 // Use TargetConstant instead of a regular constant for immarg.
5477 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5478 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5479 assert(CI->getBitWidth() <= 64 &&
5480 "large intrinsic immediates not handled");
5481 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5482 } else {
5483 Ops.push_back(
5484 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5485 }
5486 }
5487
5488 if (std::optional<OperandBundleUse> Bundle =
5489 I.getOperandBundle(LLVMContext::OB_deactivation_symbol)) {
5490 auto *Sym = Bundle->Inputs[0].get();
5491 SDValue SDSym = getValue(Sym);
5492 SDSym = DAG.getDeactivationSymbol(cast<GlobalValue>(Sym));
5493 Ops.push_back(SDSym);
5494 }
5495
5496 if (std::optional<OperandBundleUse> Bundle =
5497 I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5498 Value *Token = Bundle->Inputs[0].get();
5499 SDValue ConvControlToken = getValue(Token);
5500 assert(Ops.back().getValueType() != MVT::Glue &&
5501 "Did not expect another glue node here.");
5502 ConvControlToken =
5503 DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5504 Ops.push_back(ConvControlToken);
5505 }
5506
5507 return Ops;
5508}
5509
5510SDVTList SelectionDAGBuilder::getTargetIntrinsicVTList(const CallBase &I,
5511 bool HasChain) {
5512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5513
5514 SmallVector<EVT, 4> ValueVTs;
5515 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5516
5517 if (HasChain)
5518 ValueVTs.push_back(MVT::Other);
5519
5520 return DAG.getVTList(ValueVTs);
5521}
5522
5523/// Get an INTRINSIC node for a target intrinsic which does not touch memory.
5524SDValue SelectionDAGBuilder::getTargetNonMemIntrinsicNode(
5525 const Type &IntrinsicVT, bool HasChain, ArrayRef<SDValue> Ops,
5526 const SDVTList &VTs) {
5527 if (!HasChain)
5528 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5529 if (!IntrinsicVT.isVoidTy())
5530 return DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5531 return DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5532}
5533
5534/// Set root, convert return type if necessary and check alignment.
5535SDValue SelectionDAGBuilder::handleTargetIntrinsicRet(const CallBase &I,
5536 bool HasChain,
5537 bool OnlyLoad,
5538 SDValue Result) {
5539 if (HasChain) {
5540 SDValue Chain = Result.getValue(Result.getNode()->getNumValues() - 1);
5541 if (OnlyLoad)
5542 PendingLoads.push_back(Chain);
5543 else
5544 DAG.setRoot(Chain);
5545 }
5546
5547 if (I.getType()->isVoidTy())
5548 return Result;
5549
5550 if (MaybeAlign Alignment = I.getRetAlign(); InsertAssertAlign && Alignment) {
5551 // Insert `assertalign` node if there's an alignment.
5552 Result = DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5553 } else if (!isa<VectorType>(I.getType())) {
5554 Result = lowerRangeToAssertZExt(DAG, I, Result);
5555 }
5556
5557 return Result;
5558}
5559
5560/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5561/// node.
5562void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5563 unsigned Intrinsic) {
5564 auto [HasChain, OnlyLoad] = getTargetIntrinsicCallProperties(I);
5565 Intrinsic::ID IntrinsicID = static_cast<Intrinsic::ID>(Intrinsic);
5566
5567 if (!DAG.getMachineFunction().getSubtarget().isIntrinsicSupported(
5568 Intrinsic)) {
5569 SDLoc DL = getCurSDLoc();
5570 DAG.getContext()->diagnose(DiagnosticInfoUnsupportedTargetIntrinsic(
5571 *I.getFunction(), IntrinsicID, DL.getDebugLoc()));
5572
5573 // The intrinsic is not available on this subtarget. Preserve the chain for
5574 // side-effecting intrinsics and lower any result to poison so that
5575 // compilation can continue and collect further diagnostics.
5576 if (HasChain && !OnlyLoad)
5577 DAG.setRoot(getRoot());
5578
5580 return;
5581 }
5582
5583 // Infos is set by getTgtMemIntrinsic.
5585 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5586 TLI.getTgtMemIntrinsic(Infos, I, DAG.getMachineFunction(), Intrinsic);
5587 // Use the first (primary) info determines the node opcode.
5588 TargetLowering::IntrinsicInfo *Info = !Infos.empty() ? &Infos[0] : nullptr;
5589
5591 getTargetIntrinsicOperands(I, HasChain, OnlyLoad, Info);
5592 SDVTList VTs = getTargetIntrinsicVTList(I, HasChain);
5593
5594 // Propagate fast-math-flags from IR to node(s).
5595 SDNodeFlags Flags;
5596 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5597 Flags.copyFMF(*FPMO);
5598 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5599
5600 // Create the node.
5602
5603 // In some cases, custom collection of operands from CallInst I may be needed.
5605 if (!Infos.empty()) {
5606 // This is target intrinsic that touches memory
5607 // Create MachineMemOperands for each memory access described by the target.
5608 MachineFunction &MF = DAG.getMachineFunction();
5610 for (const auto &Info : Infos) {
5611 // TODO: We currently just fallback to address space 0 if
5612 // getTgtMemIntrinsic didn't yield anything useful.
5613 MachinePointerInfo MPI;
5614 if (Info.ptrVal)
5615 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5616 else if (Info.fallbackAddressSpace)
5617 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5618 EVT MemVT = Info.memVT;
5619 LocationSize Size = LocationSize::precise(Info.size);
5620 if (Size.hasValue() && !Size.getValue())
5622 Align Alignment = Info.align.value_or(DAG.getEVTAlign(MemVT));
5623 MachineMemOperand *MMO = MF.getMachineMemOperand(
5624 MPI, Info.flags, Size, Alignment, I.getAAMetadata(), Info.ssid,
5625 Info.order, Info.failureOrder);
5626 MMOs.push_back(MMO);
5627 }
5628
5629 Result = DAG.getMemIntrinsicNode(Info->opc, getCurSDLoc(), VTs, Ops,
5630 Info->memVT, MMOs);
5631 } else {
5632 Result = getTargetNonMemIntrinsicNode(*I.getType(), HasChain, Ops, VTs);
5633 }
5634
5635 Result = handleTargetIntrinsicRet(I, HasChain, OnlyLoad, Result);
5636
5637 setValue(&I, Result);
5638}
5639
5640/// GetSignificand - Get the significand and build it into a floating-point
5641/// number with exponent of 1:
5642///
5643/// Op = (Op & 0x007fffff) | 0x3f800000;
5644///
5645/// where Op is the hexadecimal representation of floating point value.
5647 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5648 DAG.getConstant(0x007fffff, dl, MVT::i32));
5649 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5650 DAG.getConstant(0x3f800000, dl, MVT::i32));
5651 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5652}
5653
5654/// GetExponent - Get the exponent:
5655///
5656/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5657///
5658/// where Op is the hexadecimal representation of floating point value.
5660 const TargetLowering &TLI, const SDLoc &dl) {
5661 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5662 DAG.getConstant(0x7f800000, dl, MVT::i32));
5663 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
5664 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5665 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5666 DAG.getConstant(127, dl, MVT::i32));
5667 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5668}
5669
5670/// getF32Constant - Get 32-bit floating point constant.
5671static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5672 const SDLoc &dl) {
5673 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5674 MVT::f32);
5675}
5676
5678 SelectionDAG &DAG) {
5679 // TODO: What fast-math-flags should be set on the floating-point nodes?
5680
5681 // IntegerPartOfX = ((int32_t)(t0);
5682 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5683
5684 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5685 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5686 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5687
5688 // IntegerPartOfX <<= 23;
5689 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5690 DAG.getShiftAmountConstant(23, MVT::i32, dl));
5691
5692 SDValue TwoToFractionalPartOfX;
5693 if (LimitFloatPrecision <= 6) {
5694 // For floating-point precision of 6:
5695 //
5696 // TwoToFractionalPartOfX =
5697 // 0.997535578f +
5698 // (0.735607626f + 0.252464424f * x) * x;
5699 //
5700 // error 0.0144103317, which is 6 bits
5701 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5702 getF32Constant(DAG, 0x3e814304, dl));
5703 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5704 getF32Constant(DAG, 0x3f3c50c8, dl));
5705 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5706 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5707 getF32Constant(DAG, 0x3f7f5e7e, dl));
5708 } else if (LimitFloatPrecision <= 12) {
5709 // For floating-point precision of 12:
5710 //
5711 // TwoToFractionalPartOfX =
5712 // 0.999892986f +
5713 // (0.696457318f +
5714 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5715 //
5716 // error 0.000107046256, which is 13 to 14 bits
5717 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5718 getF32Constant(DAG, 0x3da235e3, dl));
5719 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5720 getF32Constant(DAG, 0x3e65b8f3, dl));
5721 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5722 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5723 getF32Constant(DAG, 0x3f324b07, dl));
5724 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5725 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5726 getF32Constant(DAG, 0x3f7ff8fd, dl));
5727 } else { // LimitFloatPrecision <= 18
5728 // For floating-point precision of 18:
5729 //
5730 // TwoToFractionalPartOfX =
5731 // 0.999999982f +
5732 // (0.693148872f +
5733 // (0.240227044f +
5734 // (0.554906021e-1f +
5735 // (0.961591928e-2f +
5736 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5737 // error 2.47208000*10^(-7), which is better than 18 bits
5738 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5739 getF32Constant(DAG, 0x3924b03e, dl));
5740 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5741 getF32Constant(DAG, 0x3ab24b87, dl));
5742 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5743 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5744 getF32Constant(DAG, 0x3c1d8c17, dl));
5745 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5746 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5747 getF32Constant(DAG, 0x3d634a1d, dl));
5748 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5749 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5750 getF32Constant(DAG, 0x3e75fe14, dl));
5751 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5752 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5753 getF32Constant(DAG, 0x3f317234, dl));
5754 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5755 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5756 getF32Constant(DAG, 0x3f800000, dl));
5757 }
5758
5759 // Add the exponent into the result in integer domain.
5760 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5761 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5762 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5763}
5764
5765/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5766/// limited-precision mode.
5768 const TargetLowering &TLI, SDNodeFlags Flags) {
5769 if (Op.getValueType() == MVT::f32 &&
5771
5772 // Put the exponent in the right bit position for later addition to the
5773 // final result:
5774 //
5775 // t0 = Op * log2(e)
5776
5777 // TODO: What fast-math-flags should be set here?
5778 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5779 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5780 return getLimitedPrecisionExp2(t0, dl, DAG);
5781 }
5782
5783 // No special expansion.
5784 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5785}
5786
5787/// expandLog - Lower a log intrinsic. Handles the special sequences for
5788/// limited-precision mode.
5790 const TargetLowering &TLI, SDNodeFlags Flags) {
5791 // TODO: What fast-math-flags should be set on the floating-point nodes?
5792
5793 if (Op.getValueType() == MVT::f32 &&
5795 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5796
5797 // Scale the exponent by log(2).
5798 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5799 SDValue LogOfExponent =
5800 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5801 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5802
5803 // Get the significand and build it into a floating-point number with
5804 // exponent of 1.
5805 SDValue X = GetSignificand(DAG, Op1, dl);
5806
5807 SDValue LogOfMantissa;
5808 if (LimitFloatPrecision <= 6) {
5809 // For floating-point precision of 6:
5810 //
5811 // LogofMantissa =
5812 // -1.1609546f +
5813 // (1.4034025f - 0.23903021f * x) * x;
5814 //
5815 // error 0.0034276066, which is better than 8 bits
5816 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5817 getF32Constant(DAG, 0xbe74c456, dl));
5818 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5819 getF32Constant(DAG, 0x3fb3a2b1, dl));
5820 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5821 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5822 getF32Constant(DAG, 0x3f949a29, dl));
5823 } else if (LimitFloatPrecision <= 12) {
5824 // For floating-point precision of 12:
5825 //
5826 // LogOfMantissa =
5827 // -1.7417939f +
5828 // (2.8212026f +
5829 // (-1.4699568f +
5830 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5831 //
5832 // error 0.000061011436, which is 14 bits
5833 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5834 getF32Constant(DAG, 0xbd67b6d6, dl));
5835 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5836 getF32Constant(DAG, 0x3ee4f4b8, dl));
5837 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5838 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5839 getF32Constant(DAG, 0x3fbc278b, dl));
5840 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5841 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5842 getF32Constant(DAG, 0x40348e95, dl));
5843 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5844 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5845 getF32Constant(DAG, 0x3fdef31a, dl));
5846 } else { // LimitFloatPrecision <= 18
5847 // For floating-point precision of 18:
5848 //
5849 // LogOfMantissa =
5850 // -2.1072184f +
5851 // (4.2372794f +
5852 // (-3.7029485f +
5853 // (2.2781945f +
5854 // (-0.87823314f +
5855 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5856 //
5857 // error 0.0000023660568, which is better than 18 bits
5858 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5859 getF32Constant(DAG, 0xbc91e5ac, dl));
5860 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5861 getF32Constant(DAG, 0x3e4350aa, dl));
5862 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5863 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5864 getF32Constant(DAG, 0x3f60d3e3, dl));
5865 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5866 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5867 getF32Constant(DAG, 0x4011cdf0, dl));
5868 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5869 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5870 getF32Constant(DAG, 0x406cfd1c, dl));
5871 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5872 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5873 getF32Constant(DAG, 0x408797cb, dl));
5874 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5875 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5876 getF32Constant(DAG, 0x4006dcab, dl));
5877 }
5878
5879 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5880 }
5881
5882 // No special expansion.
5883 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5884}
5885
5886/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5887/// limited-precision mode.
5889 const TargetLowering &TLI, SDNodeFlags Flags) {
5890 // TODO: What fast-math-flags should be set on the floating-point nodes?
5891
5892 if (Op.getValueType() == MVT::f32 &&
5894 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5895
5896 // Get the exponent.
5897 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5898
5899 // Get the significand and build it into a floating-point number with
5900 // exponent of 1.
5901 SDValue X = GetSignificand(DAG, Op1, dl);
5902
5903 // Different possible minimax approximations of significand in
5904 // floating-point for various degrees of accuracy over [1,2].
5905 SDValue Log2ofMantissa;
5906 if (LimitFloatPrecision <= 6) {
5907 // For floating-point precision of 6:
5908 //
5909 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5910 //
5911 // error 0.0049451742, which is more than 7 bits
5912 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5913 getF32Constant(DAG, 0xbeb08fe0, dl));
5914 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5915 getF32Constant(DAG, 0x40019463, dl));
5916 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5917 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5918 getF32Constant(DAG, 0x3fd6633d, dl));
5919 } else if (LimitFloatPrecision <= 12) {
5920 // For floating-point precision of 12:
5921 //
5922 // Log2ofMantissa =
5923 // -2.51285454f +
5924 // (4.07009056f +
5925 // (-2.12067489f +
5926 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5927 //
5928 // error 0.0000876136000, which is better than 13 bits
5929 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5930 getF32Constant(DAG, 0xbda7262e, dl));
5931 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5932 getF32Constant(DAG, 0x3f25280b, dl));
5933 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5934 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5935 getF32Constant(DAG, 0x4007b923, dl));
5936 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5937 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5938 getF32Constant(DAG, 0x40823e2f, dl));
5939 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5940 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5941 getF32Constant(DAG, 0x4020d29c, dl));
5942 } else { // LimitFloatPrecision <= 18
5943 // For floating-point precision of 18:
5944 //
5945 // Log2ofMantissa =
5946 // -3.0400495f +
5947 // (6.1129976f +
5948 // (-5.3420409f +
5949 // (3.2865683f +
5950 // (-1.2669343f +
5951 // (0.27515199f -
5952 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5953 //
5954 // error 0.0000018516, which is better than 18 bits
5955 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5956 getF32Constant(DAG, 0xbcd2769e, dl));
5957 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5958 getF32Constant(DAG, 0x3e8ce0b9, dl));
5959 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5960 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5961 getF32Constant(DAG, 0x3fa22ae7, dl));
5962 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5963 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5964 getF32Constant(DAG, 0x40525723, dl));
5965 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5966 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5967 getF32Constant(DAG, 0x40aaf200, dl));
5968 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5969 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5970 getF32Constant(DAG, 0x40c39dad, dl));
5971 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5972 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5973 getF32Constant(DAG, 0x4042902c, dl));
5974 }
5975
5976 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5977 }
5978
5979 // No special expansion.
5980 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5981}
5982
5983/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5984/// limited-precision mode.
5986 const TargetLowering &TLI, SDNodeFlags Flags) {
5987 // TODO: What fast-math-flags should be set on the floating-point nodes?
5988
5989 if (Op.getValueType() == MVT::f32 &&
5991 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5992
5993 // Scale the exponent by log10(2) [0.30102999f].
5994 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5995 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5996 getF32Constant(DAG, 0x3e9a209a, dl));
5997
5998 // Get the significand and build it into a floating-point number with
5999 // exponent of 1.
6000 SDValue X = GetSignificand(DAG, Op1, dl);
6001
6002 SDValue Log10ofMantissa;
6003 if (LimitFloatPrecision <= 6) {
6004 // For floating-point precision of 6:
6005 //
6006 // Log10ofMantissa =
6007 // -0.50419619f +
6008 // (0.60948995f - 0.10380950f * x) * x;
6009 //
6010 // error 0.0014886165, which is 6 bits
6011 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6012 getF32Constant(DAG, 0xbdd49a13, dl));
6013 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
6014 getF32Constant(DAG, 0x3f1c0789, dl));
6015 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6016 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
6017 getF32Constant(DAG, 0x3f011300, dl));
6018 } else if (LimitFloatPrecision <= 12) {
6019 // For floating-point precision of 12:
6020 //
6021 // Log10ofMantissa =
6022 // -0.64831180f +
6023 // (0.91751397f +
6024 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
6025 //
6026 // error 0.00019228036, which is better than 12 bits
6027 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6028 getF32Constant(DAG, 0x3d431f31, dl));
6029 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6030 getF32Constant(DAG, 0x3ea21fb2, dl));
6031 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6032 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6033 getF32Constant(DAG, 0x3f6ae232, dl));
6034 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6035 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6036 getF32Constant(DAG, 0x3f25f7c3, dl));
6037 } else { // LimitFloatPrecision <= 18
6038 // For floating-point precision of 18:
6039 //
6040 // Log10ofMantissa =
6041 // -0.84299375f +
6042 // (1.5327582f +
6043 // (-1.0688956f +
6044 // (0.49102474f +
6045 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
6046 //
6047 // error 0.0000037995730, which is better than 18 bits
6048 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
6049 getF32Constant(DAG, 0x3c5d51ce, dl));
6050 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
6051 getF32Constant(DAG, 0x3e00685a, dl));
6052 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
6053 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
6054 getF32Constant(DAG, 0x3efb6798, dl));
6055 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
6056 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
6057 getF32Constant(DAG, 0x3f88d192, dl));
6058 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
6059 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
6060 getF32Constant(DAG, 0x3fc4316c, dl));
6061 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
6062 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
6063 getF32Constant(DAG, 0x3f57ce70, dl));
6064 }
6065
6066 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
6067 }
6068
6069 // No special expansion.
6070 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
6071}
6072
6073/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
6074/// limited-precision mode.
6076 const TargetLowering &TLI, SDNodeFlags Flags) {
6077 if (Op.getValueType() == MVT::f32 &&
6079 return getLimitedPrecisionExp2(Op, dl, DAG);
6080
6081 // No special expansion.
6082 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
6083}
6084
6085/// visitPow - Lower a pow intrinsic. Handles the special sequences for
6086/// limited-precision mode with x == 10.0f.
6088 SelectionDAG &DAG, const TargetLowering &TLI,
6089 SDNodeFlags Flags) {
6090 bool IsExp10 = false;
6091 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
6094 APFloat Ten(10.0f);
6095 IsExp10 = LHSC->isExactlyValue(Ten);
6096 }
6097 }
6098
6099 // TODO: What fast-math-flags should be set on the FMUL node?
6100 if (IsExp10) {
6101 // Put the exponent in the right bit position for later addition to the
6102 // final result:
6103 //
6104 // #define LOG2OF10 3.3219281f
6105 // t0 = Op * LOG2OF10;
6106 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
6107 getF32Constant(DAG, 0x40549a78, dl));
6108 return getLimitedPrecisionExp2(t0, dl, DAG);
6109 }
6110
6111 // No special expansion.
6112 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
6113}
6114
6115/// ExpandPowI - Expand a llvm.powi intrinsic.
6117 SelectionDAG &DAG) {
6118 // If RHS is a constant, we can expand this out to a multiplication tree if
6119 // it's beneficial on the target, otherwise we end up lowering to a call to
6120 // __powidf2 (for example).
6122 unsigned Val = RHSC->getSExtValue();
6123
6124 // powi(x, 0) -> 1.0
6125 if (Val == 0)
6126 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
6127
6129 Val, DAG.shouldOptForSize())) {
6130 // Get the exponent as a positive value.
6131 if ((int)Val < 0)
6132 Val = -Val;
6133 // We use the simple binary decomposition method to generate the multiply
6134 // sequence. There are more optimal ways to do this (for example,
6135 // powi(x,15) generates one more multiply than it should), but this has
6136 // the benefit of being both really simple and much better than a libcall.
6137 SDValue Res; // Logically starts equal to 1.0
6138 SDValue CurSquare = LHS;
6139 // TODO: Intrinsics should have fast-math-flags that propagate to these
6140 // nodes.
6141 while (Val) {
6142 if (Val & 1) {
6143 if (Res.getNode())
6144 Res =
6145 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
6146 else
6147 Res = CurSquare; // 1.0*CurSquare.
6148 }
6149
6150 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
6151 CurSquare, CurSquare);
6152 Val >>= 1;
6153 }
6154
6155 // If the original was negative, invert the result, producing 1/(x*x*x).
6156 if (RHSC->getSExtValue() < 0)
6157 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
6158 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
6159 return Res;
6160 }
6161 }
6162
6163 // Otherwise, expand to a libcall.
6164 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
6165}
6166
6167static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
6168 SDValue LHS, SDValue RHS, SDValue Scale,
6169 SelectionDAG &DAG, const TargetLowering &TLI) {
6170 EVT VT = LHS.getValueType();
6171 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
6172 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
6173 LLVMContext &Ctx = *DAG.getContext();
6174
6175 // If the type is legal but the operation isn't, this node might survive all
6176 // the way to operation legalization. If we end up there and we do not have
6177 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
6178 // node.
6179
6180 // Coax the legalizer into expanding the node during type legalization instead
6181 // by bumping the size by one bit. This will force it to Promote, enabling the
6182 // early expansion and avoiding the need to expand later.
6183
6184 // We don't have to do this if Scale is 0; that can always be expanded, unless
6185 // it's a saturating signed operation. Those can experience true integer
6186 // division overflow, a case which we must avoid.
6187
6188 // FIXME: We wouldn't have to do this (or any of the early
6189 // expansion/promotion) if it was possible to expand a libcall of an
6190 // illegal type during operation legalization. But it's not, so things
6191 // get a bit hacky.
6192 unsigned ScaleInt = Scale->getAsZExtVal();
6193 if ((ScaleInt > 0 || (Saturating && Signed)) &&
6194 (TLI.isTypeLegal(VT) ||
6195 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
6197 Opcode, VT, ScaleInt);
6198 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
6199 EVT PromVT;
6200 if (VT.isScalarInteger())
6201 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
6202 else if (VT.isVector()) {
6203 PromVT = VT.getVectorElementType();
6204 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
6205 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
6206 } else
6207 llvm_unreachable("Wrong VT for DIVFIX?");
6208 LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
6209 RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
6210 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
6211 // For saturating operations, we need to shift up the LHS to get the
6212 // proper saturation width, and then shift down again afterwards.
6213 if (Saturating)
6214 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
6215 DAG.getConstant(1, DL, ShiftTy));
6216 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
6217 if (Saturating)
6218 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
6219 DAG.getConstant(1, DL, ShiftTy));
6220 return DAG.getZExtOrTrunc(Res, DL, VT);
6221 }
6222 }
6223
6224 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
6225}
6226
6227// getUnderlyingArgRegs - Find underlying registers used for a truncated,
6228// bitcasted, or split argument. Returns a list of <Register, size in bits>
6229static void
6230getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
6231 const SDValue &N) {
6232 switch (N.getOpcode()) {
6233 case ISD::CopyFromReg: {
6234 SDValue Op = N.getOperand(1);
6235 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
6236 Op.getValueType().getSizeInBits());
6237 return;
6238 }
6239 case ISD::BITCAST:
6240 case ISD::AssertZext:
6241 case ISD::AssertSext:
6242 case ISD::TRUNCATE:
6243 getUnderlyingArgRegs(Regs, N.getOperand(0));
6244 return;
6245 case ISD::BUILD_PAIR:
6246 case ISD::BUILD_VECTOR:
6248 for (SDValue Op : N->op_values())
6249 getUnderlyingArgRegs(Regs, Op);
6250 return;
6251 default:
6252 return;
6253 }
6254}
6255
6256/// If the DbgValueInst is a dbg_value of a function argument, create the
6257/// corresponding DBG_VALUE machine instruction for it now. At the end of
6258/// instruction selection, they will be inserted to the entry BB.
6259/// We don't currently support this for variadic dbg_values, as they shouldn't
6260/// appear for function arguments or in the prologue.
6261bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6262 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6263 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6264 const Argument *Arg = dyn_cast<Argument>(V);
6265 if (!Arg)
6266 return false;
6267
6268 MachineFunction &MF = DAG.getMachineFunction();
6269 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6270
6271 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6272 // we've been asked to pursue.
6273 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6274 bool Indirect) {
6275 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6276 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6277 // pointing at the VReg, which will be patched up later.
6278 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6280 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6281 /* isKill */ false, /* isDead */ false,
6282 /* isUndef */ false, /* isEarlyClobber */ false,
6283 /* SubReg */ 0, /* isDebug */ true)});
6284
6285 auto *NewDIExpr = FragExpr;
6286 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6287 // the DIExpression.
6288 if (Indirect)
6289 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6291 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6292 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6293 } else {
6294 // Create a completely standard DBG_VALUE.
6295 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6296 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6297 }
6298 };
6299
6300 if (Kind == FuncArgumentDbgValueKind::Value) {
6301 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6302 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6303 // the entry block.
6304 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6305 if (!IsInEntryBlock)
6306 return false;
6307
6308 // ArgDbgValues are hoisted to the beginning of the entry block. So we
6309 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6310 // variable that also is a param.
6311 //
6312 // Although, if we are at the top of the entry block already, we can still
6313 // emit using ArgDbgValue. This might catch some situations when the
6314 // dbg.value refers to an argument that isn't used in the entry block, so
6315 // any CopyToReg node would be optimized out and the only way to express
6316 // this DBG_VALUE is by using the physical reg (or FI) as done in this
6317 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
6318 // we should only emit as ArgDbgValue if the Variable is an argument to the
6319 // current function, and the dbg.value intrinsic is found in the entry
6320 // block.
6321 bool VariableIsFunctionInputArg = Variable->isParameter() &&
6322 !DL->getInlinedAt();
6323 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6324 if (!IsInPrologue && !VariableIsFunctionInputArg)
6325 return false;
6326
6327 // Here we assume that a function argument on IR level only can be used to
6328 // describe one input parameter on source level. If we for example have
6329 // source code like this
6330 //
6331 // struct A { long x, y; };
6332 // void foo(struct A a, long b) {
6333 // ...
6334 // b = a.x;
6335 // ...
6336 // }
6337 //
6338 // and IR like this
6339 //
6340 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
6341 // entry:
6342 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6343 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6344 // call void @llvm.dbg.value(metadata i32 %b, "b",
6345 // ...
6346 // call void @llvm.dbg.value(metadata i32 %a1, "b"
6347 // ...
6348 //
6349 // then the last dbg.value is describing a parameter "b" using a value that
6350 // is an argument. But since we already has used %a1 to describe a parameter
6351 // we should not handle that last dbg.value here (that would result in an
6352 // incorrect hoisting of the DBG_VALUE to the function entry).
6353 // Notice that we allow one dbg.value per IR level argument, to accommodate
6354 // for the situation with fragments above.
6355 // If there is no node for the value being handled, we return true to skip
6356 // the normal generation of debug info, as it would kill existing debug
6357 // info for the parameter in case of duplicates.
6358 if (VariableIsFunctionInputArg) {
6359 unsigned ArgNo = Arg->getArgNo();
6360 if (ArgNo >= FuncInfo.DescribedArgs.size())
6361 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6362 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6363 return !NodeMap[V].getNode();
6364 FuncInfo.DescribedArgs.set(ArgNo);
6365 }
6366 }
6367
6368 bool IsIndirect = false;
6369 std::optional<MachineOperand> Op;
6370 // Some arguments' frame index is recorded during argument lowering.
6371 int FI = FuncInfo.getArgumentFrameIndex(Arg);
6372 if (FI != std::numeric_limits<int>::max())
6374
6376 if (!Op && N.getNode()) {
6377 getUnderlyingArgRegs(ArgRegsAndSizes, N);
6378 Register Reg;
6379 if (ArgRegsAndSizes.size() == 1)
6380 Reg = ArgRegsAndSizes.front().first;
6381
6382 if (Reg && Reg.isVirtual()) {
6383 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6384 Register PR = RegInfo.getLiveInPhysReg(Reg);
6385 if (PR)
6386 Reg = PR;
6387 }
6388 if (Reg) {
6390 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6391 }
6392 }
6393
6394 if (!Op && N.getNode()) {
6395 // Check if frame index is available.
6396 SDValue LCandidate = peekThroughBitcasts(N);
6397 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6398 if (FrameIndexSDNode *FINode =
6399 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6400 Op = MachineOperand::CreateFI(FINode->getIndex());
6401 }
6402
6403 if (!Op) {
6404 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6405 auto splitMultiRegDbgValue =
6406 [&](ArrayRef<std::pair<Register, TypeSize>> SplitRegs) -> bool {
6407 unsigned Offset = 0;
6408 for (const auto &[Reg, RegSizeInBits] : SplitRegs) {
6409 // FIXME: Scalable sizes are not supported in fragment expressions.
6410 if (RegSizeInBits.isScalable())
6411 return false;
6412
6413 // If the expression is already a fragment, the current register
6414 // offset+size might extend beyond the fragment. In this case, only
6415 // the register bits that are inside the fragment are relevant.
6416 int RegFragmentSizeInBits = RegSizeInBits.getFixedValue();
6417 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6418 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6419 // The register is entirely outside the expression fragment,
6420 // so is irrelevant for debug info.
6421 if (Offset >= ExprFragmentSizeInBits)
6422 break;
6423 // The register is partially outside the expression fragment, only
6424 // the low bits within the fragment are relevant for debug info.
6425 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6426 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6427 }
6428 }
6429
6430 auto FragmentExpr = DIExpression::createFragmentExpression(
6431 Expr, Offset, RegFragmentSizeInBits);
6432 Offset += RegSizeInBits.getFixedValue();
6433 // If a valid fragment expression cannot be created, the variable's
6434 // correct value cannot be determined and so it is set as poison.
6435 if (!FragmentExpr) {
6436 SDDbgValue *SDV = DAG.getConstantDbgValue(
6437 Variable, Expr, PoisonValue::get(V->getType()), DL, SDNodeOrder);
6438 DAG.AddDbgValue(SDV, false);
6439 continue;
6440 }
6441 MachineInstr *NewMI = MakeVRegDbgValue(
6442 Reg, *FragmentExpr, Kind != FuncArgumentDbgValueKind::Value);
6443 FuncInfo.ArgDbgValues.push_back(NewMI);
6444 }
6445
6446 return true;
6447 };
6448
6449 // Check if ValueMap has reg number.
6451 VMI = FuncInfo.ValueMap.find(V);
6452 if (VMI != FuncInfo.ValueMap.end()) {
6453 const auto &TLI = DAG.getTargetLoweringInfo();
6454 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6455 V->getType(), std::nullopt);
6456 if (RFV.occupiesMultipleRegs())
6457 return splitMultiRegDbgValue(RFV.getRegsAndSizes());
6458
6459 Op = MachineOperand::CreateReg(VMI->second, false);
6460 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6461 } else if (ArgRegsAndSizes.size() > 1) {
6462 // This was split due to the calling convention, and no virtual register
6463 // mapping exists for the value.
6464 return splitMultiRegDbgValue(ArgRegsAndSizes);
6465 }
6466 }
6467
6468 if (!Op)
6469 return false;
6470
6471 assert(Variable->isValidLocationForIntrinsic(DL) &&
6472 "Expected inlined-at fields to agree");
6473 MachineInstr *NewMI = nullptr;
6474
6475 if (Op->isReg())
6476 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6477 else
6478 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6479 Variable, Expr);
6480
6481 // Otherwise, use ArgDbgValues.
6482 FuncInfo.ArgDbgValues.push_back(NewMI);
6483 return true;
6484}
6485
6486/// Return the appropriate SDDbgValue based on N.
6487SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6488 DILocalVariable *Variable,
6489 DIExpression *Expr,
6490 const DebugLoc &dl,
6491 unsigned DbgSDNodeOrder) {
6492 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6493 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6494 // stack slot locations.
6495 //
6496 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6497 // debug values here after optimization:
6498 //
6499 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
6500 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6501 //
6502 // Both describe the direct values of their associated variables.
6503 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6504 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6505 }
6506 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6507 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6508}
6509
6510static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6511 switch (Intrinsic) {
6512 case Intrinsic::smul_fix:
6513 return ISD::SMULFIX;
6514 case Intrinsic::umul_fix:
6515 return ISD::UMULFIX;
6516 case Intrinsic::smul_fix_sat:
6517 return ISD::SMULFIXSAT;
6518 case Intrinsic::umul_fix_sat:
6519 return ISD::UMULFIXSAT;
6520 case Intrinsic::sdiv_fix:
6521 return ISD::SDIVFIX;
6522 case Intrinsic::udiv_fix:
6523 return ISD::UDIVFIX;
6524 case Intrinsic::sdiv_fix_sat:
6525 return ISD::SDIVFIXSAT;
6526 case Intrinsic::udiv_fix_sat:
6527 return ISD::UDIVFIXSAT;
6528 default:
6529 llvm_unreachable("Unhandled fixed point intrinsic");
6530 }
6531}
6532
6533/// Given a @llvm.call.preallocated.setup, return the corresponding
6534/// preallocated call.
6535static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6536 assert(cast<CallBase>(PreallocatedSetup)
6538 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6539 "expected call_preallocated_setup Value");
6540 for (const auto *U : PreallocatedSetup->users()) {
6541 auto *UseCall = cast<CallBase>(U);
6542 const Function *Fn = UseCall->getCalledFunction();
6543 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6544 return UseCall;
6545 }
6546 }
6547 llvm_unreachable("expected corresponding call to preallocated setup/arg");
6548}
6549
6550/// If DI is a debug value with an EntryValue expression, lower it using the
6551/// corresponding physical register of the associated Argument value
6552/// (guaranteed to exist by the verifier).
6553bool SelectionDAGBuilder::visitEntryValueDbgValue(
6555 DIExpression *Expr, DebugLoc DbgLoc) {
6556 if (!Expr->isEntryValue() || !hasSingleElement(Values))
6557 return false;
6558
6559 // These properties are guaranteed by the verifier.
6560 const Argument *Arg = cast<Argument>(Values[0]);
6561 assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6562
6563 auto ArgIt = FuncInfo.ValueMap.find(Arg);
6564 if (ArgIt == FuncInfo.ValueMap.end()) {
6565 LLVM_DEBUG(
6566 dbgs() << "Dropping dbg.value: expression is entry_value but "
6567 "couldn't find an associated register for the Argument\n");
6568 return true;
6569 }
6570 Register ArgVReg = ArgIt->getSecond();
6571
6572 for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6573 if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6574 SDDbgValue *SDV = DAG.getVRegDbgValue(
6575 Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6576 DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6577 return true;
6578 }
6579 LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6580 "couldn't find a physical register\n");
6581 return true;
6582}
6583
6584/// Lower the call to the specified intrinsic function.
6585void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6586 unsigned Intrinsic) {
6587 SDLoc sdl = getCurSDLoc();
6588 switch (Intrinsic) {
6589 case Intrinsic::experimental_convergence_anchor:
6590 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6591 break;
6592 case Intrinsic::experimental_convergence_entry:
6593 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6594 break;
6595 case Intrinsic::experimental_convergence_loop: {
6596 auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6597 auto *Token = Bundle->Inputs[0].get();
6598 setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6599 getValue(Token)));
6600 break;
6601 }
6602 }
6603}
6604
6605void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6606 unsigned IntrinsicID) {
6607 // For now, we're only lowering an 'add' histogram.
6608 // We can add others later, e.g. saturating adds, min/max.
6609 assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6610 "Tried to lower unsupported histogram type");
6611 SDLoc sdl = getCurSDLoc();
6612 Value *Ptr = I.getOperand(0);
6613 SDValue Inc = getValue(I.getOperand(1));
6614 SDValue Mask = getValue(I.getOperand(2));
6615
6616 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6617 DataLayout TargetDL = DAG.getDataLayout();
6618 EVT VT = Inc.getValueType();
6619 Align Alignment = DAG.getEVTAlign(VT);
6620
6621 const MDNode *Ranges = getRangeMetadata(I);
6622
6623 SDValue Root = DAG.getRoot();
6624 SDValue Base;
6625 SDValue Index;
6626 SDValue Scale;
6627 bool UniformBase = getUniformBase(Ptr, Base, Index, Scale, this,
6628 I.getParent(), VT.getScalarStoreSize());
6629
6630 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6631
6632 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6633 MachinePointerInfo(AS),
6635 MemoryLocation::UnknownSize, Alignment,
6636 MMOMetadata(I.getAAMetadata(), Ranges));
6637
6638 if (!UniformBase) {
6639 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6640 Index = getValue(Ptr);
6641 Scale =
6642 DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6643 }
6644
6645 EVT IdxVT = Index.getValueType();
6646
6647 // Avoid using e.g. i32 as index type when the increment must be performed
6648 // on i64's.
6649 bool MustExtendIndex = VT.getScalarSizeInBits() > IdxVT.getScalarSizeInBits();
6650 EVT EltTy = MustExtendIndex ? VT : IdxVT.getVectorElementType();
6651 if (MustExtendIndex || TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6652 EVT NewIdxVT = IdxVT.changeVectorElementType(*DAG.getContext(), EltTy);
6653 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6654 }
6655
6656 SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6657
6658 SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6659 SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6660 Ops, MMO, ISD::SIGNED_SCALED);
6661
6662 setValue(&I, Histogram);
6663 DAG.setRoot(Histogram);
6664}
6665
6666void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6667 unsigned Intrinsic) {
6668 assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6669 "Tried lowering invalid vector extract last");
6670 SDLoc sdl = getCurSDLoc();
6671 const DataLayout &Layout = DAG.getDataLayout();
6672 SDValue Data = getValue(I.getOperand(0));
6673 SDValue Mask = getValue(I.getOperand(1));
6674
6675 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6676 EVT ResVT = TLI.getValueType(Layout, I.getType());
6677
6678 EVT ExtVT = TLI.getVectorIdxTy(Layout);
6679 SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6680 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6681
6682 Value *Default = I.getOperand(2);
6684 SDValue PassThru = getValue(Default);
6685 EVT BoolVT = Mask.getValueType().getScalarType();
6686 SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6687 Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6688 }
6689
6690 setValue(&I, Result);
6691}
6692
6693/// Lower the call to the specified intrinsic function.
6694void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6695 unsigned Intrinsic) {
6696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6697 SDLoc sdl = getCurSDLoc();
6698 DebugLoc dl = getCurDebugLoc();
6699 SDValue Res;
6700
6701 SDNodeFlags Flags;
6702 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6703 Flags.copyFMF(*FPOp);
6704
6705 switch (Intrinsic) {
6706 default:
6707 // By default, turn this into a target intrinsic node.
6708 visitTargetIntrinsic(I, Intrinsic);
6709 return;
6710 case Intrinsic::vscale: {
6711 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6712 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6713 return;
6714 }
6715 case Intrinsic::vastart: visitVAStart(I); return;
6716 case Intrinsic::vaend: visitVAEnd(I); return;
6717 case Intrinsic::vacopy: visitVACopy(I); return;
6718 case Intrinsic::returnaddress:
6719 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6720 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6721 getValue(I.getArgOperand(0))));
6722 return;
6723 case Intrinsic::addressofreturnaddress:
6724 setValue(&I,
6725 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6726 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6727 return;
6728 case Intrinsic::sponentry:
6729 setValue(&I,
6730 DAG.getNode(ISD::SPONENTRY, sdl,
6731 TLI.getValueType(DAG.getDataLayout(), I.getType())));
6732 return;
6733 case Intrinsic::frameaddress:
6734 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6735 TLI.getFrameIndexTy(DAG.getDataLayout()),
6736 getValue(I.getArgOperand(0))));
6737 return;
6738 case Intrinsic::read_volatile_register:
6739 case Intrinsic::read_register: {
6740 Value *Reg = I.getArgOperand(0);
6741 SDValue Chain = getRoot();
6743 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6744 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6745 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6746 DAG.getVTList(VT, MVT::Other), Chain, RegName);
6747 setValue(&I, Res);
6748 DAG.setRoot(Res.getValue(1));
6749 return;
6750 }
6751 case Intrinsic::write_register: {
6752 Value *Reg = I.getArgOperand(0);
6753 Value *RegValue = I.getArgOperand(1);
6754 SDValue Chain = getRoot();
6756 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6757 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6758 RegName, getValue(RegValue)));
6759 return;
6760 }
6761 case Intrinsic::write_volatile_register: {
6762 Value *Reg = I.getArgOperand(0);
6763 Value *RegValue = I.getArgOperand(1);
6764 SDValue Chain = getRoot();
6765 const MDNode *MD = cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata());
6766 SDValue RegName = DAG.getMDNode(MD);
6767 EVT VT = TLI.getValueType(DAG.getDataLayout(), RegValue->getType());
6768 SDValue WriteChain = DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other,
6769 Chain, RegName, getValue(RegValue));
6770 // FAKE_USE of the physical register marks it live after the WRITE_REGISTER,
6771 // preventing the backend from dead-eliminating the write. This is
6772 // preferred over READ_REGISTER, which would emit extra register copies
6773 // (e.g. fmov xN, dN for FP/SIMD registers).
6774 const MDString *RegStr = cast<MDString>(MD->getOperand(0));
6775 LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
6776 const MachineFunction &MF = DAG.getMachineFunction();
6777 Register PhysReg =
6778 TLI.getRegisterByName(RegStr->getString().data(), Ty, MF);
6779 if (PhysReg.isValid()) {
6780 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6781 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
6782 MVT RegVT = *TRI->legalclasstypes_begin(*RC);
6783 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other,
6784 {WriteChain, DAG.getRegister(PhysReg, RegVT)}));
6785 } else {
6786 DAG.setRoot(WriteChain);
6787 }
6788 return;
6789 }
6790 case Intrinsic::memcpy:
6791 case Intrinsic::memcpy_inline: {
6792 const auto &MCI = cast<MemCpyInst>(I);
6793 SDValue Dst = getValue(I.getArgOperand(0));
6794 SDValue Src = getValue(I.getArgOperand(1));
6795 SDValue Size = getValue(I.getArgOperand(2));
6796 assert((!MCI.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6797 "memcpy_inline needs constant size");
6798 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6799 Align DstAlign = MCI.getDestAlign().valueOrOne();
6800 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6801 bool isVol = MCI.isVolatile();
6802 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6803 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, DstAlign, SrcAlign,
6804 isVol, MCI.isForceInlined(), &I, std::nullopt,
6805 MachinePointerInfo(I.getArgOperand(0)),
6806 MachinePointerInfo(I.getArgOperand(1)),
6807 I.getAAMetadata(), BatchAA);
6808 updateDAGForMaybeTailCall(MC);
6809 return;
6810 }
6811 case Intrinsic::memset:
6812 case Intrinsic::memset_inline: {
6813 const auto &MSII = cast<MemSetInst>(I);
6814 SDValue Dst = getValue(I.getArgOperand(0));
6815 SDValue Value = getValue(I.getArgOperand(1));
6816 SDValue Size = getValue(I.getArgOperand(2));
6817 assert((!MSII.isForceInlined() || isa<ConstantSDNode>(Size)) &&
6818 "memset_inline needs constant size");
6819 // @llvm.memset defines 0 and 1 to both mean no alignment.
6820 Align DstAlign = MSII.getDestAlign().valueOrOne();
6821 bool isVol = MSII.isVolatile();
6822 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6823 SDValue MC = DAG.getMemset(
6824 Root, sdl, Dst, Value, Size, DstAlign, isVol, MSII.isForceInlined(),
6825 &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6826 updateDAGForMaybeTailCall(MC);
6827 return;
6828 }
6829 case Intrinsic::memmove: {
6830 const auto &MMI = cast<MemMoveInst>(I);
6831 SDValue Op1 = getValue(I.getArgOperand(0));
6832 SDValue Op2 = getValue(I.getArgOperand(1));
6833 SDValue Op3 = getValue(I.getArgOperand(2));
6834 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6835 Align DstAlign = MMI.getDestAlign().valueOrOne();
6836 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6837 bool isVol = MMI.isVolatile();
6838 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6839 SDValue MM = DAG.getMemmove(
6840 Root, sdl, Op1, Op2, Op3, DstAlign, SrcAlign, isVol, &I,
6841 /* OverrideTailCall */ std::nullopt,
6842 MachinePointerInfo(I.getArgOperand(0)),
6843 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), BatchAA);
6844 updateDAGForMaybeTailCall(MM);
6845 return;
6846 }
6847 case Intrinsic::memcpy_element_unordered_atomic: {
6848 auto &MI = cast<AnyMemCpyInst>(I);
6849 SDValue Dst = getValue(MI.getRawDest());
6850 SDValue Src = getValue(MI.getRawSource());
6851 SDValue Length = getValue(MI.getLength());
6852
6853 Type *LengthTy = MI.getLength()->getType();
6854 unsigned ElemSz = MI.getElementSizeInBytes();
6855 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6856 SDValue MC =
6857 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6858 isTC, MachinePointerInfo(MI.getRawDest()),
6859 MachinePointerInfo(MI.getRawSource()));
6860 updateDAGForMaybeTailCall(MC);
6861 return;
6862 }
6863 case Intrinsic::memmove_element_unordered_atomic: {
6864 auto &MI = cast<AnyMemMoveInst>(I);
6865 SDValue Dst = getValue(MI.getRawDest());
6866 SDValue Src = getValue(MI.getRawSource());
6867 SDValue Length = getValue(MI.getLength());
6868
6869 Type *LengthTy = MI.getLength()->getType();
6870 unsigned ElemSz = MI.getElementSizeInBytes();
6871 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6872 SDValue MC =
6873 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6874 isTC, MachinePointerInfo(MI.getRawDest()),
6875 MachinePointerInfo(MI.getRawSource()));
6876 updateDAGForMaybeTailCall(MC);
6877 return;
6878 }
6879 case Intrinsic::memset_element_unordered_atomic: {
6880 auto &MI = cast<AnyMemSetInst>(I);
6881 SDValue Dst = getValue(MI.getRawDest());
6882 SDValue Val = getValue(MI.getValue());
6883 SDValue Length = getValue(MI.getLength());
6884
6885 Type *LengthTy = MI.getLength()->getType();
6886 unsigned ElemSz = MI.getElementSizeInBytes();
6887 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6888 SDValue MC =
6889 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6890 isTC, MachinePointerInfo(MI.getRawDest()));
6891 updateDAGForMaybeTailCall(MC);
6892 return;
6893 }
6894 case Intrinsic::call_preallocated_setup: {
6895 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6896 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6897 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6898 getRoot(), SrcValue);
6899 setValue(&I, Res);
6900 DAG.setRoot(Res);
6901 return;
6902 }
6903 case Intrinsic::call_preallocated_arg: {
6904 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6905 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6906 SDValue Ops[3];
6907 Ops[0] = getRoot();
6908 Ops[1] = SrcValue;
6909 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6910 MVT::i32); // arg index
6911 SDValue Res = DAG.getNode(
6913 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6914 setValue(&I, Res);
6915 DAG.setRoot(Res.getValue(1));
6916 return;
6917 }
6918
6919 case Intrinsic::eh_typeid_for: {
6920 // Find the type id for the given typeinfo.
6921 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6922 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6923 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6924 setValue(&I, Res);
6925 return;
6926 }
6927
6928 case Intrinsic::eh_return_i32:
6929 case Intrinsic::eh_return_i64:
6930 DAG.getMachineFunction().setCallsEHReturn(true);
6931 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6932 MVT::Other,
6934 getValue(I.getArgOperand(0)),
6935 getValue(I.getArgOperand(1))));
6936 return;
6937 case Intrinsic::eh_unwind_init:
6938 DAG.getMachineFunction().setCallsUnwindInit(true);
6939 return;
6940 case Intrinsic::eh_dwarf_cfa:
6941 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6942 TLI.getPointerTy(DAG.getDataLayout()),
6943 getValue(I.getArgOperand(0))));
6944 return;
6945 case Intrinsic::eh_sjlj_callsite: {
6946 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6947 assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6948
6949 FuncInfo.setCurrentCallSite(CI->getZExtValue());
6950 return;
6951 }
6952 case Intrinsic::eh_sjlj_functioncontext: {
6953 // Get and store the index of the function context.
6954 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6955 AllocaInst *FnCtx =
6956 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6957 int FI = FuncInfo.StaticAllocaMap[FnCtx];
6959 return;
6960 }
6961 case Intrinsic::eh_sjlj_setjmp: {
6962 SDValue Ops[2];
6963 Ops[0] = getRoot();
6964 Ops[1] = getValue(I.getArgOperand(0));
6965 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6966 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6967 setValue(&I, Op.getValue(0));
6968 DAG.setRoot(Op.getValue(1));
6969 return;
6970 }
6971 case Intrinsic::eh_sjlj_longjmp:
6972 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6973 getRoot(), getValue(I.getArgOperand(0))));
6974 return;
6975 case Intrinsic::eh_sjlj_setup_dispatch:
6976 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6977 getRoot()));
6978 return;
6979 case Intrinsic::masked_gather:
6980 visitMaskedGather(I);
6981 return;
6982 case Intrinsic::masked_load:
6983 visitMaskedLoad(I);
6984 return;
6985 case Intrinsic::masked_scatter:
6986 visitMaskedScatter(I);
6987 return;
6988 case Intrinsic::masked_store:
6989 visitMaskedStore(I);
6990 return;
6991 case Intrinsic::masked_expandload:
6992 visitMaskedLoad(I, true /* IsExpanding */);
6993 return;
6994 case Intrinsic::masked_compressstore:
6995 visitMaskedStore(I, true /* IsCompressing */);
6996 return;
6997 case Intrinsic::powi:
6998 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6999 getValue(I.getArgOperand(1)), DAG));
7000 return;
7001 case Intrinsic::log:
7002 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7003 return;
7004 case Intrinsic::log2:
7005 setValue(&I,
7006 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7007 return;
7008 case Intrinsic::log10:
7009 setValue(&I,
7010 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7011 return;
7012 case Intrinsic::exp:
7013 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7014 return;
7015 case Intrinsic::exp2:
7016 setValue(&I,
7017 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
7018 return;
7019 case Intrinsic::pow:
7020 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
7021 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
7022 return;
7023 case Intrinsic::sqrt:
7024 case Intrinsic::fabs:
7025 case Intrinsic::sin:
7026 case Intrinsic::cos:
7027 case Intrinsic::tan:
7028 case Intrinsic::asin:
7029 case Intrinsic::acos:
7030 case Intrinsic::atan:
7031 case Intrinsic::sinh:
7032 case Intrinsic::cosh:
7033 case Intrinsic::tanh:
7034 case Intrinsic::exp10:
7035 case Intrinsic::floor:
7036 case Intrinsic::ceil:
7037 case Intrinsic::trunc:
7038 case Intrinsic::rint:
7039 case Intrinsic::nearbyint:
7040 case Intrinsic::round:
7041 case Intrinsic::roundeven:
7042 case Intrinsic::canonicalize: {
7043 unsigned Opcode;
7044 // clang-format off
7045 switch (Intrinsic) {
7046 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7047 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
7048 case Intrinsic::fabs: Opcode = ISD::FABS; break;
7049 case Intrinsic::sin: Opcode = ISD::FSIN; break;
7050 case Intrinsic::cos: Opcode = ISD::FCOS; break;
7051 case Intrinsic::tan: Opcode = ISD::FTAN; break;
7052 case Intrinsic::asin: Opcode = ISD::FASIN; break;
7053 case Intrinsic::acos: Opcode = ISD::FACOS; break;
7054 case Intrinsic::atan: Opcode = ISD::FATAN; break;
7055 case Intrinsic::sinh: Opcode = ISD::FSINH; break;
7056 case Intrinsic::cosh: Opcode = ISD::FCOSH; break;
7057 case Intrinsic::tanh: Opcode = ISD::FTANH; break;
7058 case Intrinsic::exp10: Opcode = ISD::FEXP10; break;
7059 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
7060 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
7061 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
7062 case Intrinsic::rint: Opcode = ISD::FRINT; break;
7063 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
7064 case Intrinsic::round: Opcode = ISD::FROUND; break;
7065 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
7066 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
7067 }
7068 // clang-format on
7069
7070 setValue(&I, DAG.getNode(Opcode, sdl,
7071 getValue(I.getArgOperand(0)).getValueType(),
7072 getValue(I.getArgOperand(0)), Flags));
7073 return;
7074 }
7075 case Intrinsic::atan2:
7076 setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
7077 getValue(I.getArgOperand(0)).getValueType(),
7078 getValue(I.getArgOperand(0)),
7079 getValue(I.getArgOperand(1)), Flags));
7080 return;
7081 case Intrinsic::lround:
7082 case Intrinsic::llround:
7083 case Intrinsic::lrint:
7084 case Intrinsic::llrint: {
7085 unsigned Opcode;
7086 // clang-format off
7087 switch (Intrinsic) {
7088 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7089 case Intrinsic::lround: Opcode = ISD::LROUND; break;
7090 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
7091 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
7092 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
7093 }
7094 // clang-format on
7095
7096 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7097 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
7098 getValue(I.getArgOperand(0))));
7099 return;
7100 }
7101 case Intrinsic::minnum:
7102 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
7103 getValue(I.getArgOperand(0)).getValueType(),
7104 getValue(I.getArgOperand(0)),
7105 getValue(I.getArgOperand(1)), Flags));
7106 return;
7107 case Intrinsic::maxnum:
7108 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
7109 getValue(I.getArgOperand(0)).getValueType(),
7110 getValue(I.getArgOperand(0)),
7111 getValue(I.getArgOperand(1)), Flags));
7112 return;
7113 case Intrinsic::minimum:
7114 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
7115 getValue(I.getArgOperand(0)).getValueType(),
7116 getValue(I.getArgOperand(0)),
7117 getValue(I.getArgOperand(1)), Flags));
7118 return;
7119 case Intrinsic::maximum:
7120 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
7121 getValue(I.getArgOperand(0)).getValueType(),
7122 getValue(I.getArgOperand(0)),
7123 getValue(I.getArgOperand(1)), Flags));
7124 return;
7125 case Intrinsic::minimumnum:
7126 setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
7127 getValue(I.getArgOperand(0)).getValueType(),
7128 getValue(I.getArgOperand(0)),
7129 getValue(I.getArgOperand(1)), Flags));
7130 return;
7131 case Intrinsic::maximumnum:
7132 setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
7133 getValue(I.getArgOperand(0)).getValueType(),
7134 getValue(I.getArgOperand(0)),
7135 getValue(I.getArgOperand(1)), Flags));
7136 return;
7137 case Intrinsic::copysign:
7138 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
7139 getValue(I.getArgOperand(0)).getValueType(),
7140 getValue(I.getArgOperand(0)),
7141 getValue(I.getArgOperand(1)), Flags));
7142 return;
7143 case Intrinsic::ldexp:
7144 setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
7145 getValue(I.getArgOperand(0)).getValueType(),
7146 getValue(I.getArgOperand(0)),
7147 getValue(I.getArgOperand(1)), Flags));
7148 return;
7149 case Intrinsic::modf:
7150 case Intrinsic::sincos:
7151 case Intrinsic::sincospi:
7152 case Intrinsic::frexp: {
7153 unsigned Opcode;
7154 switch (Intrinsic) {
7155 default:
7156 llvm_unreachable("unexpected intrinsic");
7157 case Intrinsic::sincos:
7158 Opcode = ISD::FSINCOS;
7159 break;
7160 case Intrinsic::sincospi:
7161 Opcode = ISD::FSINCOSPI;
7162 break;
7163 case Intrinsic::modf:
7164 Opcode = ISD::FMODF;
7165 break;
7166 case Intrinsic::frexp:
7167 Opcode = ISD::FFREXP;
7168 break;
7169 }
7170 SmallVector<EVT, 2> ValueVTs;
7171 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
7172 SDVTList VTs = DAG.getVTList(ValueVTs);
7173 setValue(
7174 &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
7175 return;
7176 }
7177 case Intrinsic::arithmetic_fence: {
7178 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7179 getValue(I.getArgOperand(0)).getValueType(),
7180 getValue(I.getArgOperand(0)), Flags));
7181 return;
7182 }
7183 case Intrinsic::fma:
7184 setValue(&I, DAG.getNode(
7185 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7186 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7187 getValue(I.getArgOperand(2)), Flags));
7188 return;
7189#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
7190 case Intrinsic::INTRINSIC:
7191#include "llvm/IR/ConstrainedOps.def"
7192 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7193 return;
7194#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7195#include "llvm/IR/VPIntrinsics.def"
7196 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7197 return;
7198 case Intrinsic::fptrunc_round: {
7199 // Get the last argument, the metadata and convert it to an integer in the
7200 // call
7201 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7202 std::optional<RoundingMode> RoundMode =
7203 convertStrToRoundingMode(cast<MDString>(MD)->getString());
7204
7205 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7206
7207 // Propagate fast-math-flags from IR to node(s).
7208 SDNodeFlags Flags;
7209 Flags.copyFMF(*cast<FPMathOperator>(&I));
7210 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7211
7213 Result = DAG.getNode(
7214 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7215 DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7216 setValue(&I, Result);
7217
7218 return;
7219 }
7220 case Intrinsic::fmuladd: {
7221 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7222 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7223 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7224 setValue(&I, DAG.getNode(ISD::FMA, sdl,
7225 getValue(I.getArgOperand(0)).getValueType(),
7226 getValue(I.getArgOperand(0)),
7227 getValue(I.getArgOperand(1)),
7228 getValue(I.getArgOperand(2)), Flags));
7229 } else if (TLI.isOperationLegalOrCustom(ISD::FMULADD, VT)) {
7230 // TODO: Support splitting the vector.
7231 setValue(&I, DAG.getNode(ISD::FMULADD, sdl,
7232 getValue(I.getArgOperand(0)).getValueType(),
7233 getValue(I.getArgOperand(0)),
7234 getValue(I.getArgOperand(1)),
7235 getValue(I.getArgOperand(2)), Flags));
7236 } else {
7237 // TODO: Intrinsic calls should have fast-math-flags.
7238 SDValue Mul = DAG.getNode(
7239 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7240 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7241 SDValue Add = DAG.getNode(ISD::FADD, sdl,
7242 getValue(I.getArgOperand(0)).getValueType(),
7243 Mul, getValue(I.getArgOperand(2)), Flags);
7244 setValue(&I, Add);
7245 }
7246 return;
7247 }
7248 case Intrinsic::fptosi_sat: {
7249 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7250 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7251 getValue(I.getArgOperand(0)),
7252 DAG.getValueType(VT.getScalarType())));
7253 return;
7254 }
7255 case Intrinsic::fptoui_sat: {
7256 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7257 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7258 getValue(I.getArgOperand(0)),
7259 DAG.getValueType(VT.getScalarType())));
7260 return;
7261 }
7262 case Intrinsic::convert_from_arbitrary_fp: {
7263 // Extract format metadata and convert to semantics enum.
7264 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7265 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7266 StringRef FormatStr = cast<MDString>(MD)->getString();
7267 const fltSemantics *SrcSem =
7269 if (!SrcSem) {
7270 DAG.getContext()->emitError(
7271 "convert_from_arbitrary_fp: not implemented format '" + FormatStr +
7272 "'");
7273 setValue(&I, DAG.getPOISON(DstVT));
7274 return;
7275 }
7277
7278 SDValue IntVal = getValue(I.getArgOperand(0));
7279
7280 // Emit ISD::CONVERT_FROM_ARBITRARY_FP node.
7281 SDValue SemConst =
7282 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7283 setValue(&I, DAG.getNode(ISD::CONVERT_FROM_ARBITRARY_FP, sdl, DstVT, IntVal,
7284 SemConst));
7285 return;
7286 }
7287 case Intrinsic::convert_to_arbitrary_fp: {
7288 // Extract format metadata and convert to semantics enum.
7289 EVT DstVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7290 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7291 StringRef FormatStr = cast<MDString>(MD)->getString();
7292 const fltSemantics *DstSem =
7294 if (!DstSem) {
7295 DAG.getContext()->emitError(
7296 "convert_to_arbitrary_fp: not implemented format '" + FormatStr +
7297 "'");
7298 setValue(&I, DAG.getPOISON(DstVT));
7299 return;
7300 }
7302
7303 Metadata *RoundMD =
7304 cast<MetadataAsValue>(I.getArgOperand(2))->getMetadata();
7305 StringRef RoundStr = cast<MDString>(RoundMD)->getString();
7306 std::optional<RoundingMode> RoundMode = convertStrToRoundingMode(RoundStr);
7307 assert(RoundMode && *RoundMode != RoundingMode::Dynamic &&
7308 "Dynamic rounding mode should have been rejected by the verifier");
7309
7310 uint64_t Saturate =
7311 cast<ConstantInt>(I.getArgOperand(3))->getZExtValue() ? 1 : 0;
7312
7313 SDValue FloatVal = getValue(I.getArgOperand(0));
7314
7315 SDValue SemConst =
7316 DAG.getTargetConstant(static_cast<int>(SemEnum), sdl, MVT::i32);
7317 SDValue RoundConst =
7318 DAG.getTargetConstant(static_cast<int>(*RoundMode), sdl, MVT::i32);
7319 SDValue SatConst = DAG.getTargetConstant(Saturate, sdl, MVT::i32);
7320 setValue(&I, DAG.getNode(ISD::CONVERT_TO_ARBITRARY_FP, sdl, DstVT, FloatVal,
7321 SemConst, RoundConst, SatConst));
7322 return;
7323 }
7324 case Intrinsic::set_rounding:
7325 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7326 {getRoot(), getValue(I.getArgOperand(0))});
7327 setValue(&I, Res);
7328 DAG.setRoot(Res.getValue(0));
7329 return;
7330 case Intrinsic::is_fpclass: {
7331 const DataLayout DLayout = DAG.getDataLayout();
7332 EVT DestVT = TLI.getValueType(DLayout, I.getType());
7333 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7334 FPClassTest Test = static_cast<FPClassTest>(
7335 cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7336 MachineFunction &MF = DAG.getMachineFunction();
7337 const Function &F = MF.getFunction();
7338 SDValue Op = getValue(I.getArgOperand(0));
7339 SDNodeFlags Flags;
7340 Flags.setNoFPExcept(
7341 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7342 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7343 // expansion can use illegal types. Making expansion early allows
7344 // legalizing these types prior to selection.
7345 if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7346 !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7347 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7348 setValue(&I, Result);
7349 return;
7350 }
7351
7352 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7353 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7354 setValue(&I, V);
7355 return;
7356 }
7357 case Intrinsic::get_fpenv: {
7358 const DataLayout DLayout = DAG.getDataLayout();
7359 EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7360 Align TempAlign = DAG.getEVTAlign(EnvVT);
7361 SDValue Chain = getRoot();
7362 // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7363 // and temporary storage in stack.
7364 if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7365 Res = DAG.getNode(
7366 ISD::GET_FPENV, sdl,
7367 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7368 MVT::Other),
7369 Chain);
7370 } else {
7371 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7372 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7373 auto MPI =
7374 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7375 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7377 TempAlign);
7378 Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7379 Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7380 }
7381 setValue(&I, Res);
7382 DAG.setRoot(Res.getValue(1));
7383 return;
7384 }
7385 case Intrinsic::set_fpenv: {
7386 const DataLayout DLayout = DAG.getDataLayout();
7387 SDValue Env = getValue(I.getArgOperand(0));
7388 EVT EnvVT = Env.getValueType();
7389 Align TempAlign = DAG.getEVTAlign(EnvVT);
7390 SDValue Chain = getRoot();
7391 // If SET_FPENV is custom or legal, use it. Otherwise use loading
7392 // environment from memory.
7393 if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7394 Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7395 } else {
7396 // Allocate space in stack, copy environment bits into it and use this
7397 // memory in SET_FPENV_MEM.
7398 SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7399 int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7400 auto MPI =
7401 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7402 Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7404 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7406 TempAlign);
7407 Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7408 }
7409 DAG.setRoot(Chain);
7410 return;
7411 }
7412 case Intrinsic::reset_fpenv:
7413 DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7414 return;
7415 case Intrinsic::get_fpmode:
7416 Res = DAG.getNode(
7417 ISD::GET_FPMODE, sdl,
7418 DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7419 MVT::Other),
7420 DAG.getRoot());
7421 setValue(&I, Res);
7422 DAG.setRoot(Res.getValue(1));
7423 return;
7424 case Intrinsic::set_fpmode:
7425 Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7426 getValue(I.getArgOperand(0)));
7427 DAG.setRoot(Res);
7428 return;
7429 case Intrinsic::reset_fpmode: {
7430 Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7431 DAG.setRoot(Res);
7432 return;
7433 }
7434 case Intrinsic::pcmarker: {
7435 SDValue Tmp = getValue(I.getArgOperand(0));
7436 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7437 return;
7438 }
7439 case Intrinsic::readcyclecounter: {
7440 SDValue Op = getRoot();
7441 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7442 DAG.getVTList(MVT::i64, MVT::Other), Op);
7443 setValue(&I, Res);
7444 DAG.setRoot(Res.getValue(1));
7445 return;
7446 }
7447 case Intrinsic::readsteadycounter: {
7448 SDValue Op = getRoot();
7449 Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7450 DAG.getVTList(MVT::i64, MVT::Other), Op);
7451 setValue(&I, Res);
7452 DAG.setRoot(Res.getValue(1));
7453 return;
7454 }
7455 case Intrinsic::bitreverse:
7456 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7457 getValue(I.getArgOperand(0)).getValueType(),
7458 getValue(I.getArgOperand(0))));
7459 return;
7460 case Intrinsic::bswap:
7461 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7462 getValue(I.getArgOperand(0)).getValueType(),
7463 getValue(I.getArgOperand(0))));
7464 return;
7465 case Intrinsic::cttz: {
7466 SDValue Arg = getValue(I.getArgOperand(0));
7467 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7468 EVT Ty = Arg.getValueType();
7469 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_POISON,
7470 sdl, Ty, Arg));
7471 return;
7472 }
7473 case Intrinsic::ctlz: {
7474 SDValue Arg = getValue(I.getArgOperand(0));
7475 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7476 EVT Ty = Arg.getValueType();
7477 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_POISON,
7478 sdl, Ty, Arg));
7479 return;
7480 }
7481 case Intrinsic::ctpop: {
7482 SDValue Arg = getValue(I.getArgOperand(0));
7483 EVT Ty = Arg.getValueType();
7484 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7485 return;
7486 }
7487 case Intrinsic::fshl:
7488 case Intrinsic::fshr: {
7489 bool IsFSHL = Intrinsic == Intrinsic::fshl;
7490 SDValue X = getValue(I.getArgOperand(0));
7491 SDValue Y = getValue(I.getArgOperand(1));
7492 SDValue Z = getValue(I.getArgOperand(2));
7493 EVT VT = X.getValueType();
7494
7495 if (X == Y) {
7496 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7497 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7498 } else {
7499 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7500 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7501 }
7502 return;
7503 }
7504 case Intrinsic::clmul: {
7505 SDValue X = getValue(I.getArgOperand(0));
7506 SDValue Y = getValue(I.getArgOperand(1));
7507 setValue(&I, DAG.getNode(ISD::CLMUL, sdl, X.getValueType(), X, Y));
7508 return;
7509 }
7510 case Intrinsic::pext: {
7511 SDValue X = getValue(I.getArgOperand(0));
7512 SDValue Y = getValue(I.getArgOperand(1));
7513 setValue(&I, DAG.getNode(ISD::PEXT, sdl, X.getValueType(), X, Y));
7514 return;
7515 }
7516 case Intrinsic::pdep: {
7517 SDValue X = getValue(I.getArgOperand(0));
7518 SDValue Y = getValue(I.getArgOperand(1));
7519 setValue(&I, DAG.getNode(ISD::PDEP, sdl, X.getValueType(), X, Y));
7520 return;
7521 }
7522 case Intrinsic::sadd_sat: {
7523 SDValue Op1 = getValue(I.getArgOperand(0));
7524 SDValue Op2 = getValue(I.getArgOperand(1));
7525 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7526 return;
7527 }
7528 case Intrinsic::uadd_sat: {
7529 SDValue Op1 = getValue(I.getArgOperand(0));
7530 SDValue Op2 = getValue(I.getArgOperand(1));
7531 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7532 return;
7533 }
7534 case Intrinsic::ssub_sat: {
7535 SDValue Op1 = getValue(I.getArgOperand(0));
7536 SDValue Op2 = getValue(I.getArgOperand(1));
7537 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7538 return;
7539 }
7540 case Intrinsic::usub_sat: {
7541 SDValue Op1 = getValue(I.getArgOperand(0));
7542 SDValue Op2 = getValue(I.getArgOperand(1));
7543 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7544 return;
7545 }
7546 case Intrinsic::sshl_sat:
7547 case Intrinsic::ushl_sat: {
7548 SDValue Op1 = getValue(I.getArgOperand(0));
7549 SDValue Op2 = getValue(I.getArgOperand(1));
7550
7551 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
7552 Op1.getValueType(), DAG.getDataLayout());
7553
7554 // Coerce the shift amount to the right type if we can. This exposes the
7555 // truncate or zext to optimization early.
7556 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
7557 assert(ShiftTy.getSizeInBits() >=
7559 "Unexpected shift type");
7560 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
7561 }
7562
7563 unsigned Opc =
7564 Intrinsic == Intrinsic::sshl_sat ? ISD::SSHLSAT : ISD::USHLSAT;
7565 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1, Op2));
7566 return;
7567 }
7568 case Intrinsic::smul_fix:
7569 case Intrinsic::umul_fix:
7570 case Intrinsic::smul_fix_sat:
7571 case Intrinsic::umul_fix_sat: {
7572 SDValue Op1 = getValue(I.getArgOperand(0));
7573 SDValue Op2 = getValue(I.getArgOperand(1));
7574 SDValue Op3 = getValue(I.getArgOperand(2));
7575 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7576 Op1.getValueType(), Op1, Op2, Op3));
7577 return;
7578 }
7579 case Intrinsic::sdiv_fix:
7580 case Intrinsic::udiv_fix:
7581 case Intrinsic::sdiv_fix_sat:
7582 case Intrinsic::udiv_fix_sat: {
7583 SDValue Op1 = getValue(I.getArgOperand(0));
7584 SDValue Op2 = getValue(I.getArgOperand(1));
7585 SDValue Op3 = getValue(I.getArgOperand(2));
7587 Op1, Op2, Op3, DAG, TLI));
7588 return;
7589 }
7590 case Intrinsic::smax: {
7591 SDValue Op1 = getValue(I.getArgOperand(0));
7592 SDValue Op2 = getValue(I.getArgOperand(1));
7593 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7594 return;
7595 }
7596 case Intrinsic::smin: {
7597 SDValue Op1 = getValue(I.getArgOperand(0));
7598 SDValue Op2 = getValue(I.getArgOperand(1));
7599 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7600 return;
7601 }
7602 case Intrinsic::umax: {
7603 SDValue Op1 = getValue(I.getArgOperand(0));
7604 SDValue Op2 = getValue(I.getArgOperand(1));
7605 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7606 return;
7607 }
7608 case Intrinsic::umin: {
7609 SDValue Op1 = getValue(I.getArgOperand(0));
7610 SDValue Op2 = getValue(I.getArgOperand(1));
7611 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7612 return;
7613 }
7614 case Intrinsic::abs: {
7615 SDValue Op1 = getValue(I.getArgOperand(0));
7616 bool IntMinIsPoison = cast<ConstantInt>(I.getArgOperand(1))->isOne();
7617 unsigned Opc = IntMinIsPoison ? ISD::ABS_MIN_POISON : ISD::ABS;
7618 setValue(&I, DAG.getNode(Opc, sdl, Op1.getValueType(), Op1));
7619 return;
7620 }
7621 case Intrinsic::scmp: {
7622 SDValue Op1 = getValue(I.getArgOperand(0));
7623 SDValue Op2 = getValue(I.getArgOperand(1));
7624 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7625 setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7626 break;
7627 }
7628 case Intrinsic::ucmp: {
7629 SDValue Op1 = getValue(I.getArgOperand(0));
7630 SDValue Op2 = getValue(I.getArgOperand(1));
7631 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7632 setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7633 break;
7634 }
7635 case Intrinsic::stackaddress:
7636 case Intrinsic::stacksave: {
7637 unsigned SDOpcode = Intrinsic == Intrinsic::stackaddress ? ISD::STACKADDRESS
7639 SDValue Op = getRoot();
7640 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7641 Res = DAG.getNode(SDOpcode, sdl, DAG.getVTList(VT, MVT::Other), Op);
7642 setValue(&I, Res);
7643 DAG.setRoot(Res.getValue(1));
7644 return;
7645 }
7646 case Intrinsic::stackrestore:
7647 Res = getValue(I.getArgOperand(0));
7648 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7649 return;
7650 case Intrinsic::get_dynamic_area_offset: {
7651 SDValue Op = getRoot();
7652 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7653 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7654 Op);
7655 DAG.setRoot(Op);
7656 setValue(&I, Res);
7657 return;
7658 }
7659 case Intrinsic::stackguard: {
7660 MachineFunction &MF = DAG.getMachineFunction();
7661 const Module &M = *MF.getFunction().getParent();
7662 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7663 SDValue Chain = getRoot();
7664 if (TLI.useLoadStackGuardNode(M)) {
7665 Res = getLoadStackGuard(DAG, sdl, Chain);
7666 Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7667 } else {
7668 const Value *Global = TLI.getSDagStackGuard(M, DAG.getLibcalls());
7669 if (!Global) {
7670 LLVMContext &Ctx = *DAG.getContext();
7671 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
7672 setValue(&I, DAG.getPOISON(PtrTy));
7673 return;
7674 }
7675
7676 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7677 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7678 MachinePointerInfo(Global, 0), Align,
7680 }
7681 // Mix the cookie with FP if enabled. Skip if using LOAD_STACK_GUARD
7682 // with post-RA mixing (AArch64 MSVCRT), as the mixing will be done during
7683 // post-RA expansion of LOAD_STACK_GUARD.
7684 if (TLI.useStackGuardMixFP() && !TLI.useLoadStackGuardNode(M))
7685 Res = TLI.emitStackGuardMixFP(DAG, Res, sdl);
7686 DAG.setRoot(Chain);
7687 setValue(&I, Res);
7688 return;
7689 }
7690 case Intrinsic::stackprotector: {
7691 // Emit code into the DAG to store the stack guard onto the stack.
7692 MachineFunction &MF = DAG.getMachineFunction();
7693 MachineFrameInfo &MFI = MF.getFrameInfo();
7694 const Module &M = *MF.getFunction().getParent();
7695 SDValue Src, Chain = getRoot();
7696
7697 if (TLI.useLoadStackGuardNode(M))
7698 Src = getLoadStackGuard(DAG, sdl, Chain);
7699 else
7700 Src = getValue(I.getArgOperand(0)); // The guard's value.
7701
7702 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7703
7704 int FI = FuncInfo.StaticAllocaMap[Slot];
7705 MFI.setStackProtectorIndex(FI);
7706 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7707
7708 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7709
7710 // Store the stack protector onto the stack.
7711 Res = DAG.getStore(
7712 Chain, sdl, Src, FIN,
7713 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7714 MaybeAlign(), MachineMemOperand::MOVolatile);
7715 setValue(&I, Res);
7716 DAG.setRoot(Res);
7717 return;
7718 }
7719 case Intrinsic::objectsize:
7720 llvm_unreachable("llvm.objectsize.* should have been lowered already");
7721
7722 case Intrinsic::is_constant:
7723 llvm_unreachable("llvm.is.constant.* should have been lowered already");
7724
7725 case Intrinsic::annotation:
7726 case Intrinsic::ptr_annotation:
7727 case Intrinsic::launder_invariant_group:
7728 case Intrinsic::strip_invariant_group:
7729 // Drop the intrinsic, but forward the value
7730 setValue(&I, getValue(I.getOperand(0)));
7731 return;
7732
7733 case Intrinsic::type_test:
7734 case Intrinsic::public_type_test:
7735 case Intrinsic::type_checked_load:
7736 case Intrinsic::type_checked_load_relative: {
7737 // These intrinsics are expected to be lowered by the LowerTypeTests pass
7738 // before code generation. Surviving until here usually indicates a
7739 // misconfiguration, for instance when devirtualization is enabled but LTO
7740 // does not actually run.
7741 DAG.getContext()->diagnose(DiagnosticInfoUnsupported(
7742 *I.getFunction(),
7743 Intrinsic::getBaseName(Intrinsic) +
7744 " intrinsic must be lowered by the LowerTypeTests pass "
7745 "before code generation",
7746 sdl.getDebugLoc()));
7747
7748 // Lower the result to poison so that compilation can continue and collect
7749 // any further diagnostics.
7750 setValueToPoison(&I, sdl);
7751 return;
7752 }
7753
7754 case Intrinsic::assume:
7755 case Intrinsic::experimental_noalias_scope_decl:
7756 case Intrinsic::var_annotation:
7757 case Intrinsic::sideeffect:
7758 // Discard annotate attributes, noalias scope declarations, assumptions, and
7759 // artificial side-effects.
7760 return;
7761
7762 case Intrinsic::codeview_annotation: {
7763 // Emit a label associated with this metadata.
7764 MachineFunction &MF = DAG.getMachineFunction();
7765 MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7766 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7767 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7768 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7769 DAG.setRoot(Res);
7770 return;
7771 }
7772
7773 case Intrinsic::init_trampoline: {
7774 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7775
7776 SDValue Ops[6];
7777 Ops[0] = getRoot();
7778 Ops[1] = getValue(I.getArgOperand(0));
7779 Ops[2] = getValue(I.getArgOperand(1));
7780 Ops[3] = getValue(I.getArgOperand(2));
7781 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7782 Ops[5] = DAG.getSrcValue(F);
7783
7784 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7785
7786 DAG.setRoot(Res);
7787 return;
7788 }
7789 case Intrinsic::adjust_trampoline:
7790 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7791 TLI.getPointerTy(DAG.getDataLayout()),
7792 getValue(I.getArgOperand(0))));
7793 return;
7794 case Intrinsic::gcroot: {
7795 assert(DAG.getMachineFunction().getFunction().hasGC() &&
7796 "only valid in functions with gc specified, enforced by Verifier");
7797 assert(GFI && "implied by previous");
7798 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7799 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7800
7801 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7802 GFI->addStackRoot(FI->getIndex(), TypeMap);
7803 return;
7804 }
7805 case Intrinsic::gcread:
7806 case Intrinsic::gcwrite:
7807 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7808 case Intrinsic::get_rounding:
7809 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7810 setValue(&I, Res);
7811 DAG.setRoot(Res.getValue(1));
7812 return;
7813
7814 case Intrinsic::expect:
7815 case Intrinsic::expect_with_probability:
7816 // Just replace __builtin_expect(exp, c) and
7817 // __builtin_expect_with_probability(exp, c, p) with EXP.
7818 setValue(&I, getValue(I.getArgOperand(0)));
7819 return;
7820
7821 case Intrinsic::ubsantrap:
7822 case Intrinsic::debugtrap:
7823 case Intrinsic::trap: {
7824 StringRef TrapFuncName =
7825 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7826 if (TrapFuncName.empty()) {
7827 switch (Intrinsic) {
7828 case Intrinsic::trap:
7829 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7830 break;
7831 case Intrinsic::debugtrap:
7832 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7833 break;
7834 case Intrinsic::ubsantrap:
7835 DAG.setRoot(DAG.getNode(
7836 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7837 DAG.getTargetConstant(
7838 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7839 MVT::i32)));
7840 break;
7841 default: llvm_unreachable("unknown trap intrinsic");
7842 }
7843 DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7844 I.hasFnAttr(Attribute::NoMerge));
7845 return;
7846 }
7848 if (Intrinsic == Intrinsic::ubsantrap) {
7849 Value *Arg = I.getArgOperand(0);
7850 Args.emplace_back(Arg, getValue(Arg));
7851 }
7852
7853 TargetLowering::CallLoweringInfo CLI(DAG);
7854 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7855 CallingConv::C, I.getType(),
7856 DAG.getExternalSymbol(TrapFuncName.data(),
7857 TLI.getPointerTy(DAG.getDataLayout())),
7858 std::move(Args));
7859 CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7860 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7861 DAG.setRoot(Result.second);
7862 return;
7863 }
7864
7865 case Intrinsic::allow_runtime_check:
7866 case Intrinsic::allow_ubsan_check:
7867 setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7868 return;
7869
7870 case Intrinsic::uadd_with_overflow:
7871 case Intrinsic::sadd_with_overflow:
7872 case Intrinsic::usub_with_overflow:
7873 case Intrinsic::ssub_with_overflow:
7874 case Intrinsic::umul_with_overflow:
7875 case Intrinsic::smul_with_overflow: {
7877 switch (Intrinsic) {
7878 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7879 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7880 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7881 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7882 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7883 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7884 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7885 }
7886 SDValue Op1 = getValue(I.getArgOperand(0));
7887 SDValue Op2 = getValue(I.getArgOperand(1));
7888
7889 EVT ResultVT = Op1.getValueType();
7890 EVT OverflowVT = ResultVT.changeElementType(*Context, MVT::i1);
7891
7892 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7893 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7894 return;
7895 }
7896 case Intrinsic::prefetch: {
7897 SDValue Ops[5];
7898 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7900 Ops[0] = DAG.getRoot();
7901 Ops[1] = getValue(I.getArgOperand(0));
7902 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7903 MVT::i32);
7904 Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7905 MVT::i32);
7906 Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7907 MVT::i32);
7908 SDValue Result = DAG.getMemIntrinsicNode(
7909 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7910 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7911 /* align */ std::nullopt, Flags);
7912
7913 // Chain the prefetch in parallel with any pending loads, to stay out of
7914 // the way of later optimizations.
7915 PendingLoads.push_back(Result);
7916 Result = getRoot();
7917 DAG.setRoot(Result);
7918 return;
7919 }
7920 case Intrinsic::lifetime_start:
7921 case Intrinsic::lifetime_end: {
7922 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7923 // Stack coloring is not enabled in O0, discard region information.
7924 if (TM.getOptLevel() == CodeGenOptLevel::None)
7925 return;
7926
7927 const AllocaInst *LifetimeObject = dyn_cast<AllocaInst>(I.getArgOperand(0));
7928 if (!LifetimeObject)
7929 return;
7930
7931 // First check that the Alloca is static, otherwise it won't have a
7932 // valid frame index.
7933 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7934 if (SI == FuncInfo.StaticAllocaMap.end())
7935 return;
7936
7937 const int FrameIndex = SI->second;
7938 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex);
7939 DAG.setRoot(Res);
7940 return;
7941 }
7942 case Intrinsic::pseudoprobe: {
7943 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7944 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7945 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7946 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7947 DAG.setRoot(Res);
7948 return;
7949 }
7950 case Intrinsic::invariant_start:
7951 // Discard region information.
7952 setValue(&I,
7953 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7954 return;
7955 case Intrinsic::invariant_end:
7956 // Discard region information.
7957 return;
7958 case Intrinsic::clear_cache: {
7959 SDValue InputChain = DAG.getRoot();
7960 SDValue StartVal = getValue(I.getArgOperand(0));
7961 SDValue EndVal = getValue(I.getArgOperand(1));
7962 Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7963 {InputChain, StartVal, EndVal});
7964 setValue(&I, Res);
7965 DAG.setRoot(Res);
7966 return;
7967 }
7968 case Intrinsic::donothing:
7969 case Intrinsic::seh_try_begin:
7970 case Intrinsic::seh_scope_begin:
7971 case Intrinsic::seh_try_end:
7972 case Intrinsic::seh_scope_end:
7973 // ignore
7974 return;
7975 case Intrinsic::experimental_stackmap:
7976 visitStackmap(I);
7977 return;
7978 case Intrinsic::experimental_patchpoint_void:
7979 case Intrinsic::experimental_patchpoint:
7980 visitPatchpoint(I);
7981 return;
7982 case Intrinsic::experimental_gc_statepoint:
7984 return;
7985 case Intrinsic::experimental_gc_result:
7986 visitGCResult(cast<GCResultInst>(I));
7987 return;
7988 case Intrinsic::experimental_gc_relocate:
7989 visitGCRelocate(cast<GCRelocateInst>(I));
7990 return;
7991 case Intrinsic::instrprof_cover:
7992 llvm_unreachable("instrprof failed to lower a cover");
7993 case Intrinsic::instrprof_increment:
7994 llvm_unreachable("instrprof failed to lower an increment");
7995 case Intrinsic::instrprof_timestamp:
7996 llvm_unreachable("instrprof failed to lower a timestamp");
7997 case Intrinsic::instrprof_value_profile:
7998 llvm_unreachable("instrprof failed to lower a value profiling call");
7999 case Intrinsic::instrprof_mcdc_parameters:
8000 llvm_unreachable("instrprof failed to lower mcdc parameters");
8001 case Intrinsic::instrprof_mcdc_tvbitmap_update:
8002 llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
8003 case Intrinsic::localescape: {
8004 MachineFunction &MF = DAG.getMachineFunction();
8005 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
8006
8007 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
8008 // is the same on all targets.
8009 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
8010 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
8011 if (isa<ConstantPointerNull>(Arg))
8012 continue; // Skip null pointers. They represent a hole in index space.
8013 AllocaInst *Slot = cast<AllocaInst>(Arg);
8014 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
8015 "can only escape static allocas");
8016 int FI = FuncInfo.StaticAllocaMap[Slot];
8017 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8019 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
8020 TII->get(TargetOpcode::LOCAL_ESCAPE))
8021 .addSym(FrameAllocSym)
8022 .addFrameIndex(FI);
8023 }
8024
8025 return;
8026 }
8027
8028 case Intrinsic::localrecover: {
8029 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
8030 MachineFunction &MF = DAG.getMachineFunction();
8031
8032 // Get the symbol that defines the frame offset.
8033 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
8034 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
8035 unsigned IdxVal =
8036 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
8037 MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
8039
8040 Value *FP = I.getArgOperand(1);
8041 SDValue FPVal = getValue(FP);
8042 EVT PtrVT = FPVal.getValueType();
8043
8044 // Create a MCSymbol for the label to avoid any target lowering
8045 // that would make this PC relative.
8046 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
8047 SDValue OffsetVal =
8048 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
8049
8050 // Add the offset to the FP.
8051 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
8052 setValue(&I, Add);
8053
8054 return;
8055 }
8056
8057 case Intrinsic::fake_use: {
8058 Value *V = I.getArgOperand(0);
8059 SDValue Ops[2];
8060 // For Values not declared or previously used in this basic block, the
8061 // NodeMap will not have an entry, and `getValue` will assert if V has no
8062 // valid register value.
8063 auto FakeUseValue = [&]() -> SDValue {
8064 SDValue &N = NodeMap[V];
8065 if (N.getNode())
8066 return N;
8067
8068 // If there's a virtual register allocated and initialized for this
8069 // value, use it.
8070 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
8071 return copyFromReg;
8072 // FIXME: Do we want to preserve constants? It seems pointless.
8073 if (isa<Constant>(V))
8074 return getValue(V);
8075 return SDValue();
8076 }();
8077 if (!FakeUseValue || FakeUseValue.isUndef())
8078 return;
8079 Ops[0] = getRoot();
8080 Ops[1] = FakeUseValue;
8081 // Also, do not translate a fake use with an undef operand, or any other
8082 // empty SDValues.
8083 if (!Ops[1] || Ops[1].isUndef())
8084 return;
8085 DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
8086 return;
8087 }
8088
8089 case Intrinsic::reloc_none: {
8090 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
8091 StringRef SymbolName = cast<MDString>(MD)->getString();
8092 SDValue Ops[2] = {
8093 getRoot(),
8094 DAG.getTargetExternalSymbol(
8095 SymbolName.data(), TLI.getProgramPointerTy(DAG.getDataLayout()))};
8096 DAG.setRoot(DAG.getNode(ISD::RELOC_NONE, sdl, MVT::Other, Ops));
8097 return;
8098 }
8099
8100 case Intrinsic::cond_loop: {
8101 SDValue InputChain = DAG.getRoot();
8102 SDValue P = getValue(I.getArgOperand(0));
8103 Res = DAG.getNode(ISD::COND_LOOP, sdl, DAG.getVTList(MVT::Other),
8104 {InputChain, P});
8105 setValue(&I, Res);
8106 DAG.setRoot(Res);
8107 return;
8108 }
8109
8110 case Intrinsic::eh_exceptionpointer:
8111 case Intrinsic::eh_exceptioncode: {
8112 // Get the exception pointer vreg, copy from it, and resize it to fit.
8113 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
8114 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
8115 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
8116 Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
8117 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
8118 if (Intrinsic == Intrinsic::eh_exceptioncode)
8119 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
8120 setValue(&I, N);
8121 return;
8122 }
8123 case Intrinsic::xray_customevent: {
8124 // Here we want to make sure that the intrinsic behaves as if it has a
8125 // specific calling convention.
8126 const auto &Triple = DAG.getTarget().getTargetTriple();
8127 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8128 Triple.getArch() != Triple::hexagon)
8129 return;
8130
8132
8133 // We want to say that we always want the arguments in registers.
8134 SDValue LogEntryVal = getValue(I.getArgOperand(0));
8135 SDValue StrSizeVal = getValue(I.getArgOperand(1));
8136 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8137 SDValue Chain = getRoot();
8138 Ops.push_back(LogEntryVal);
8139 Ops.push_back(StrSizeVal);
8140 Ops.push_back(Chain);
8141
8142 // We need to enforce the calling convention for the callsite, so that
8143 // argument ordering is enforced correctly, and that register allocation can
8144 // see that some registers may be assumed clobbered and have to preserve
8145 // them across calls to the intrinsic.
8146 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
8147 sdl, NodeTys, Ops);
8148 SDValue patchableNode = SDValue(MN, 0);
8149 DAG.setRoot(patchableNode);
8150 setValue(&I, patchableNode);
8151 return;
8152 }
8153 case Intrinsic::xray_typedevent: {
8154 // Here we want to make sure that the intrinsic behaves as if it has a
8155 // specific calling convention.
8156 const auto &Triple = DAG.getTarget().getTargetTriple();
8157 if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64 &&
8158 Triple.getArch() != Triple::hexagon)
8159 return;
8160
8162
8163 // We want to say that we always want the arguments in registers.
8164 // It's unclear to me how manipulating the selection DAG here forces callers
8165 // to provide arguments in registers instead of on the stack.
8166 SDValue LogTypeId = getValue(I.getArgOperand(0));
8167 SDValue LogEntryVal = getValue(I.getArgOperand(1));
8168 SDValue StrSizeVal = getValue(I.getArgOperand(2));
8169 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8170 SDValue Chain = getRoot();
8171 Ops.push_back(LogTypeId);
8172 Ops.push_back(LogEntryVal);
8173 Ops.push_back(StrSizeVal);
8174 Ops.push_back(Chain);
8175
8176 // We need to enforce the calling convention for the callsite, so that
8177 // argument ordering is enforced correctly, and that register allocation can
8178 // see that some registers may be assumed clobbered and have to preserve
8179 // them across calls to the intrinsic.
8180 MachineSDNode *MN = DAG.getMachineNode(
8181 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
8182 SDValue patchableNode = SDValue(MN, 0);
8183 DAG.setRoot(patchableNode);
8184 setValue(&I, patchableNode);
8185 return;
8186 }
8187 case Intrinsic::experimental_deoptimize:
8189 return;
8190 case Intrinsic::stepvector:
8191 visitStepVector(I);
8192 return;
8193 case Intrinsic::vector_reduce_fadd:
8194 case Intrinsic::vector_reduce_fmul:
8195 case Intrinsic::vector_reduce_add:
8196 case Intrinsic::vector_reduce_mul:
8197 case Intrinsic::vector_reduce_and:
8198 case Intrinsic::vector_reduce_or:
8199 case Intrinsic::vector_reduce_xor:
8200 case Intrinsic::vector_reduce_smax:
8201 case Intrinsic::vector_reduce_smin:
8202 case Intrinsic::vector_reduce_umax:
8203 case Intrinsic::vector_reduce_umin:
8204 case Intrinsic::vector_reduce_fmax:
8205 case Intrinsic::vector_reduce_fmin:
8206 case Intrinsic::vector_reduce_fmaximum:
8207 case Intrinsic::vector_reduce_fminimum:
8208 case Intrinsic::vector_reduce_fmaximumnum:
8209 case Intrinsic::vector_reduce_fminimumnum:
8210 visitVectorReduce(I, Intrinsic);
8211 return;
8212
8213 case Intrinsic::icall_branch_funnel: {
8215 Ops.push_back(getValue(I.getArgOperand(0)));
8216
8217 int64_t Offset;
8219 I.getArgOperand(1), Offset, DAG.getDataLayout()));
8220 if (!Base)
8222 "llvm.icall.branch.funnel operand must be a GlobalValue");
8223 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
8224
8225 struct BranchFunnelTarget {
8226 int64_t Offset;
8228 };
8230
8231 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
8233 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
8234 if (ElemBase != Base)
8235 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
8236 "to the same GlobalValue");
8237
8238 SDValue Val = getValue(I.getArgOperand(Op + 1));
8239 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
8240 if (!GA)
8242 "llvm.icall.branch.funnel operand must be a GlobalValue");
8243 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
8244 GA->getGlobal(), sdl, Val.getValueType(),
8245 GA->getOffset())});
8246 }
8247 llvm::sort(Targets,
8248 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
8249 return T1.Offset < T2.Offset;
8250 });
8251
8252 for (auto &T : Targets) {
8253 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
8254 Ops.push_back(T.Target);
8255 }
8256
8257 Ops.push_back(DAG.getRoot()); // Chain
8258 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
8259 MVT::Other, Ops),
8260 0);
8261 DAG.setRoot(N);
8262 setValue(&I, N);
8263 HasTailCall = true;
8264 return;
8265 }
8266
8267 case Intrinsic::wasm_landingpad_index:
8268 // Information this intrinsic contained has been transferred to
8269 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
8270 // delete it now.
8271 return;
8272
8273 case Intrinsic::aarch64_settag:
8274 case Intrinsic::aarch64_settag_zero: {
8275 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8276 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
8278 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
8279 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
8280 ZeroMemory);
8281 DAG.setRoot(Val);
8282 setValue(&I, Val);
8283 return;
8284 }
8285 case Intrinsic::amdgcn_cs_chain: {
8286 // At this point we don't care if it's amdgpu_cs_chain or
8287 // amdgpu_cs_chain_preserve.
8289
8290 Type *RetTy = I.getType();
8291 assert(RetTy->isVoidTy() && "Should not return");
8292
8293 SDValue Callee = getValue(I.getOperand(0));
8294
8295 // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8296 // We'll also tack the value of the EXEC mask at the end.
8298 Args.reserve(3);
8299
8300 for (unsigned Idx : {2, 3, 1}) {
8301 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8302 I.getOperand(Idx)->getType());
8303 Arg.setAttributes(&I, Idx);
8304 Args.push_back(Arg);
8305 }
8306
8307 assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8308 assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8309 Args[2].IsInReg = true; // EXEC should be inreg
8310
8311 // Forward the flags and any additional arguments.
8312 for (unsigned Idx = 4; Idx < I.arg_size(); ++Idx) {
8313 TargetLowering::ArgListEntry Arg(getValue(I.getOperand(Idx)),
8314 I.getOperand(Idx)->getType());
8315 Arg.setAttributes(&I, Idx);
8316 Args.push_back(Arg);
8317 }
8318
8319 TargetLowering::CallLoweringInfo CLI(DAG);
8320 CLI.setDebugLoc(getCurSDLoc())
8321 .setChain(getRoot())
8322 .setCallee(CC, RetTy, Callee, std::move(Args))
8323 .setNoReturn(true)
8324 .setTailCall(true)
8325 .setConvergent(I.isConvergent());
8326 CLI.CB = &I;
8327 std::pair<SDValue, SDValue> Result =
8328 lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8329 (void)Result;
8330 assert(!Result.first.getNode() && !Result.second.getNode() &&
8331 "Should've lowered as tail call");
8332
8333 HasTailCall = true;
8334 return;
8335 }
8336 case Intrinsic::amdgcn_call_whole_wave: {
8338 bool isTailCall = I.isTailCall();
8339
8340 // The first argument is the callee. Skip it when assembling the call args.
8341 for (unsigned Idx = 1; Idx < I.arg_size(); ++Idx) {
8342 TargetLowering::ArgListEntry Arg(getValue(I.getArgOperand(Idx)),
8343 I.getArgOperand(Idx)->getType());
8344 Arg.setAttributes(&I, Idx);
8345
8346 // If we have an explicit sret argument that is an Instruction, (i.e., it
8347 // might point to function-local memory), we can't meaningfully tail-call.
8348 if (Arg.IsSRet && isa<Instruction>(I.getArgOperand(Idx)))
8349 isTailCall = false;
8350
8351 Args.push_back(Arg);
8352 }
8353
8354 SDValue ConvControlToken;
8355 if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8356 auto *Token = Bundle->Inputs[0].get();
8357 ConvControlToken = getValue(Token);
8358 }
8359
8360 TargetLowering::CallLoweringInfo CLI(DAG);
8361 CLI.setDebugLoc(getCurSDLoc())
8362 .setChain(getRoot())
8363 .setCallee(CallingConv::AMDGPU_Gfx_WholeWave, I.getType(),
8364 getValue(I.getArgOperand(0)), std::move(Args))
8365 .setTailCall(isTailCall && canTailCall(I))
8366 .setIsPreallocated(
8367 I.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8368 .setConvergent(I.isConvergent())
8369 .setConvergenceControlToken(ConvControlToken);
8370 CLI.CB = &I;
8371
8372 std::pair<SDValue, SDValue> Result =
8373 lowerInvokable(CLI, /*EHPadBB=*/nullptr);
8374
8375 if (Result.first.getNode())
8376 setValue(&I, Result.first);
8377 return;
8378 }
8379 case Intrinsic::ptrmask: {
8380 SDValue Ptr = getValue(I.getOperand(0));
8381 SDValue Mask = getValue(I.getOperand(1));
8382
8383 // On arm64_32, pointers are 32 bits when stored in memory, but
8384 // zero-extended to 64 bits when in registers. Thus the mask is 32 bits to
8385 // match the index type, but the pointer is 64 bits, so the mask must be
8386 // zero-extended up to 64 bits to match the pointer.