Debian Codegraph @

clang/lib/AST/ByteCode/InterpBuiltin.cpp

raw
1 //===--- InterpBuiltin.cpp - Interpreter for the constexpr VM ---*- C++ -*-===//
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 #include "../ExprConstShared.h"
9 #include "Boolean.h"
10 #include "EvalEmitter.h"
11 #include "InterpBuiltinBitCast.h"
12 #include "InterpHelpers.h"
13 #include "PrimType.h"
14 #include "Program.h"
15 #include "clang/AST/InferAlloc.h"
16 #include "clang/AST/OSLog.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/Basic/Builtins.h"
19 #include "clang/Basic/TargetBuiltins.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/AllocToken.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/SipHash.h"
25
26 namespace clang {
27 namespace interp {
28
29 [[maybe_unused]] static bool isNoopBuiltin(unsigned ID) {
30 switch (ID) {
31 case Builtin::BIas_const:
32 case Builtin::BIforward:
33 case Builtin::BIforward_like:
34 case Builtin::BImove:
35 case Builtin::BImove_if_noexcept:
36 case Builtin::BIaddressof:
37 case Builtin::BI__addressof:
38 case Builtin::BI__builtin_addressof:
39 case Builtin::BI__builtin_launder:
40 return true;
41 default:
42 return false;
43 }
44 return false;
45 }
46
47 static void discard(InterpStack &Stk, PrimType T) {
48 TYPE_SWITCH(T, { Stk.discard<T>(); });
49 }
50
51 static uint64_t popToUInt64(const InterpState &S, const Expr *E) {
52 INT_TYPE_SWITCH(*S.getContext().classify(E->getType()),
53 return static_cast<uint64_t>(S.Stk.pop<T>()));
54 }
55
56 static APSInt popToAPSInt(InterpStack &Stk, PrimType T) {
57 INT_TYPE_SWITCH(T, return Stk.pop<T>().toAPSInt());
58 }
59
60 static APSInt popToAPSInt(InterpState &S, const Expr *E) {
61 return popToAPSInt(S.Stk, *S.getContext().classify(E->getType()));
62 }
63 static APSInt popToAPSInt(InterpState &S, QualType T) {
64 return popToAPSInt(S.Stk, *S.getContext().classify(T));
65 }
66
67 /// Check for common reasons a pointer can't be read from, which
68 /// are usually not diagnosed in a builtin function.
69 static bool isReadable(const Pointer &P) {
70 if (P.isDummy())
71 return false;
72 if (!P.isBlockPointer())
73 return false;
74 if (!P.isLive())
75 return false;
76 if (P.isOnePastEnd())
77 return false;
78 return true;
79 }
80
81 /// Pushes \p Val on the stack as the type given by \p QT.
82 static void pushInteger(InterpState &S, const APSInt &Val, QualType QT) {
83 assert(QT->isSignedIntegerOrEnumerationType() ||
84 QT->isUnsignedIntegerOrEnumerationType());
85 OptPrimType T = S.getContext().classify(QT);
86 assert(T);
87
88 unsigned BitWidth = S.getASTContext().getTypeSize(QT);
89
90 if (T == PT_IntAPS) {
91 auto Result = S.allocAP<IntegralAP<true>>(BitWidth);
92 Result.copy(Val);
93 S.Stk.push<IntegralAP<true>>(Result);
94 return;
95 }
96
97 if (T == PT_IntAP) {
98 auto Result = S.allocAP<IntegralAP<false>>(BitWidth);
99 Result.copy(Val);
100 S.Stk.push<IntegralAP<false>>(Result);
101 return;
102 }
103
104 if (QT->isSignedIntegerOrEnumerationType()) {
105 int64_t V = Val.getSExtValue();
106 INT_TYPE_SWITCH(*T, { S.Stk.push<T>(T::from(V, BitWidth)); });
107 } else {
108 assert(QT->isUnsignedIntegerOrEnumerationType());
109 uint64_t V = Val.getZExtValue();
110 INT_TYPE_SWITCH(*T, { S.Stk.push<T>(T::from(V, BitWidth)); });
111 }
112 }
113
114 template <typename T>
115 static void pushInteger(InterpState &S, T Val, QualType QT) {
116 if constexpr (std::is_same_v<T, APInt>)
117 pushInteger(S, APSInt(Val, !std::is_signed_v<T>), QT);
118 else if constexpr (std::is_same_v<T, APSInt>)
119 pushInteger(S, Val, QT);
120 else
121 pushInteger(S,
122 APSInt(APInt(sizeof(T) * 8, static_cast<uint64_t>(Val),
123 std::is_signed_v<T>),
124 !std::is_signed_v<T>),
125 QT);
126 }
127
128 static void assignInteger(InterpState &S, const Pointer &Dest, PrimType ValueT,
129 const APSInt &Value) {
130
131 if (ValueT == PT_IntAPS) {
132 Dest.deref<IntegralAP<true>>() =
133 S.allocAP<IntegralAP<true>>(Value.getBitWidth());
134 Dest.deref<IntegralAP<true>>().copy(Value);
135 } else if (ValueT == PT_IntAP) {
136 Dest.deref<IntegralAP<false>>() =
137 S.allocAP<IntegralAP<false>>(Value.getBitWidth());
138 Dest.deref<IntegralAP<false>>().copy(Value);
139 } else {
140 INT_TYPE_SWITCH_NO_BOOL(
141 ValueT, { Dest.deref<T>() = T::from(static_cast<T>(Value)); });
142 }
143 }
144
145 static QualType getElemType(const Pointer &P) {
146 const Descriptor *Desc = P.getFieldDesc();
147 QualType T = Desc->getType();
148 if (Desc->isPrimitive())
149 return T;
150 if (T->isPointerType())
151 return T->castAs<PointerType>()->getPointeeType();
152 if (Desc->isArray())
153 return Desc->getElemQualType();
154 if (const auto *AT = T->getAsArrayTypeUnsafe())
155 return AT->getElementType();
156 return T;
157 }
158
159 static void diagnoseNonConstexprBuiltin(InterpState &S, CodePtr OpPC,
160 unsigned ID) {
161 if (!S.diagnosing())
162 return;
163
164 auto Loc = S.Current->getSource(OpPC);
165 if (S.getLangOpts().CPlusPlus11)
166 S.CCEDiag(Loc, diag::note_constexpr_invalid_function)
167 << /*isConstexpr=*/0 << /*isConstructor=*/0
168 << S.getASTContext().BuiltinInfo.getQuotedName(ID);
169 else
170 S.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
171 }
172
173 static llvm::APSInt convertBoolVectorToInt(const Pointer &Val) {
174 assert(Val.getFieldDesc()->isPrimitiveArray() &&
175 Val.getFieldDesc()->getElemQualType()->isBooleanType() &&
176 "Not a boolean vector");
177 unsigned NumElems = Val.getNumElems();
178
179 // Each element is one bit, so create an integer with NumElts bits.
180 llvm::APSInt Result(NumElems, 0);
181 for (unsigned I = 0; I != NumElems; ++I) {
182 if (Val.elem<bool>(I))
183 Result.setBit(I);
184 }
185
186 return Result;
187 }
188
189 // Strict double -> float conversion used for X86 PD2PS/cvtsd2ss intrinsics.
190 // Reject NaN/Inf/Subnormal inputs and any lossy/inexact conversions.
191 static bool convertDoubleToFloatStrict(APFloat Src, Floating &Dst,
192 InterpState &S, const Expr *DiagExpr) {
193 if (Src.isInfinity()) {
194 if (S.diagnosing())
195 S.CCEDiag(DiagExpr, diag::note_constexpr_float_arithmetic) << 0;
196 return false;
197 }
198 if (Src.isNaN()) {
199 if (S.diagnosing())
200 S.CCEDiag(DiagExpr, diag::note_constexpr_float_arithmetic) << 1;
201 return false;
202 }
203 APFloat Val = Src;
204 bool LosesInfo = false;
205 APFloat::opStatus Status = Val.convert(
206 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
207 if (LosesInfo || Val.isDenormal()) {
208 if (S.diagnosing())
209 S.CCEDiag(DiagExpr, diag::note_constexpr_float_arithmetic_strict);
210 return false;
211 }
212 if (Status != APFloat::opOK) {
213 if (S.diagnosing())
214 S.CCEDiag(DiagExpr, diag::note_invalid_subexpr_in_const_expr);
215 return false;
216 }
217 Dst.copy(Val);
218 return true;
219 }
220
221 static bool interp__builtin_is_constant_evaluated(InterpState &S, CodePtr OpPC,
222 const InterpFrame *Frame,
223 const CallExpr *Call) {
224 unsigned Depth = S.Current->getDepth();
225 auto isStdCall = [](const FunctionDecl *F) -> bool {
226 return F && F->isInStdNamespace() && F->getIdentifier() &&
227 F->getIdentifier()->isStr("is_constant_evaluated");
228 };
229 const InterpFrame *Caller = Frame->Caller;
230 // The current frame is the one for __builtin_is_constant_evaluated.
231 // The one above that, potentially the one for std::is_constant_evaluated().
232 if (S.inConstantContext() && !S.checkingPotentialConstantExpression() &&
233 S.getEvalStatus().Diag &&
234 (Depth == 0 || (Depth == 1 && isStdCall(Frame->getCallee())))) {
235 if (Caller && isStdCall(Frame->getCallee())) {
236 const Expr *E = Caller->getExpr(Caller->getRetPC());
237 S.report(E->getExprLoc(),
238 diag::warn_is_constant_evaluated_always_true_constexpr)
239 << "std::is_constant_evaluated" << E->getSourceRange();
240 } else {
241 S.report(Call->getExprLoc(),
242 diag::warn_is_constant_evaluated_always_true_constexpr)
243 << "__builtin_is_constant_evaluated" << Call->getSourceRange();
244 }
245 }
246
247 S.Stk.push<Boolean>(Boolean::from(S.inConstantContext()));
248 return true;
249 }
250
251 // __builtin_assume(int)
252 static bool interp__builtin_assume(InterpState &S, CodePtr OpPC,
253 const InterpFrame *Frame,
254 const CallExpr *Call) {
255 assert(Call->getNumArgs() == 1);
256 discard(S.Stk, *S.getContext().classify(Call->getArg(0)));
257 return true;
258 }
259
260 static bool interp__builtin_strcmp(InterpState &S, CodePtr OpPC,
261 const InterpFrame *Frame,
262 const CallExpr *Call, unsigned ID) {
263 uint64_t Limit = ~static_cast<uint64_t>(0);
264 if (ID == Builtin::BIstrncmp || ID == Builtin::BI__builtin_strncmp ||
265 ID == Builtin::BIwcsncmp || ID == Builtin::BI__builtin_wcsncmp)
266 Limit = popToUInt64(S, Call->getArg(2));
267
268 const Pointer &B = S.Stk.pop<Pointer>();
269 const Pointer &A = S.Stk.pop<Pointer>();
270 if (ID == Builtin::BIstrcmp || ID == Builtin::BIstrncmp ||
271 ID == Builtin::BIwcscmp || ID == Builtin::BIwcsncmp)
272 diagnoseNonConstexprBuiltin(S, OpPC, ID);
273
274 if (Limit == 0) {
275 pushInteger(S, 0, Call->getType());
276 return true;
277 }
278
279 if (!CheckLive(S, OpPC, A, AK_Read) || !CheckLive(S, OpPC, B, AK_Read))
280 return false;
281
282 if (A.isDummy() || B.isDummy())
283 return false;
284 if (!A.isBlockPointer() || !B.isBlockPointer())
285 return false;
286
287 bool IsWide = ID == Builtin::BIwcscmp || ID == Builtin::BIwcsncmp ||
288 ID == Builtin::BI__builtin_wcscmp ||
289 ID == Builtin::BI__builtin_wcsncmp;
290 assert(A.getFieldDesc()->isPrimitiveArray());
291 assert(B.getFieldDesc()->isPrimitiveArray());
292
293 // Different element types shouldn't happen, but with casts they can.
294 if (!S.getASTContext().hasSameUnqualifiedType(getElemType(A), getElemType(B)))
295 return false;
296
297 PrimType ElemT = *S.getContext().classify(getElemType(A));
298
299 auto returnResult = [&](int V) -> bool {
300 pushInteger(S, V, Call->getType());
301 return true;
302 };
303
304 unsigned IndexA = A.getIndex();
305 unsigned IndexB = B.getIndex();
306 uint64_t Steps = 0;
307 for (;; ++IndexA, ++IndexB, ++Steps) {
308
309 if (Steps >= Limit)
310 break;
311 const Pointer &PA = A.atIndex(IndexA);
312 const Pointer &PB = B.atIndex(IndexB);
313 if (!CheckRange(S, OpPC, PA, AK_Read) ||
314 !CheckRange(S, OpPC, PB, AK_Read)) {
315 return false;
316 }
317
318 if (IsWide) {
319 INT_TYPE_SWITCH(ElemT, {
320 T CA = PA.deref<T>();
321 T CB = PB.deref<T>();
322 if (CA > CB)
323 return returnResult(1);
324 if (CA < CB)
325 return returnResult(-1);
326 if (CA.isZero() || CB.isZero())
327 return returnResult(0);
328 });
329 continue;
330 }
331
332 uint8_t CA = PA.deref<uint8_t>();
333 uint8_t CB = PB.deref<uint8_t>();
334
335 if (CA > CB)
336 return returnResult(1);
337 if (CA < CB)
338 return returnResult(-1);
339 if (CA == 0 || CB == 0)
340 return returnResult(0);
341 }
342
343 return returnResult(0);
344 }
345
346 static bool interp__builtin_strlen(InterpState &S, CodePtr OpPC,
347 const InterpFrame *Frame,
348 const CallExpr *Call, unsigned ID) {
349 const Pointer &StrPtr = S.Stk.pop<Pointer>().expand();
350
351 if (ID == Builtin::BIstrlen || ID == Builtin::BIwcslen)
352 diagnoseNonConstexprBuiltin(S, OpPC, ID);
353
354 if (!CheckArray(S, OpPC, StrPtr))
355 return false;
356
357 if (!CheckLive(S, OpPC, StrPtr, AK_Read))
358 return false;
359
360 if (!CheckDummy(S, OpPC, StrPtr.block(), AK_Read))
361 return false;
362
363 if (!StrPtr.getFieldDesc()->isPrimitiveArray())
364 return false;
365
366 assert(StrPtr.getFieldDesc()->isPrimitiveArray());
367 unsigned ElemSize = StrPtr.getFieldDesc()->getElemSize();
368
369 if (ID == Builtin::BI__builtin_wcslen || ID == Builtin::BIwcslen) {
370 [[maybe_unused]] const ASTContext &AC = S.getASTContext();
371 assert(ElemSize == AC.getTypeSizeInChars(AC.getWCharType()).getQuantity());
372 }
373
374 size_t Len = 0;
375 for (size_t I = StrPtr.getIndex();; ++I, ++Len) {
376 const Pointer &ElemPtr = StrPtr.atIndex(I);
377
378 if (!CheckRange(S, OpPC, ElemPtr, AK_Read))
379 return false;
380
381 uint32_t Val;
382 switch (ElemSize) {
383 case 1:
384 Val = ElemPtr.deref<uint8_t>();
385 break;
386 case 2:
387 Val = ElemPtr.deref<uint16_t>();
388 break;
389 case 4:
390 Val = ElemPtr.deref<uint32_t>();
391 break;
392 default:
393 llvm_unreachable("Unsupported char size");
394 }
395 if (Val == 0)
396 break;
397 }
398
399 pushInteger(S, Len, Call->getType());
400
401 return true;
402 }
403
404 static bool interp__builtin_nan(InterpState &S, CodePtr OpPC,
405 const InterpFrame *Frame, const CallExpr *Call,
406 bool Signaling) {
407 const Pointer &Arg = S.Stk.pop<Pointer>();
408
409 if (!CheckLoad(S, OpPC, Arg))
410 return false;
411
412 assert(Arg.getFieldDesc()->isPrimitiveArray());
413
414 // Convert the given string to an integer using StringRef's API.
415 llvm::APInt Fill;
416 std::string Str;
417 assert(Arg.getNumElems() >= 1);
418 for (unsigned I = 0;; ++I) {
419 const Pointer &Elem = Arg.atIndex(I);
420
421 if (!CheckLoad(S, OpPC, Elem))
422 return false;
423
424 if (Elem.deref<int8_t>() == 0)
425 break;
426
427 Str += Elem.deref<char>();
428 }
429
430 // Treat empty strings as if they were zero.
431 if (Str.empty())
432 Fill = llvm::APInt(32, 0);
433 else if (StringRef(Str).getAsInteger(0, Fill))
434 return false;
435
436 const llvm::fltSemantics &TargetSemantics =
437 S.getASTContext().getFloatTypeSemantics(
438 Call->getDirectCallee()->getReturnType());
439
440 Floating Result = S.allocFloat(TargetSemantics);
441 if (S.getASTContext().getTargetInfo().isNan2008()) {
442 if (Signaling)
443 Result.copy(
444 llvm::APFloat::getSNaN(TargetSemantics, /*Negative=*/false, &Fill));
445 else
446 Result.copy(
447 llvm::APFloat::getQNaN(TargetSemantics, /*Negative=*/false, &Fill));
448 } else {
449 // Prior to IEEE 754-2008, architectures were allowed to choose whether
450 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
451 // a different encoding to what became a standard in 2008, and for pre-
452 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
453 // sNaN. This is now known as "legacy NaN" encoding.
454 if (Signaling)
455 Result.copy(
456 llvm::APFloat::getQNaN(TargetSemantics, /*Negative=*/false, &Fill));
457 else
458 Result.copy(
459 llvm::APFloat::getSNaN(TargetSemantics, /*Negative=*/false, &Fill));
460 }
461
462 S.Stk.push<Floating>(Result);
463 return true;
464 }
465
466 static bool interp__builtin_inf(InterpState &S, CodePtr OpPC,
467 const InterpFrame *Frame,
468 const CallExpr *Call) {
469 const llvm::fltSemantics &TargetSemantics =
470 S.getASTContext().getFloatTypeSemantics(
471 Call->getDirectCallee()->getReturnType());
472
473 Floating Result = S.allocFloat(TargetSemantics);
474 Result.copy(APFloat::getInf(TargetSemantics));
475 S.Stk.push<Floating>(Result);
476 return true;
477 }
478
479 static bool interp__builtin_copysign(InterpState &S, CodePtr OpPC,
480 const InterpFrame *Frame) {
481 const Floating &Arg2 = S.Stk.pop<Floating>();
482 const Floating &Arg1 = S.Stk.pop<Floating>();
483 Floating Result = S.allocFloat(Arg1.getSemantics());
484
485 APFloat Copy = Arg1.getAPFloat();
486 Copy.copySign(Arg2.getAPFloat());
487 Result.copy(Copy);
488 S.Stk.push<Floating>(Result);
489
490 return true;
491 }
492
493 static bool interp__builtin_fmin(InterpState &S, CodePtr OpPC,
494 const InterpFrame *Frame, bool IsNumBuiltin) {
495 const Floating &RHS = S.Stk.pop<Floating>();
496 const Floating &LHS = S.Stk.pop<Floating>();
497 Floating Result = S.allocFloat(LHS.getSemantics());
498
499 if (IsNumBuiltin)
500 Result.copy(llvm::minimumnum(LHS.getAPFloat(), RHS.getAPFloat()));
501 else
502 Result.copy(minnum(LHS.getAPFloat(), RHS.getAPFloat()));
503 S.Stk.push<Floating>(Result);
504 return true;
505 }
506
507 static bool interp__builtin_fmax(InterpState &S, CodePtr OpPC,
508 const InterpFrame *Frame, bool IsNumBuiltin) {
509 const Floating &RHS = S.Stk.pop<Floating>();
510 const Floating &LHS = S.Stk.pop<Floating>();
511 Floating Result = S.allocFloat(LHS.getSemantics());
512
513 if (IsNumBuiltin)
514 Result.copy(llvm::maximumnum(LHS.getAPFloat(), RHS.getAPFloat()));
515 else
516 Result.copy(maxnum(LHS.getAPFloat(), RHS.getAPFloat()));
517 S.Stk.push<Floating>(Result);
518 return true;
519 }
520
521 /// Defined as __builtin_isnan(...), to accommodate the fact that it can
522 /// take a float, double, long double, etc.
523 /// But for us, that's all a Floating anyway.
524 static bool interp__builtin_isnan(InterpState &S, CodePtr OpPC,
525 const InterpFrame *Frame,
526 const CallExpr *Call) {
527 const Floating &Arg = S.Stk.pop<Floating>();
528
529 pushInteger(S, Arg.isNan(), Call->getType());
530 return true;
531 }
532
533 static bool interp__builtin_issignaling(InterpState &S, CodePtr OpPC,
534 const InterpFrame *Frame,
535 const CallExpr *Call) {
536 const Floating &Arg = S.Stk.pop<Floating>();
537
538 pushInteger(S, Arg.isSignaling(), Call->getType());
539 return true;
540 }
541
542 static bool interp__builtin_isinf(InterpState &S, CodePtr OpPC,
543 const InterpFrame *Frame, bool CheckSign,
544 const CallExpr *Call) {
545 const Floating &Arg = S.Stk.pop<Floating>();
546 APFloat F = Arg.getAPFloat();
547 bool IsInf = F.isInfinity();
548
549 if (CheckSign)
550 pushInteger(S, IsInf ? (F.isNegative() ? -1 : 1) : 0, Call->getType());
551 else
552 pushInteger(S, IsInf, Call->getType());
553 return true;
554 }
555
556 static bool interp__builtin_isfinite(InterpState &S, CodePtr OpPC,
557 const InterpFrame *Frame,
558 const CallExpr *Call) {
559 const Floating &Arg = S.Stk.pop<Floating>();
560
561 pushInteger(S, Arg.isFinite(), Call->getType());
562 return true;
563 }
564
565 static bool interp__builtin_isnormal(InterpState &S, CodePtr OpPC,
566 const InterpFrame *Frame,
567 const CallExpr *Call) {
568 const Floating &Arg = S.Stk.pop<Floating>();
569
570 pushInteger(S, Arg.isNormal(), Call->getType());
571 return true;
572 }
573
574 static bool interp__builtin_issubnormal(InterpState &S, CodePtr OpPC,
575 const InterpFrame *Frame,
576 const CallExpr *Call) {
577 const Floating &Arg = S.Stk.pop<Floating>();
578
579 pushInteger(S, Arg.isDenormal(), Call->getType());
580 return true;
581 }
582
583 static bool interp__builtin_iszero(InterpState &S, CodePtr OpPC,
584 const InterpFrame *Frame,
585 const CallExpr *Call) {
586 const Floating &Arg = S.Stk.pop<Floating>();
587
588 pushInteger(S, Arg.isZero(), Call->getType());
589 return true;
590 }
591
592 static bool interp__builtin_signbit(InterpState &S, CodePtr OpPC,
593 const InterpFrame *Frame,
594 const CallExpr *Call) {
595 const Floating &Arg = S.Stk.pop<Floating>();
596
597 pushInteger(S, Arg.isNegative(), Call->getType());
598 return true;
599 }
600
601 static bool interp_floating_comparison(InterpState &S, CodePtr OpPC,
602 const CallExpr *Call, unsigned ID) {
603 const Floating &RHS = S.Stk.pop<Floating>();
604 const Floating &LHS = S.Stk.pop<Floating>();
605
606 pushInteger(
607 S,
608 [&] {
609 switch (ID) {
610 case Builtin::BI__builtin_isgreater:
611 return LHS > RHS;
612 case Builtin::BI__builtin_isgreaterequal:
613 return LHS >= RHS;
614 case Builtin::BI__builtin_isless:
615 return LHS < RHS;
616 case Builtin::BI__builtin_islessequal:
617 return LHS <= RHS;
618 case Builtin::BI__builtin_islessgreater: {
619 ComparisonCategoryResult Cmp = LHS.compare(RHS);
620 return Cmp == ComparisonCategoryResult::Less ||
621 Cmp == ComparisonCategoryResult::Greater;
622 }
623 case Builtin::BI__builtin_isunordered:
624 return LHS.compare(RHS) == ComparisonCategoryResult::Unordered;
625 default:
626 llvm_unreachable("Unexpected builtin ID: Should be a floating point "
627 "comparison function");
628 }
629 }(),
630 Call->getType());
631 return true;
632 }
633
634 /// First parameter to __builtin_isfpclass is the floating value, the
635 /// second one is an integral value.
636 static bool interp__builtin_isfpclass(InterpState &S, CodePtr OpPC,
637 const InterpFrame *Frame,
638 const CallExpr *Call) {
639 APSInt FPClassArg = popToAPSInt(S, Call->getArg(1));
640 const Floating &F = S.Stk.pop<Floating>();
641
642 int32_t Result = static_cast<int32_t>(
643 (F.classify() & std::move(FPClassArg)).getZExtValue());
644 pushInteger(S, Result, Call->getType());
645
646 return true;
647 }
648
649 /// Five int values followed by one floating value.
650 /// __builtin_fpclassify(int, int, int, int, int, float)
651 static bool interp__builtin_fpclassify(InterpState &S, CodePtr OpPC,
652 const InterpFrame *Frame,
653 const CallExpr *Call) {
654 const Floating &Val = S.Stk.pop<Floating>();
655
656 PrimType IntT = *S.getContext().classify(Call->getArg(0));
657 APSInt Values[5];
658 for (unsigned I = 0; I != 5; ++I)
659 Values[4 - I] = popToAPSInt(S.Stk, IntT);
660
661 unsigned Index;
662 switch (Val.getCategory()) {
663 case APFloat::fcNaN:
664 Index = 0;
665 break;
666 case APFloat::fcInfinity:
667 Index = 1;
668 break;
669 case APFloat::fcNormal:
670 Index = Val.isDenormal() ? 3 : 2;
671 break;
672 case APFloat::fcZero:
673 Index = 4;
674 break;
675 }
676
677 // The last argument is first on the stack.
678 assert(Index <= 4);
679
680 pushInteger(S, Values[Index], Call->getType());
681 return true;
682 }
683
684 static inline Floating abs(InterpState &S, const Floating &In) {
685 if (!In.isNegative())
686 return In;
687
688 Floating Output = S.allocFloat(In.getSemantics());
689 APFloat New = In.getAPFloat();
690 New.changeSign();
691 Output.copy(New);
692 return Output;
693 }
694
695 // The C standard says "fabs raises no floating-point exceptions,
696 // even if x is a signaling NaN. The returned value is independent of
697 // the current rounding direction mode." Therefore constant folding can
698 // proceed without regard to the floating point settings.
699 // Reference, WG14 N2478 F.10.4.3
700 static bool interp__builtin_fabs(InterpState &S, CodePtr OpPC,
701 const InterpFrame *Frame) {
702 const Floating &Val = S.Stk.pop<Floating>();
703 S.Stk.push<Floating>(abs(S, Val));
704 return true;
705 }
706
707 static bool interp__builtin_abs(InterpState &S, CodePtr OpPC,
708 const InterpFrame *Frame,
709 const CallExpr *Call) {
710 APSInt Val = popToAPSInt(S, Call->getArg(0));
711 if (Val ==
712 APSInt(APInt::getSignedMinValue(Val.getBitWidth()), /*IsUnsigned=*/false))
713 return false;
714 if (Val.isNegative())
715 Val.negate();
716 pushInteger(S, Val, Call->getType());
717 return true;
718 }
719
720 static bool interp__builtin_popcount(InterpState &S, CodePtr OpPC,
721 const InterpFrame *Frame,
722 const CallExpr *Call) {
723 APSInt Val;
724 if (Call->getArg(0)->getType()->isExtVectorBoolType()) {
725 const Pointer &Arg = S.Stk.pop<Pointer>();
726 Val = convertBoolVectorToInt(Arg);
727 } else {
728 Val = popToAPSInt(S, Call->getArg(0));
729 }
730 pushInteger(S, Val.popcount(), Call->getType());
731 return true;
732 }
733
734 static bool interp__builtin_classify_type(InterpState &S, CodePtr OpPC,
735 const InterpFrame *Frame,
736 const CallExpr *Call) {
737 // This is an unevaluated call, so there are no arguments on the stack.
738 assert(Call->getNumArgs() == 1);
739 const Expr *Arg = Call->getArg(0);
740
741 GCCTypeClass ResultClass =
742 EvaluateBuiltinClassifyType(Arg->getType(), S.getLangOpts());
743 int32_t ReturnVal = static_cast<int32_t>(ResultClass);
744 pushInteger(S, ReturnVal, Call->getType());
745 return true;
746 }
747
748 // __builtin_expect(long, long)
749 // __builtin_expect_with_probability(long, long, double)
750 static bool interp__builtin_expect(InterpState &S, CodePtr OpPC,
751 const InterpFrame *Frame,
752 const CallExpr *Call) {
753 // The return value is simply the value of the first parameter.
754 // We ignore the probability.
755 unsigned NumArgs = Call->getNumArgs();
756 assert(NumArgs == 2 || NumArgs == 3);
757
758 PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
759 if (NumArgs == 3)
760 S.Stk.discard<Floating>();
761 discard(S.Stk, ArgT);
762
763 APSInt Val = popToAPSInt(S.Stk, ArgT);
764 pushInteger(S, Val, Call->getType());
765 return true;
766 }
767
768 static bool interp__builtin_addressof(InterpState &S, CodePtr OpPC,
769 const InterpFrame *Frame,
770 const CallExpr *Call) {
771 #ifndef NDEBUG
772 assert(Call->getArg(0)->isLValue());
773 PrimType PtrT = S.getContext().classify(Call->getArg(0)).value_or(PT_Ptr);
774 assert(PtrT == PT_Ptr &&
775 "Unsupported pointer type passed to __builtin_addressof()");
776 #endif
777 return true;
778 }
779
780 static bool interp__builtin_move(InterpState &S, CodePtr OpPC,
781 const InterpFrame *Frame,
782 const CallExpr *Call) {
783 return Call->getDirectCallee()->isConstexpr();
784 }
785
786 static bool interp__builtin_eh_return_data_regno(InterpState &S, CodePtr OpPC,
787 const InterpFrame *Frame,
788 const CallExpr *Call) {
789 APSInt Arg = popToAPSInt(S, Call->getArg(0));
790
791 int Result = S.getASTContext().getTargetInfo().getEHDataRegisterNumber(
792 Arg.getZExtValue());
793 pushInteger(S, Result, Call->getType());
794 return true;
795 }
796
797 // Two integral values followed by a pointer (lhs, rhs, resultOut)
798 static bool interp__builtin_overflowop(InterpState &S, CodePtr OpPC,
799 const CallExpr *Call,
800 unsigned BuiltinOp) {
801 const Pointer &ResultPtr = S.Stk.pop<Pointer>();
802 if (ResultPtr.isDummy() || !ResultPtr.isBlockPointer())
803 return false;
804
805 PrimType RHST = *S.getContext().classify(Call->getArg(1)->getType());
806 PrimType LHST = *S.getContext().classify(Call->getArg(0)->getType());
807 APSInt RHS = popToAPSInt(S.Stk, RHST);
808 APSInt LHS = popToAPSInt(S.Stk, LHST);
809 QualType ResultType = Call->getArg(2)->getType()->getPointeeType();
810 PrimType ResultT = *S.getContext().classify(ResultType);
811 bool Overflow;
812
813 APSInt Result;
814 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
815 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
816 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
817 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
818 ResultType->isSignedIntegerOrEnumerationType();
819 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
820 ResultType->isSignedIntegerOrEnumerationType();
821 uint64_t LHSSize = LHS.getBitWidth();
822 uint64_t RHSSize = RHS.getBitWidth();
823 uint64_t ResultSize = S.getASTContext().getTypeSize(ResultType);
824 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
825
826 // Add an additional bit if the signedness isn't uniformly agreed to. We
827 // could do this ONLY if there is a signed and an unsigned that both have
828 // MaxBits, but the code to check that is pretty nasty. The issue will be
829 // caught in the shrink-to-result later anyway.
830 if (IsSigned && !AllSigned)
831 ++MaxBits;
832
833 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
834 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
835 Result = APSInt(MaxBits, !IsSigned);
836 }
837
838 // Find largest int.
839 switch (BuiltinOp) {
840 default:
841 llvm_unreachable("Invalid value for BuiltinOp");
842 case Builtin::BI__builtin_add_overflow:
843 case Builtin::BI__builtin_sadd_overflow:
844 case Builtin::BI__builtin_saddl_overflow:
845 case Builtin::BI__builtin_saddll_overflow:
846 case Builtin::BI__builtin_uadd_overflow:
847 case Builtin::BI__builtin_uaddl_overflow:
848 case Builtin::BI__builtin_uaddll_overflow:
849 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, Overflow)
850 : LHS.uadd_ov(RHS, Overflow);
851 break;
852 case Builtin::BI__builtin_sub_overflow:
853 case Builtin::BI__builtin_ssub_overflow:
854 case Builtin::BI__builtin_ssubl_overflow:
855 case Builtin::BI__builtin_ssubll_overflow:
856 case Builtin::BI__builtin_usub_overflow:
857 case Builtin::BI__builtin_usubl_overflow:
858 case Builtin::BI__builtin_usubll_overflow:
859 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, Overflow)
860 : LHS.usub_ov(RHS, Overflow);
861 break;
862 case Builtin::BI__builtin_mul_overflow:
863 case Builtin::BI__builtin_smul_overflow:
864 case Builtin::BI__builtin_smull_overflow:
865 case Builtin::BI__builtin_smulll_overflow:
866 case Builtin::BI__builtin_umul_overflow:
867 case Builtin::BI__builtin_umull_overflow:
868 case Builtin::BI__builtin_umulll_overflow:
869 Result = LHS.isSigned() ? LHS.smul_ov(RHS, Overflow)
870 : LHS.umul_ov(RHS, Overflow);
871 break;
872 }
873
874 // In the case where multiple sizes are allowed, truncate and see if
875 // the values are the same.
876 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
877 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
878 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
879 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
880 // since it will give us the behavior of a TruncOrSelf in the case where
881 // its parameter <= its size. We previously set Result to be at least the
882 // type-size of the result, so getTypeSize(ResultType) <= Resu
883 APSInt Temp = Result.extOrTrunc(S.getASTContext().getTypeSize(ResultType));
884 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
885
886 if (!APSInt::isSameValue(Temp, Result))
887 Overflow = true;
888 Result = std::move(Temp);
889 }
890
891 // Write Result to ResultPtr and put Overflow on the stack.
892 assignInteger(S, ResultPtr, ResultT, Result);
893 if (ResultPtr.canBeInitialized())
894 ResultPtr.initialize();
895
896 assert(Call->getDirectCallee()->getReturnType()->isBooleanType());
897 S.Stk.push<Boolean>(Overflow);
898 return true;
899 }
900
901 /// Three integral values followed by a pointer (lhs, rhs, carry, carryOut).
902 static bool interp__builtin_carryop(InterpState &S, CodePtr OpPC,
903 const InterpFrame *Frame,
904 const CallExpr *Call, unsigned BuiltinOp) {
905 const Pointer &CarryOutPtr = S.Stk.pop<Pointer>();
906 PrimType LHST = *S.getContext().classify(Call->getArg(0)->getType());
907 PrimType RHST = *S.getContext().classify(Call->getArg(1)->getType());
908 APSInt CarryIn = popToAPSInt(S.Stk, LHST);
909 APSInt RHS = popToAPSInt(S.Stk, RHST);
910 APSInt LHS = popToAPSInt(S.Stk, LHST);
911
912 if (CarryOutPtr.isDummy() || !CarryOutPtr.isBlockPointer())
913 return false;
914
915 APSInt CarryOut;
916
917 APSInt Result;
918 // Copy the number of bits and sign.
919 Result = LHS;
920 CarryOut = LHS;
921
922 bool FirstOverflowed = false;
923 bool SecondOverflowed = false;
924 switch (BuiltinOp) {
925 default:
926 llvm_unreachable("Invalid value for BuiltinOp");
927 case Builtin::BI__builtin_addcb:
928 case Builtin::BI__builtin_addcs:
929 case Builtin::BI__builtin_addc:
930 case Builtin::BI__builtin_addcl:
931 case Builtin::BI__builtin_addcll:
932 Result =
933 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
934 break;
935 case Builtin::BI__builtin_subcb:
936 case Builtin::BI__builtin_subcs:
937 case Builtin::BI__builtin_subc:
938 case Builtin::BI__builtin_subcl:
939 case Builtin::BI__builtin_subcll:
940 Result =
941 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
942 break;
943 }
944 // It is possible for both overflows to happen but CGBuiltin uses an OR so
945 // this is consistent.
946 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
947
948 QualType CarryOutType = Call->getArg(3)->getType()->getPointeeType();
949 PrimType CarryOutT = *S.getContext().classify(CarryOutType);
950 assignInteger(S, CarryOutPtr, CarryOutT, CarryOut);
951 CarryOutPtr.initialize();
952
953 assert(Call->getType() == Call->getArg(0)->getType());
954 pushInteger(S, Result, Call->getType());
955 return true;
956 }
957
958 static bool interp__builtin_clz(InterpState &S, CodePtr OpPC,
959 const InterpFrame *Frame, const CallExpr *Call,
960 unsigned BuiltinOp) {
961
962 std::optional<APSInt> Fallback;
963 if (BuiltinOp == Builtin::BI__builtin_clzg && Call->getNumArgs() == 2)
964 Fallback = popToAPSInt(S, Call->getArg(1));
965
966 APSInt Val;
967 if (Call->getArg(0)->getType()->isExtVectorBoolType()) {
968 const Pointer &Arg = S.Stk.pop<Pointer>();
969 Val = convertBoolVectorToInt(Arg);
970 } else {
971 Val = popToAPSInt(S, Call->getArg(0));
972 }
973
974 // When the argument is 0, the result of GCC builtins is undefined, whereas
975 // for Microsoft intrinsics, the result is the bit-width of the argument.
976 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
977 BuiltinOp != Builtin::BI__lzcnt &&
978 BuiltinOp != Builtin::BI__lzcnt64;
979
980 if (Val == 0) {
981 if (Fallback) {
982 pushInteger(S, *Fallback, Call->getType());
983 return true;
984 }
985
986 if (ZeroIsUndefined)
987 return false;
988 }
989
990 pushInteger(S, Val.countl_zero(), Call->getType());
991 return true;
992 }
993
994 static bool interp__builtin_ctz(InterpState &S, CodePtr OpPC,
995 const InterpFrame *Frame, const CallExpr *Call,
996 unsigned BuiltinID) {
997 std::optional<APSInt> Fallback;
998 if (BuiltinID == Builtin::BI__builtin_ctzg && Call->getNumArgs() == 2)
999 Fallback = popToAPSInt(S, Call->getArg(1));
1000
1001 APSInt Val;
1002 if (Call->getArg(0)->getType()->isExtVectorBoolType()) {
1003 const Pointer &Arg = S.Stk.pop<Pointer>();
1004 Val = convertBoolVectorToInt(Arg);
1005 } else {
1006 Val = popToAPSInt(S, Call->getArg(0));
1007 }
1008
1009 if (Val == 0) {
1010 if (Fallback) {
1011 pushInteger(S, *Fallback, Call->getType());
1012 return true;
1013 }
1014 return false;
1015 }
1016
1017 pushInteger(S, Val.countr_zero(), Call->getType());
1018 return true;
1019 }
1020
1021 static bool interp__builtin_bswap(InterpState &S, CodePtr OpPC,
1022 const InterpFrame *Frame,
1023 const CallExpr *Call) {
1024 const APSInt &Val = popToAPSInt(S, Call->getArg(0));
1025 if (Val.getBitWidth() == 8)
1026 pushInteger(S, Val, Call->getType());
1027 else
1028 pushInteger(S, Val.byteSwap(), Call->getType());
1029 return true;
1030 }
1031
1032 /// bool __atomic_always_lock_free(size_t, void const volatile*)
1033 /// bool __atomic_is_lock_free(size_t, void const volatile*)
1034 static bool interp__builtin_atomic_lock_free(InterpState &S, CodePtr OpPC,
1035 const InterpFrame *Frame,
1036 const CallExpr *Call,
1037 unsigned BuiltinOp) {
1038 auto returnBool = [&S](bool Value) -> bool {
1039 S.Stk.push<Boolean>(Value);
1040 return true;
1041 };
1042
1043 const Pointer &Ptr = S.Stk.pop<Pointer>();
1044 uint64_t SizeVal = popToUInt64(S, Call->getArg(0));
1045
1046 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1047 // of two less than or equal to the maximum inline atomic width, we know it
1048 // is lock-free. If the size isn't a power of two, or greater than the
1049 // maximum alignment where we promote atomics, we know it is not lock-free
1050 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1051 // the answer can only be determined at runtime; for example, 16-byte
1052 // atomics have lock-free implementations on some, but not all,
1053 // x86-64 processors.
1054
1055 // Check power-of-two.
1056 CharUnits Size = CharUnits::fromQuantity(SizeVal);
1057 if (Size.isPowerOfTwo()) {
1058 // Check against inlining width.
1059 unsigned InlineWidthBits =
1060 S.getASTContext().getTargetInfo().getMaxAtomicInlineWidth();
1061 if (Size <= S.getASTContext().toCharUnitsFromBits(InlineWidthBits)) {
1062
1063 // OK, we will inline appropriately-aligned operations of this size,
1064 // and _Atomic(T) is appropriately-aligned.
1065 if (Size == CharUnits::One())
1066 return returnBool(true);
1067
1068 // Same for null pointers.
1069 assert(BuiltinOp != Builtin::BI__c11_atomic_is_lock_free);
1070 if (Ptr.isZero())
1071 return returnBool(true);
1072
1073 if (Ptr.isIntegralPointer()) {
1074 uint64_t IntVal = Ptr.getIntegerRepresentation();
1075 if (APSInt(APInt(64, IntVal, false), true).isAligned(Size.getAsAlign()))
1076 return returnBool(true);
1077 }
1078
1079 const Expr *PtrArg = Call->getArg(1);
1080 // Otherwise, check if the type's alignment against Size.
1081 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
1082 // Drop the potential implicit-cast to 'const volatile void*', getting
1083 // the underlying type.
1084 if (ICE->getCastKind() == CK_BitCast)
1085 PtrArg = ICE->getSubExpr();
1086 }
1087
1088 if (const auto *PtrTy = PtrArg->getType()->getAs<PointerType>()) {
1089 QualType PointeeType = PtrTy->getPointeeType();
1090 if (!PointeeType->isIncompleteType() &&
1091 S.getASTContext().getTypeAlignInChars(PointeeType) >= Size) {
1092 // OK, we will inline operations on this object.
1093 return returnBool(true);
1094 }
1095 }
1096 }
1097 }
1098
1099 if (BuiltinOp == Builtin::BI__atomic_always_lock_free)
1100 return returnBool(false);
1101
1102 return false;
1103 }
1104
1105 /// bool __c11_atomic_is_lock_free(size_t)
1106 static bool interp__builtin_c11_atomic_is_lock_free(InterpState &S,
1107 CodePtr OpPC,
1108 const InterpFrame *Frame,
1109 const CallExpr *Call) {
1110 uint64_t SizeVal = popToUInt64(S, Call->getArg(0));
1111
1112 CharUnits Size = CharUnits::fromQuantity(SizeVal);
1113 if (Size.isPowerOfTwo()) {
1114 // Check against inlining width.
1115 unsigned InlineWidthBits =
1116 S.getASTContext().getTargetInfo().getMaxAtomicInlineWidth();
1117 if (Size <= S.getASTContext().toCharUnitsFromBits(InlineWidthBits)) {
1118 S.Stk.push<Boolean>(true);
1119 return true;
1120 }
1121 }
1122
1123 return false; // returnBool(false);
1124 }
1125
1126 /// __builtin_complex(Float A, float B);
1127 static bool interp__builtin_complex(InterpState &S, CodePtr OpPC,
1128 const InterpFrame *Frame,
1129 const CallExpr *Call) {
1130 const Floating &Arg2 = S.Stk.pop<Floating>();
1131 const Floating &Arg1 = S.Stk.pop<Floating>();
1132 Pointer &Result = S.Stk.peek<Pointer>();
1133
1134 Result.elem<Floating>(0) = Arg1;
1135 Result.elem<Floating>(1) = Arg2;
1136 Result.initializeAllElements();
1137
1138 return true;
1139 }
1140
1141 /// __builtin_is_aligned()
1142 /// __builtin_align_up()
1143 /// __builtin_align_down()
1144 /// The first parameter is either an integer or a pointer.
1145 /// The second parameter is the requested alignment as an integer.
1146 static bool interp__builtin_is_aligned_up_down(InterpState &S, CodePtr OpPC,
1147 const InterpFrame *Frame,
1148 const CallExpr *Call,
1149 unsigned BuiltinOp) {
1150 const APSInt &Alignment = popToAPSInt(S, Call->getArg(1));
1151
1152 if (Alignment < 0 || !Alignment.isPowerOf2()) {
1153 S.FFDiag(Call, diag::note_constexpr_invalid_alignment) << Alignment;
1154 return false;
1155 }
1156 unsigned SrcWidth = S.getASTContext().getIntWidth(Call->getArg(0)->getType());
1157 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
1158 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
1159 S.FFDiag(Call, diag::note_constexpr_alignment_too_big)
1160 << MaxValue << Call->getArg(0)->getType() << Alignment;
1161 return false;
1162 }
1163
1164 // The first parameter is either an integer or a pointer.
1165 PrimType FirstArgT = *S.Ctx.classify(Call->getArg(0));
1166
1167 if (isIntegralType(FirstArgT)) {
1168 const APSInt &Src = popToAPSInt(S.Stk, FirstArgT);
1169 APInt AlignMinusOne = Alignment.extOrTrunc(Src.getBitWidth()) - 1;
1170 if (BuiltinOp == Builtin::BI__builtin_align_up) {
1171 APSInt AlignedVal =
1172 APSInt((Src + AlignMinusOne) & ~AlignMinusOne, Src.isUnsigned());
1173 pushInteger(S, AlignedVal, Call->getType());
1174 } else if (BuiltinOp == Builtin::BI__builtin_align_down) {
1175 APSInt AlignedVal = APSInt(Src & ~AlignMinusOne, Src.isUnsigned());
1176 pushInteger(S, AlignedVal, Call->getType());
1177 } else {
1178 assert(*S.Ctx.classify(Call->getType()) == PT_Bool);
1179 S.Stk.push<Boolean>((Src & AlignMinusOne) == 0);
1180 }
1181 return true;
1182 }
1183 assert(FirstArgT == PT_Ptr);
1184 const Pointer &Ptr = S.Stk.pop<Pointer>();
1185 if (!Ptr.isBlockPointer())
1186 return false;
1187
1188 unsigned PtrOffset = Ptr.getIndex();
1189 CharUnits BaseAlignment =
1190 S.getASTContext().getDeclAlign(Ptr.getDeclDesc()->asValueDecl());
1191 CharUnits PtrAlign =
1192 BaseAlignment.alignmentAtOffset(CharUnits::fromQuantity(PtrOffset));
1193
1194 if (BuiltinOp == Builtin::BI__builtin_is_aligned) {
1195 if (PtrAlign.getQuantity() >= Alignment) {
1196 S.Stk.push<Boolean>(true);
1197 return true;
1198 }
1199 // If the alignment is not known to be sufficient, some cases could still
1200 // be aligned at run time. However, if the requested alignment is less or
1201 // equal to the base alignment and the offset is not aligned, we know that
1202 // the run-time value can never be aligned.
1203 if (BaseAlignment.getQuantity() >= Alignment &&
1204 PtrAlign.getQuantity() < Alignment) {
1205 S.Stk.push<Boolean>(false);
1206 return true;
1207 }
1208
1209 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_compute)
1210 << Alignment;
1211 return false;
1212 }
1213
1214 assert(BuiltinOp == Builtin::BI__builtin_align_down ||
1215 BuiltinOp == Builtin::BI__builtin_align_up);
1216
1217 // For align_up/align_down, we can return the same value if the alignment
1218 // is known to be greater or equal to the requested value.
1219 if (PtrAlign.getQuantity() >= Alignment) {
1220 S.Stk.push<Pointer>(Ptr);
1221 return true;
1222 }
1223
1224 // The alignment could be greater than the minimum at run-time, so we cannot
1225 // infer much about the resulting pointer value. One case is possible:
1226 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
1227 // can infer the correct index if the requested alignment is smaller than
1228 // the base alignment so we can perform the computation on the offset.
1229 if (BaseAlignment.getQuantity() >= Alignment) {
1230 assert(Alignment.getBitWidth() <= 64 &&
1231 "Cannot handle > 64-bit address-space");
1232 uint64_t Alignment64 = Alignment.getZExtValue();
1233 CharUnits NewOffset =
1234 CharUnits::fromQuantity(BuiltinOp == Builtin::BI__builtin_align_down
1235 ? llvm::alignDown(PtrOffset, Alignment64)
1236 : llvm::alignTo(PtrOffset, Alignment64));
1237
1238 S.Stk.push<Pointer>(Ptr.atIndex(NewOffset.getQuantity()));
1239 return true;
1240 }
1241
1242 // Otherwise, we cannot constant-evaluate the result.
1243 S.FFDiag(Call->getArg(0), diag::note_constexpr_alignment_adjust) << Alignment;
1244 return false;
1245 }
1246
1247 /// __builtin_assume_aligned(Ptr, Alignment[, ExtraOffset])
1248 static bool interp__builtin_assume_aligned(InterpState &S, CodePtr OpPC,
1249 const InterpFrame *Frame,
1250 const CallExpr *Call) {
1251 assert(Call->getNumArgs() == 2 || Call->getNumArgs() == 3);
1252
1253 std::optional<APSInt> ExtraOffset;
1254 if (Call->getNumArgs() == 3)
1255 ExtraOffset = popToAPSInt(S.Stk, *S.Ctx.classify(Call->getArg(2)));
1256
1257 APSInt Alignment = popToAPSInt(S.Stk, *S.Ctx.classify(Call->getArg(1)));
1258 const Pointer &Ptr = S.Stk.pop<Pointer>();
1259
1260 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
1261
1262 // If there is a base object, then it must have the correct alignment.
1263 if (Ptr.isBlockPointer()) {
1264 CharUnits BaseAlignment;
1265 if (const auto *VD = Ptr.getDeclDesc()->asValueDecl())
1266 BaseAlignment = S.getASTContext().getDeclAlign(VD);
1267 else if (const auto *E = Ptr.getDeclDesc()->asExpr())
1268 BaseAlignment = GetAlignOfExpr(S.getASTContext(), E, UETT_AlignOf);
1269
1270 if (BaseAlignment < Align) {
1271 S.CCEDiag(Call->getArg(0),
1272 diag::note_constexpr_baa_insufficient_alignment)
1273 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
1274 return false;
1275 }
1276 }
1277
1278 APValue AV = Ptr.toAPValue(S.getASTContext());
1279 CharUnits AVOffset = AV.getLValueOffset();
1280 if (ExtraOffset)
1281 AVOffset -= CharUnits::fromQuantity(ExtraOffset->getZExtValue());
1282 if (AVOffset.alignTo(Align) != AVOffset) {
1283 if (Ptr.isBlockPointer())
1284 S.CCEDiag(Call->getArg(0),
1285 diag::note_constexpr_baa_insufficient_alignment)
1286 << 1 << AVOffset.getQuantity() << Align.getQuantity();
1287 else
1288 S.CCEDiag(Call->getArg(0),
1289 diag::note_constexpr_baa_value_insufficient_alignment)
1290 << AVOffset.getQuantity() << Align.getQuantity();
1291 return false;
1292 }
1293
1294 S.Stk.push<Pointer>(Ptr);
1295 return true;
1296 }
1297
1298 /// (CarryIn, LHS, RHS, Result)
1299 static bool interp__builtin_ia32_addcarry_subborrow(InterpState &S,
1300 CodePtr OpPC,
1301 const InterpFrame *Frame,
1302 const CallExpr *Call,
1303 unsigned BuiltinOp) {
1304 if (Call->getNumArgs() != 4 || !Call->getArg(0)->getType()->isIntegerType() ||
1305 !Call->getArg(1)->getType()->isIntegerType() ||
1306 !Call->getArg(2)->getType()->isIntegerType())
1307 return false;
1308
1309 const Pointer &CarryOutPtr = S.Stk.pop<Pointer>();
1310
1311 APSInt RHS = popToAPSInt(S, Call->getArg(2));
1312 APSInt LHS = popToAPSInt(S, Call->getArg(1));
1313 APSInt CarryIn = popToAPSInt(S, Call->getArg(0));
1314
1315 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
1316 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
1317
1318 unsigned BitWidth = LHS.getBitWidth();
1319 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
1320 APInt ExResult =
1321 IsAdd ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
1322 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
1323
1324 APInt Result = ExResult.extractBits(BitWidth, 0);
1325 APSInt CarryOut =
1326 APSInt(ExResult.extractBits(1, BitWidth), /*IsUnsigned=*/true);
1327
1328 QualType CarryOutType = Call->getArg(3)->getType()->getPointeeType();
1329 PrimType CarryOutT = *S.getContext().classify(CarryOutType);
1330 assignInteger(S, CarryOutPtr, CarryOutT, APSInt(std::move(Result), true));
1331
1332 pushInteger(S, CarryOut, Call->getType());
1333
1334 return true;
1335 }
1336
1337 static bool interp__builtin_os_log_format_buffer_size(InterpState &S,
1338 CodePtr OpPC,
1339 const InterpFrame *Frame,
1340 const CallExpr *Call) {
1341 analyze_os_log::OSLogBufferLayout Layout;
1342 analyze_os_log::computeOSLogBufferLayout(S.getASTContext(), Call, Layout);
1343 pushInteger(S, Layout.size().getQuantity(), Call->getType());
1344 return true;
1345 }
1346
1347 static bool
1348 interp__builtin_ptrauth_string_discriminator(InterpState &S, CodePtr OpPC,
1349 const InterpFrame *Frame,
1350 const CallExpr *Call) {
1351 const auto &Ptr = S.Stk.pop<Pointer>();
1352 assert(Ptr.getFieldDesc()->isPrimitiveArray());
1353
1354 // This should be created for a StringLiteral, so should alway shold at least
1355 // one array element.
1356 assert(Ptr.getFieldDesc()->getNumElems() >= 1);
1357 StringRef R(&Ptr.deref<char>(), Ptr.getFieldDesc()->getNumElems() - 1);
1358 uint64_t Result = getPointerAuthStableSipHash(R);
1359 pushInteger(S, Result, Call->getType());
1360 return true;
1361 }
1362
1363 static bool interp__builtin_infer_alloc_token(InterpState &S, CodePtr OpPC,
1364 const InterpFrame *Frame,
1365 const CallExpr *Call) {
1366 const ASTContext &ASTCtx = S.getASTContext();
1367 uint64_t BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
1368 auto Mode =
1369 ASTCtx.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
1370 auto MaxTokensOpt = ASTCtx.getLangOpts().AllocTokenMax;
1371 uint64_t MaxTokens =
1372 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
1373
1374 // We do not read any of the arguments; discard them.
1375 for (int I = Call->getNumArgs() - 1; I >= 0; --I)
1376 discard(S.Stk, *S.getContext().classify(Call->getArg(I)));
1377
1378 // Note: Type inference from a surrounding cast is not supported in
1379 // constexpr evaluation.
1380 QualType AllocType = infer_alloc::inferPossibleType(Call, ASTCtx, nullptr);
1381 if (AllocType.isNull()) {
1382 S.CCEDiag(Call,
1383 diag::note_constexpr_infer_alloc_token_type_inference_failed);
1384 return false;
1385 }
1386
1387 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, ASTCtx);
1388 if (!ATMD) {
1389 S.CCEDiag(Call, diag::note_constexpr_infer_alloc_token_no_metadata);
1390 return false;
1391 }
1392
1393 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
1394 if (!MaybeToken) {
1395 S.CCEDiag(Call, diag::note_constexpr_infer_alloc_token_stateful_mode);
1396 return false;
1397 }
1398
1399 pushInteger(S, llvm::APInt(BitWidth, *MaybeToken), ASTCtx.getSizeType());
1400 return true;
1401 }
1402
1403 static bool interp__builtin_operator_new(InterpState &S, CodePtr OpPC,
1404 const InterpFrame *Frame,
1405 const CallExpr *Call) {
1406 // A call to __operator_new is only valid within std::allocate<>::allocate.
1407 // Walk up the call stack to find the appropriate caller and get the
1408 // element type from it.
1409 auto [NewCall, ElemType] = S.getStdAllocatorCaller("allocate");
1410
1411 if (ElemType.isNull()) {
1412 S.FFDiag(Call, S.getLangOpts().CPlusPlus20
1413 ? diag::note_constexpr_new_untyped
1414 : diag::note_constexpr_new);
1415 return false;
1416 }
1417 assert(NewCall);
1418
1419 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
1420 S.FFDiag(Call, diag::note_constexpr_new_not_complete_object_type)
1421 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
1422 return false;
1423 }
1424
1425 // We only care about the first parameter (the size), so discard all the
1426 // others.
1427 {
1428 unsigned NumArgs = Call->getNumArgs();
1429 assert(NumArgs >= 1);
1430
1431 // The std::nothrow_t arg never gets put on the stack.
1432 if (Call->getArg(NumArgs - 1)->getType()->isNothrowT())
1433 --NumArgs;
1434 auto Args = ArrayRef(Call->getArgs(), Call->getNumArgs());
1435 // First arg is needed.
1436 Args = Args.drop_front();
1437
1438 // Discard the rest.
1439 for (const Expr *Arg : Args)
1440 discard(S.Stk, *S.getContext().classify(Arg));
1441 }
1442
1443 APSInt Bytes = popToAPSInt(S, Call->getArg(0));
1444 CharUnits ElemSize = S.getASTContext().getTypeSizeInChars(ElemType);
1445 assert(!ElemSize.isZero());
1446 // Divide the number of bytes by sizeof(ElemType), so we get the number of
1447 // elements we should allocate.
1448 APInt NumElems, Remainder;
1449 APInt ElemSizeAP(Bytes.getBitWidth(), ElemSize.getQuantity());
1450 APInt::udivrem(Bytes, ElemSizeAP, NumElems, Remainder);
1451 if (Remainder != 0) {
1452 // This likely indicates a bug in the implementation of 'std::allocator'.
1453 S.FFDiag(Call, diag::note_constexpr_operator_new_bad_size)
1454 << Bytes << APSInt(ElemSizeAP, true) << ElemType;
1455 return false;
1456 }
1457
1458 // NB: The same check we're using in CheckArraySize()
1459 if (NumElems.getActiveBits() >
1460 ConstantArrayType::getMaxSizeBits(S.getASTContext()) ||
1461 NumElems.ugt(Descriptor::MaxArrayElemBytes / ElemSize.getQuantity())) {
1462 // FIXME: NoThrow check?
1463 const SourceInfo &Loc = S.Current->getSource(OpPC);
1464 S.FFDiag(Loc, diag::note_constexpr_new_too_large)
1465 << NumElems.getZExtValue();
1466 return false;
1467 }
1468
1469 if (!CheckArraySize(S, OpPC, NumElems.getZExtValue()))
1470 return false;
1471
1472 bool IsArray = NumElems.ugt(1);
1473 OptPrimType ElemT = S.getContext().classify(ElemType);
1474 DynamicAllocator &Allocator = S.getAllocator();
1475 if (ElemT) {
1476 Block *B =
1477 Allocator.allocate(NewCall, *ElemT, NumElems.getZExtValue(),
1478 S.Ctx.getEvalID(), DynamicAllocator::Form::Operator);
1479 assert(B);
1480 S.Stk.push<Pointer>(Pointer(B).atIndex(0));
1481 return true;
1482 }
1483
1484 assert(!ElemT);
1485
1486 // Composite arrays
1487 if (IsArray) {
1488 const Descriptor *Desc =
1489 S.P.createDescriptor(NewCall, ElemType.getTypePtr(), std::nullopt);
1490 Block *B =
1491 Allocator.allocate(Desc, NumElems.getZExtValue(), S.Ctx.getEvalID(),
1492 DynamicAllocator::Form::Operator);
1493 assert(B);
1494 S.Stk.push<Pointer>(Pointer(B).atIndex(0).narrow());
1495 return true;
1496 }
1497
1498 // Records. Still allocate them as single-element arrays.
1499 QualType AllocType = S.getASTContext().getConstantArrayType(
1500 ElemType, NumElems, nullptr, ArraySizeModifier::Normal, 0);
1501
1502 const Descriptor *Desc = S.P.createDescriptor(NewCall, AllocType.getTypePtr(),
1503 Descriptor::InlineDescMD);
1504 Block *B = Allocator.allocate(Desc, S.getContext().getEvalID(),
1505 DynamicAllocator::Form::Operator);
1506 assert(B);
1507 S.Stk.push<Pointer>(Pointer(B).atIndex(0).narrow());
1508 return true;
1509 }
1510
1511 static bool interp__builtin_operator_delete(InterpState &S, CodePtr OpPC,
1512 const InterpFrame *Frame,
1513 const CallExpr *Call) {
1514 const Expr *Source = nullptr;
1515 const Block *BlockToDelete = nullptr;
1516
1517 if (S.checkingPotentialConstantExpression()) {
1518 S.Stk.discard<Pointer>();
1519 return false;
1520 }
1521
1522 // This is permitted only within a call to std::allocator<T>::deallocate.
1523 if (!S.getStdAllocatorCaller("deallocate")) {
1524 S.FFDiag(Call);
1525 S.Stk.discard<Pointer>();
1526 return true;
1527 }
1528
1529 {
1530 const Pointer &Ptr = S.Stk.pop<Pointer>();
1531
1532 if (Ptr.isZero()) {
1533 S.CCEDiag(Call, diag::note_constexpr_deallocate_null);
1534 return true;
1535 }
1536
1537 Source = Ptr.getDeclDesc()->asExpr();
1538 BlockToDelete = Ptr.block();
1539
1540 if (!BlockToDelete->isDynamic()) {
1541 S.FFDiag(Call, diag::note_constexpr_delete_not_heap_alloc)
1542 << Ptr.toDiagnosticString(S.getASTContext());
1543 if (const auto *D = Ptr.getFieldDesc()->asDecl())
1544 S.Note(D->getLocation(), diag::note_declared_at);
1545 }
1546 }
1547 assert(BlockToDelete);
1548
1549 DynamicAllocator &Allocator = S.getAllocator();
1550 const Descriptor *BlockDesc = BlockToDelete->getDescriptor();
1551 std::optional<DynamicAllocator::Form> AllocForm =
1552 Allocator.getAllocationForm(Source);
1553
1554 if (!Allocator.deallocate(Source, BlockToDelete, S)) {
1555 // Nothing has been deallocated, this must be a double-delete.
1556 const SourceInfo &Loc = S.Current->getSource(OpPC);
1557 S.FFDiag(Loc, diag::note_constexpr_double_delete);
1558 return false;
1559 }
1560 assert(AllocForm);
1561
1562 return CheckNewDeleteForms(
1563 S, OpPC, *AllocForm, DynamicAllocator::Form::Operator, BlockDesc, Source);
1564 }
1565
1566 static bool interp__builtin_arithmetic_fence(InterpState &S, CodePtr OpPC,
1567 const InterpFrame *Frame,
1568 const CallExpr *Call) {
1569 const Floating &Arg0 = S.Stk.pop<Floating>();
1570 S.Stk.push<Floating>(Arg0);
1571 return true;
1572 }
1573
1574 static bool interp__builtin_vector_reduce(InterpState &S, CodePtr OpPC,
1575 const CallExpr *Call, unsigned ID) {
1576 const Pointer &Arg = S.Stk.pop<Pointer>();
1577 assert(Arg.getFieldDesc()->isPrimitiveArray());
1578
1579 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
1580 assert(Call->getType() == ElemType);
1581 PrimType ElemT = *S.getContext().classify(ElemType);
1582 unsigned NumElems = Arg.getNumElems();
1583
1584 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
1585 T Result = Arg.elem<T>(0);
1586 unsigned BitWidth = Result.bitWidth();
1587 for (unsigned I = 1; I != NumElems; ++I) {
1588 T Elem = Arg.elem<T>(I);
1589 T PrevResult = Result;
1590
1591 if (ID == Builtin::BI__builtin_reduce_add) {
1592 if (T::add(Result, Elem, BitWidth, &Result)) {
1593 unsigned OverflowBits = BitWidth + 1;
1594 (void)handleOverflow(S, OpPC,
1595 (PrevResult.toAPSInt(OverflowBits) +
1596 Elem.toAPSInt(OverflowBits)));
1597 return false;
1598 }
1599 } else if (ID == Builtin::BI__builtin_reduce_mul) {
1600 if (T::mul(Result, Elem, BitWidth, &Result)) {
1601 unsigned OverflowBits = BitWidth * 2;
1602 (void)handleOverflow(S, OpPC,
1603 (PrevResult.toAPSInt(OverflowBits) *
1604 Elem.toAPSInt(OverflowBits)));
1605 return false;
1606 }
1607
1608 } else if (ID == Builtin::BI__builtin_reduce_and) {
1609 (void)T::bitAnd(Result, Elem, BitWidth, &Result);
1610 } else if (ID == Builtin::BI__builtin_reduce_or) {
1611 (void)T::bitOr(Result, Elem, BitWidth, &Result);
1612 } else if (ID == Builtin::BI__builtin_reduce_xor) {
1613 (void)T::bitXor(Result, Elem, BitWidth, &Result);
1614 } else if (ID == Builtin::BI__builtin_reduce_min) {
1615 if (Elem < Result)
1616 Result = Elem;
1617 } else if (ID == Builtin::BI__builtin_reduce_max) {
1618 if (Elem > Result)
1619 Result = Elem;
1620 } else {
1621 llvm_unreachable("Unhandled vector reduce builtin");
1622 }
1623 }
1624 pushInteger(S, Result.toAPSInt(), Call->getType());
1625 });
1626
1627 return true;
1628 }
1629
1630 static bool interp__builtin_elementwise_abs(InterpState &S, CodePtr OpPC,
1631 const InterpFrame *Frame,
1632 const CallExpr *Call,
1633 unsigned BuiltinID) {
1634 assert(Call->getNumArgs() == 1);
1635 QualType Ty = Call->getArg(0)->getType();
1636 if (Ty->isIntegerType()) {
1637 APSInt Val = popToAPSInt(S, Call->getArg(0));
1638 pushInteger(S, Val.abs(), Call->getType());
1639 return true;
1640 }
1641
1642 if (Ty->isFloatingType()) {
1643 Floating Val = S.Stk.pop<Floating>();
1644 Floating Result = abs(S, Val);
1645 S.Stk.push<Floating>(Result);
1646 return true;
1647 }
1648
1649 // Otherwise, the argument must be a vector.
1650 assert(Call->getArg(0)->getType()->isVectorType());
1651 const Pointer &Arg = S.Stk.pop<Pointer>();
1652 assert(Arg.getFieldDesc()->isPrimitiveArray());
1653 const Pointer &Dst = S.Stk.peek<Pointer>();
1654 assert(Dst.getFieldDesc()->isPrimitiveArray());
1655 assert(Arg.getFieldDesc()->getNumElems() ==
1656 Dst.getFieldDesc()->getNumElems());
1657
1658 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
1659 PrimType ElemT = *S.getContext().classify(ElemType);
1660 unsigned NumElems = Arg.getNumElems();
1661 // we can either have a vector of integer or a vector of floating point
1662 for (unsigned I = 0; I != NumElems; ++I) {
1663 if (ElemType->isIntegerType()) {
1664 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
1665 Dst.elem<T>(I) = T::from(static_cast<T>(
1666 APSInt(Arg.elem<T>(I).toAPSInt().abs(),
1667 ElemType->isUnsignedIntegerOrEnumerationType())));
1668 });
1669 } else {
1670 Floating Val = Arg.elem<Floating>(I);
1671 Dst.elem<Floating>(I) = abs(S, Val);
1672 }
1673 }
1674 Dst.initializeAllElements();
1675
1676 return true;
1677 }
1678
1679 /// Can be called with an integer or vector as the first and only parameter.
1680 static bool interp__builtin_elementwise_countzeroes(InterpState &S,
1681 CodePtr OpPC,
1682 const InterpFrame *Frame,
1683 const CallExpr *Call,
1684 unsigned BuiltinID) {
1685 bool HasZeroArg = Call->getNumArgs() == 2;
1686 bool IsCTTZ = BuiltinID == Builtin::BI__builtin_elementwise_ctzg;
1687 assert(Call->getNumArgs() == 1 || HasZeroArg);
1688 if (Call->getArg(0)->getType()->isIntegerType()) {
1689 PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
1690 APSInt Val = popToAPSInt(S.Stk, ArgT);
1691 std::optional<APSInt> ZeroVal;
1692 if (HasZeroArg) {
1693 ZeroVal = Val;
1694 Val = popToAPSInt(S.Stk, ArgT);
1695 }
1696
1697 if (Val.isZero()) {
1698 if (ZeroVal) {
1699 pushInteger(S, *ZeroVal, Call->getType());
1700 return true;
1701 }
1702 // If we haven't been provided the second argument, the result is
1703 // undefined
1704 S.FFDiag(S.Current->getSource(OpPC),
1705 diag::note_constexpr_countzeroes_zero)
1706 << /*IsTrailing=*/IsCTTZ;
1707 return false;
1708 }
1709
1710 if (BuiltinID == Builtin::BI__builtin_elementwise_clzg) {
1711 pushInteger(S, Val.countLeadingZeros(), Call->getType());
1712 } else {
1713 pushInteger(S, Val.countTrailingZeros(), Call->getType());
1714 }
1715 return true;
1716 }
1717 // Otherwise, the argument must be a vector.
1718 const ASTContext &ASTCtx = S.getASTContext();
1719 Pointer ZeroArg;
1720 if (HasZeroArg) {
1721 assert(Call->getArg(1)->getType()->isVectorType() &&
1722 ASTCtx.hasSameUnqualifiedType(Call->getArg(0)->getType(),
1723 Call->getArg(1)->getType()));
1724 (void)ASTCtx;
1725 ZeroArg = S.Stk.pop<Pointer>();
1726 assert(ZeroArg.getFieldDesc()->isPrimitiveArray());
1727 }
1728 assert(Call->getArg(0)->getType()->isVectorType());
1729 const Pointer &Arg = S.Stk.pop<Pointer>();
1730 assert(Arg.getFieldDesc()->isPrimitiveArray());
1731 const Pointer &Dst = S.Stk.peek<Pointer>();
1732 assert(Dst.getFieldDesc()->isPrimitiveArray());
1733 assert(Arg.getFieldDesc()->getNumElems() ==
1734 Dst.getFieldDesc()->getNumElems());
1735
1736 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
1737 PrimType ElemT = *S.getContext().classify(ElemType);
1738 unsigned NumElems = Arg.getNumElems();
1739
1740 // FIXME: Reading from uninitialized vector elements?
1741 for (unsigned I = 0; I != NumElems; ++I) {
1742 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
1743 APInt EltVal = Arg.atIndex(I).deref<T>().toAPSInt();
1744 if (EltVal.isZero()) {
1745 if (HasZeroArg) {
1746 Dst.atIndex(I).deref<T>() = ZeroArg.atIndex(I).deref<T>();
1747 } else {
1748 // If we haven't been provided the second argument, the result is
1749 // undefined
1750 S.FFDiag(S.Current->getSource(OpPC),
1751 diag::note_constexpr_countzeroes_zero)
1752 << /*IsTrailing=*/IsCTTZ;
1753 return false;
1754 }
1755 } else if (IsCTTZ) {
1756 Dst.atIndex(I).deref<T>() = T::from(EltVal.countTrailingZeros());
1757 } else {
1758 Dst.atIndex(I).deref<T>() = T::from(EltVal.countLeadingZeros());
1759 }
1760 Dst.atIndex(I).initialize();
1761 });
1762 }
1763
1764 return true;
1765 }
1766
1767 static bool interp__builtin_memcpy(InterpState &S, CodePtr OpPC,
1768 const InterpFrame *Frame,
1769 const CallExpr *Call, unsigned ID) {
1770 assert(Call->getNumArgs() == 3);
1771 const ASTContext &ASTCtx = S.getASTContext();
1772 uint64_t Size = popToUInt64(S, Call->getArg(2));
1773 Pointer SrcPtr = S.Stk.pop<Pointer>().expand();
1774 Pointer DestPtr = S.Stk.pop<Pointer>().expand();
1775
1776 if (ID == Builtin::BImemcpy || ID == Builtin::BImemmove)
1777 diagnoseNonConstexprBuiltin(S, OpPC, ID);
1778
1779 bool Move =
1780 (ID == Builtin::BI__builtin_memmove || ID == Builtin::BImemmove ||
1781 ID == Builtin::BI__builtin_wmemmove || ID == Builtin::BIwmemmove);
1782 bool WChar = ID == Builtin::BIwmemcpy || ID == Builtin::BIwmemmove ||
1783 ID == Builtin::BI__builtin_wmemcpy ||
1784 ID == Builtin::BI__builtin_wmemmove;
1785
1786 // If the size is zero, we treat this as always being a valid no-op.
1787 if (Size == 0) {
1788 S.Stk.push<Pointer>(DestPtr);
1789 return true;
1790 }
1791
1792 if (SrcPtr.isZero() || DestPtr.isZero()) {
1793 Pointer DiagPtr = (SrcPtr.isZero() ? SrcPtr : DestPtr);
1794 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_null)
1795 << /*IsMove=*/Move << /*IsWchar=*/WChar << !SrcPtr.isZero()
1796 << DiagPtr.toDiagnosticString(ASTCtx);
1797 return false;
1798 }
1799
1800 // Diagnose integral src/dest pointers specially.
1801 if (SrcPtr.isIntegralPointer() || DestPtr.isIntegralPointer()) {
1802 std::string DiagVal = "(void *)";
1803 DiagVal += SrcPtr.isIntegralPointer()
1804 ? std::to_string(SrcPtr.getIntegerRepresentation())
1805 : std::to_string(DestPtr.getIntegerRepresentation());
1806 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_null)
1807 << Move << WChar << DestPtr.isIntegralPointer() << DiagVal;
1808 return false;
1809 }
1810
1811 if (!isReadable(DestPtr) || !isReadable(SrcPtr))
1812 return false;
1813
1814 if (DestPtr.getType()->isIncompleteType()) {
1815 S.FFDiag(S.Current->getSource(OpPC),
1816 diag::note_constexpr_memcpy_incomplete_type)
1817 << Move << DestPtr.getType();
1818 return false;
1819 }
1820 if (SrcPtr.getType()->isIncompleteType()) {
1821 S.FFDiag(S.Current->getSource(OpPC),
1822 diag::note_constexpr_memcpy_incomplete_type)
1823 << Move << SrcPtr.getType();
1824 return false;
1825 }
1826
1827 QualType DestElemType = getElemType(DestPtr);
1828 if (DestElemType->isIncompleteType()) {
1829 S.FFDiag(S.Current->getSource(OpPC),
1830 diag::note_constexpr_memcpy_incomplete_type)
1831 << Move << DestElemType;
1832 return false;
1833 }
1834
1835 size_t RemainingDestElems;
1836 if (DestPtr.getFieldDesc()->isArray()) {
1837 RemainingDestElems = DestPtr.isUnknownSizeArray()
1838 ? 0
1839 : (DestPtr.getNumElems() - DestPtr.getIndex());
1840 } else {
1841 RemainingDestElems = 1;
1842 }
1843 unsigned DestElemSize = ASTCtx.getTypeSizeInChars(DestElemType).getQuantity();
1844
1845 if (WChar) {
1846 uint64_t WCharSize =
1847 ASTCtx.getTypeSizeInChars(ASTCtx.getWCharType()).getQuantity();
1848 Size *= WCharSize;
1849 }
1850
1851 if (Size % DestElemSize != 0) {
1852 S.FFDiag(S.Current->getSource(OpPC),
1853 diag::note_constexpr_memcpy_unsupported)
1854 << Move << WChar << 0 << DestElemType << Size << DestElemSize;
1855 return false;
1856 }
1857
1858 QualType SrcElemType = getElemType(SrcPtr);
1859 size_t RemainingSrcElems;
1860 if (SrcPtr.getFieldDesc()->isArray()) {
1861 RemainingSrcElems = SrcPtr.isUnknownSizeArray()
1862 ? 0
1863 : (SrcPtr.getNumElems() - SrcPtr.getIndex());
1864 } else {
1865 RemainingSrcElems = 1;
1866 }
1867 unsigned SrcElemSize = ASTCtx.getTypeSizeInChars(SrcElemType).getQuantity();
1868
1869 if (!ASTCtx.hasSameUnqualifiedType(DestElemType, SrcElemType)) {
1870 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_type_pun)
1871 << Move << SrcElemType << DestElemType;
1872 return false;
1873 }
1874
1875 if (!DestElemType.isTriviallyCopyableType(ASTCtx)) {
1876 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_nontrivial)
1877 << Move << DestElemType;
1878 return false;
1879 }
1880
1881 // Check if we have enough elements to read from and write to.
1882 size_t RemainingDestBytes = RemainingDestElems * DestElemSize;
1883 size_t RemainingSrcBytes = RemainingSrcElems * SrcElemSize;
1884 if (Size > RemainingDestBytes || Size > RemainingSrcBytes) {
1885 APInt N = APInt(64, Size / DestElemSize);
1886 S.FFDiag(S.Current->getSource(OpPC),
1887 diag::note_constexpr_memcpy_unsupported)
1888 << Move << WChar << (Size > RemainingSrcBytes ? 1 : 2) << DestElemType
1889 << toString(N, 10, /*Signed=*/false);
1890 return false;
1891 }
1892
1893 // Check for overlapping memory regions.
1894 if (!Move && Pointer::pointToSameBlock(SrcPtr, DestPtr)) {
1895 // Remove base casts.
1896 Pointer SrcP = SrcPtr;
1897 while (SrcP.isBaseClass())
1898 SrcP = SrcP.getBase();
1899
1900 Pointer DestP = DestPtr;
1901 while (DestP.isBaseClass())
1902 DestP = DestP.getBase();
1903
1904 unsigned SrcIndex = SrcP.expand().getIndex() * SrcP.elemSize();
1905 unsigned DstIndex = DestP.expand().getIndex() * DestP.elemSize();
1906
1907 if ((SrcIndex <= DstIndex && (SrcIndex + Size) > DstIndex) ||
1908 (DstIndex <= SrcIndex && (DstIndex + Size) > SrcIndex)) {
1909 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_memcpy_overlap)
1910 << /*IsWChar=*/false;
1911 return false;
1912 }
1913 }
1914
1915 assert(Size % DestElemSize == 0);
1916 if (!DoMemcpy(S, OpPC, SrcPtr, DestPtr, Bytes(Size).toBits()))
1917 return false;
1918
1919 S.Stk.push<Pointer>(DestPtr);
1920 return true;
1921 }
1922
1923 /// Determine if T is a character type for which we guarantee that
1924 /// sizeof(T) == 1.
1925 static bool isOneByteCharacterType(QualType T) {
1926 return T->isCharType() || T->isChar8Type();
1927 }
1928
1929 static bool interp__builtin_memcmp(InterpState &S, CodePtr OpPC,
1930 const InterpFrame *Frame,
1931 const CallExpr *Call, unsigned ID) {
1932 assert(Call->getNumArgs() == 3);
1933 uint64_t Size = popToUInt64(S, Call->getArg(2));
1934 const Pointer &PtrB = S.Stk.pop<Pointer>();
1935 const Pointer &PtrA = S.Stk.pop<Pointer>();
1936
1937 if (ID == Builtin::BImemcmp || ID == Builtin::BIbcmp ||
1938 ID == Builtin::BIwmemcmp)
1939 diagnoseNonConstexprBuiltin(S, OpPC, ID);
1940
1941 if (Size == 0) {
1942 pushInteger(S, 0, Call->getType());
1943 return true;
1944 }
1945
1946 if (!PtrA.isBlockPointer() || !PtrB.isBlockPointer())
1947 return false;
1948
1949 bool IsWide =
1950 (ID == Builtin::BIwmemcmp || ID == Builtin::BI__builtin_wmemcmp);
1951
1952 const ASTContext &ASTCtx = S.getASTContext();
1953 QualType ElemTypeA = getElemType(PtrA);
1954 QualType ElemTypeB = getElemType(PtrB);
1955 // FIXME: This is an arbitrary limitation the current constant interpreter
1956 // had. We could remove this.
1957 if (!IsWide && (!isOneByteCharacterType(ElemTypeA) ||
1958 !isOneByteCharacterType(ElemTypeB))) {
1959 S.FFDiag(S.Current->getSource(OpPC),
1960 diag::note_constexpr_memcmp_unsupported)
1961 << ASTCtx.BuiltinInfo.getQuotedName(ID) << PtrA.getType()
1962 << PtrB.getType();
1963 return false;
1964 }
1965
1966 if (PtrA.isDummy() || PtrB.isDummy())
1967 return false;
1968
1969 if (!CheckRange(S, OpPC, PtrA, AK_Read) ||
1970 !CheckRange(S, OpPC, PtrB, AK_Read))
1971 return false;
1972
1973 // Now, read both pointers to a buffer and compare those.
1974 BitcastBuffer BufferA(
1975 Bits(ASTCtx.getTypeSize(ElemTypeA) * PtrA.getNumElems()));
1976 readPointerToBuffer(S.getContext(), PtrA, BufferA, false);
1977 // FIXME: The swapping here is UNDOING something we do when reading the
1978 // data into the buffer.
1979 if (ASTCtx.getTargetInfo().isBigEndian())
1980 swapBytes(BufferA.Data.get(), BufferA.byteSize().getQuantity());
1981
1982 BitcastBuffer BufferB(
1983 Bits(ASTCtx.getTypeSize(ElemTypeB) * PtrB.getNumElems()));
1984 readPointerToBuffer(S.getContext(), PtrB, BufferB, false);
1985 // FIXME: The swapping here is UNDOING something we do when reading the
1986 // data into the buffer.
1987 if (ASTCtx.getTargetInfo().isBigEndian())
1988 swapBytes(BufferB.Data.get(), BufferB.byteSize().getQuantity());
1989
1990 size_t MinBufferSize = std::min(BufferA.byteSize().getQuantity(),
1991 BufferB.byteSize().getQuantity());
1992
1993 unsigned ElemSize = 1;
1994 if (IsWide)
1995 ElemSize = ASTCtx.getTypeSizeInChars(ASTCtx.getWCharType()).getQuantity();
1996 // The Size given for the wide variants is in wide-char units. Convert it
1997 // to bytes.
1998 size_t ByteSize = Size * ElemSize;
1999 size_t CmpSize = std::min(MinBufferSize, ByteSize);
2000
2001 for (size_t I = 0; I != CmpSize; I += ElemSize) {
2002 if (IsWide) {
2003 INT_TYPE_SWITCH(*S.getContext().classify(ASTCtx.getWCharType()), {
2004 T A = *reinterpret_cast<T *>(BufferA.atByte(I));
2005 T B = *reinterpret_cast<T *>(BufferB.atByte(I));
2006 if (A < B) {
2007 pushInteger(S, -1, Call->getType());
2008 return true;
2009 }
2010 if (A > B) {
2011 pushInteger(S, 1, Call->getType());
2012 return true;
2013 }
2014 });
2015 } else {
2016 std::byte A = BufferA.deref<std::byte>(Bytes(I));
2017 std::byte B = BufferB.deref<std::byte>(Bytes(I));
2018
2019 if (A < B) {
2020 pushInteger(S, -1, Call->getType());
2021 return true;
2022 }
2023 if (A > B) {
2024 pushInteger(S, 1, Call->getType());
2025 return true;
2026 }
2027 }
2028 }
2029
2030 // We compared CmpSize bytes above. If the limiting factor was the Size
2031 // passed, we're done and the result is equality (0).
2032 if (ByteSize <= CmpSize) {
2033 pushInteger(S, 0, Call->getType());
2034 return true;
2035 }
2036
2037 // However, if we read all the available bytes but were instructed to read
2038 // even more, diagnose this as a "read of dereferenced one-past-the-end
2039 // pointer". This is what would happen if we called CheckLoad() on every array
2040 // element.
2041 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
2042 << AK_Read << S.Current->getRange(OpPC);
2043 return false;
2044 }
2045
2046 // __builtin_memchr(ptr, int, int)
2047 // __builtin_strchr(ptr, int)
2048 static bool interp__builtin_memchr(InterpState &S, CodePtr OpPC,
2049 const CallExpr *Call, unsigned ID) {
2050 if (ID == Builtin::BImemchr || ID == Builtin::BIwcschr ||
2051 ID == Builtin::BIstrchr || ID == Builtin::BIwmemchr)
2052 diagnoseNonConstexprBuiltin(S, OpPC, ID);
2053
2054 std::optional<APSInt> MaxLength;
2055 if (Call->getNumArgs() == 3)
2056 MaxLength = popToAPSInt(S, Call->getArg(2));
2057
2058 APSInt Desired = popToAPSInt(S, Call->getArg(1));
2059 const Pointer &Ptr = S.Stk.pop<Pointer>();
2060
2061 if (MaxLength && MaxLength->isZero()) {
2062 S.Stk.push<Pointer>();
2063 return true;
2064 }
2065
2066 if (Ptr.isDummy()) {
2067 if (Ptr.getType()->isIncompleteType())
2068 S.FFDiag(S.Current->getSource(OpPC),
2069 diag::note_constexpr_ltor_incomplete_type)
2070 << Ptr.getType();
2071 return false;
2072 }
2073
2074 // Null is only okay if the given size is 0.
2075 if (Ptr.isZero()) {
2076 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
2077 << AK_Read;
2078 return false;
2079 }
2080
2081 if (!Ptr.isBlockPointer())
2082 return false;
2083
2084 QualType ElemTy = Ptr.getFieldDesc()->isArray()
2085 ? Ptr.getFieldDesc()->getElemQualType()
2086 : Ptr.getFieldDesc()->getType();
2087 bool IsRawByte = ID == Builtin::BImemchr || ID == Builtin::BI__builtin_memchr;
2088
2089 // Give up on byte-oriented matching against multibyte elements.
2090 if (IsRawByte && !isOneByteCharacterType(ElemTy)) {
2091 S.FFDiag(S.Current->getSource(OpPC),
2092 diag::note_constexpr_memchr_unsupported)
2093 << S.getASTContext().BuiltinInfo.getQuotedName(ID) << ElemTy;
2094 return false;
2095 }
2096
2097 if (!isReadable(Ptr))
2098 return false;
2099
2100 if (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr) {
2101 int64_t DesiredTrunc;
2102 if (S.getASTContext().CharTy->isSignedIntegerType())
2103 DesiredTrunc =
2104 Desired.trunc(S.getASTContext().getCharWidth()).getSExtValue();
2105 else
2106 DesiredTrunc =
2107 Desired.trunc(S.getASTContext().getCharWidth()).getZExtValue();
2108 // strchr compares directly to the passed integer, and therefore
2109 // always fails if given an int that is not a char.
2110 if (Desired != DesiredTrunc) {
2111 S.Stk.push<Pointer>();
2112 return true;
2113 }
2114 }
2115
2116 uint64_t DesiredVal;
2117 if (ID == Builtin::BIwmemchr || ID == Builtin::BI__builtin_wmemchr ||
2118 ID == Builtin::BIwcschr || ID == Builtin::BI__builtin_wcschr) {
2119 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
2120 DesiredVal = Desired.getZExtValue();
2121 } else {
2122 DesiredVal = Desired.trunc(S.getASTContext().getCharWidth()).getZExtValue();
2123 }
2124
2125 bool StopAtZero =
2126 (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr ||
2127 ID == Builtin::BIwcschr || ID == Builtin::BI__builtin_wcschr);
2128
2129 PrimType ElemT =
2130 IsRawByte ? PT_Sint8 : *S.getContext().classify(getElemType(Ptr));
2131
2132 size_t Index = Ptr.getIndex();
2133 size_t Step = 0;
2134 for (;;) {
2135 const Pointer &ElemPtr =
2136 (Index + Step) > 0 ? Ptr.atIndex(Index + Step) : Ptr;
2137
2138 if (!CheckLoad(S, OpPC, ElemPtr))
2139 return false;
2140
2141 uint64_t V;
2142 INT_TYPE_SWITCH_NO_BOOL(
2143 ElemT, { V = static_cast<uint64_t>(ElemPtr.deref<T>().toUnsigned()); });
2144
2145 if (V == DesiredVal) {
2146 S.Stk.push<Pointer>(ElemPtr);
2147 return true;
2148 }
2149
2150 if (StopAtZero && V == 0)
2151 break;
2152
2153 ++Step;
2154 if (MaxLength && Step == MaxLength->getZExtValue())
2155 break;
2156 }
2157
2158 S.Stk.push<Pointer>();
2159 return true;
2160 }
2161
2162 static std::optional<unsigned> computeFullDescSize(const ASTContext &ASTCtx,
2163 const Descriptor *Desc) {
2164 if (Desc->isPrimitive())
2165 return ASTCtx.getTypeSizeInChars(Desc->getType()).getQuantity();
2166 if (Desc->isArray())
2167 return ASTCtx.getTypeSizeInChars(Desc->getElemQualType()).getQuantity() *
2168 Desc->getNumElems();
2169 if (Desc->isRecord()) {
2170 // Can't use Descriptor::getType() as that may return a pointer type. Look
2171 // at the decl directly.
2172 return ASTCtx
2173 .getTypeSizeInChars(
2174 ASTCtx.getCanonicalTagType(Desc->ElemRecord->getDecl()))
2175 .getQuantity();
2176 }
2177
2178 return std::nullopt;
2179 }
2180
2181 /// Compute the byte offset of \p Ptr in the full declaration.
2182 static unsigned computePointerOffset(const ASTContext &ASTCtx,
2183 const Pointer &Ptr) {
2184 unsigned Result = 0;
2185
2186 Pointer P = Ptr;
2187 while (P.isField() || P.isArrayElement()) {
2188 P = P.expand();
2189 const Descriptor *D = P.getFieldDesc();
2190
2191 if (P.isArrayElement()) {
2192 unsigned ElemSize =
2193 ASTCtx.getTypeSizeInChars(D->getElemQualType()).getQuantity();
2194 if (P.isOnePastEnd())
2195 Result += ElemSize * P.getNumElems();
2196 else
2197 Result += ElemSize * P.getIndex();
2198 P = P.expand().getArray();
2199 } else if (P.isBaseClass()) {
2200 const auto *RD = cast<CXXRecordDecl>(D->asDecl());
2201 bool IsVirtual = Ptr.isVirtualBaseClass();
2202 P = P.getBase();
2203 const Record *BaseRecord = P.getRecord();
2204
2205 const ASTRecordLayout &Layout =
2206 ASTCtx.getASTRecordLayout(cast<CXXRecordDecl>(BaseRecord->getDecl()));
2207 if (IsVirtual)
2208 Result += Layout.getVBaseClassOffset(RD).getQuantity();
2209 else
2210 Result += Layout.getBaseClassOffset(RD).getQuantity();
2211 } else if (P.isField()) {
2212 const FieldDecl *FD = P.getField();
2213 const ASTRecordLayout &Layout =
2214 ASTCtx.getASTRecordLayout(FD->getParent());
2215 unsigned FieldIndex = FD->getFieldIndex();
2216 uint64_t FieldOffset =
2217 ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex))
2218 .getQuantity();
2219 Result += FieldOffset;
2220 P = P.getBase();
2221 } else
2222 llvm_unreachable("Unhandled descriptor type");
2223 }
2224
2225 return Result;
2226 }
2227
2228 /// Does Ptr point to the last subobject?
2229 static bool pointsToLastObject(const Pointer &Ptr) {
2230 Pointer P = Ptr;
2231 while (!P.isRoot()) {
2232
2233 if (P.isArrayElement()) {
2234 P = P.expand().getArray();
2235 continue;
2236 }
2237 if (P.isBaseClass()) {
2238 if (P.getRecord()->getNumFields() > 0)
2239 return false;
2240 P = P.getBase();
2241 continue;
2242 }
2243
2244 Pointer Base = P.getBase();
2245 if (const Record *R = Base.getRecord()) {
2246 assert(P.getField());
2247 if (P.getField()->getFieldIndex() != R->getNumFields() - 1)
2248 return false;
2249 }
2250 P = Base;
2251 }
2252
2253 return true;
2254 }
2255
2256 /// Does Ptr point to the last object AND to a flexible array member?
2257 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const Pointer &Ptr) {
2258 auto isFlexibleArrayMember = [&](const Descriptor *FieldDesc) {
2259 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
2260 FAMKind StrictFlexArraysLevel =
2261 Ctx.getLangOpts().getStrictFlexArraysLevel();
2262
2263 if (StrictFlexArraysLevel == FAMKind::Default)
2264 return true;
2265
2266 unsigned NumElems = FieldDesc->getNumElems();
2267 if (NumElems == 0 && StrictFlexArraysLevel != FAMKind::IncompleteOnly)
2268 return true;
2269
2270 if (NumElems == 1 && StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
2271 return true;
2272 return false;
2273 };
2274
2275 const Descriptor *FieldDesc = Ptr.getFieldDesc();
2276 if (!FieldDesc->isArray())
2277 return false;
2278
2279 return Ptr.isDummy() && pointsToLastObject(Ptr) &&
2280 isFlexibleArrayMember(FieldDesc);
2281 }
2282
2283 static bool interp__builtin_object_size(InterpState &S, CodePtr OpPC,
2284 const InterpFrame *Frame,
2285 const CallExpr *Call) {
2286 const ASTContext &ASTCtx = S.getASTContext();
2287 // From the GCC docs:
2288 // Kind is an integer constant from 0 to 3. If the least significant bit is
2289 // clear, objects are whole variables. If it is set, a closest surrounding
2290 // subobject is considered the object a pointer points to. The second bit
2291 // determines if maximum or minimum of remaining bytes is computed.
2292 unsigned Kind = popToUInt64(S, Call->getArg(1));
2293 assert(Kind <= 3 && "unexpected kind");
2294 bool UseFieldDesc = (Kind & 1u);
2295 bool ReportMinimum = (Kind & 2u);
2296 const Pointer &Ptr = S.Stk.pop<Pointer>();
2297
2298 if (Call->getArg(0)->HasSideEffects(ASTCtx)) {
2299 // "If there are any side effects in them, it returns (size_t) -1
2300 // for type 0 or 1 and (size_t) 0 for type 2 or 3."
2301 pushInteger(S, Kind <= 1 ? -1 : 0, Call->getType());
2302 return true;
2303 }
2304
2305 if (Ptr.isZero() || !Ptr.isBlockPointer())
2306 return false;
2307
2308 // We can't load through pointers.
2309 if (Ptr.isDummy() && Ptr.getType()->isPointerType())
2310 return false;
2311
2312 bool DetermineForCompleteObject = Ptr.getFieldDesc() == Ptr.getDeclDesc();
2313 const Descriptor *DeclDesc = Ptr.getDeclDesc();
2314 assert(DeclDesc);
2315
2316 if (!UseFieldDesc || DetermineForCompleteObject) {
2317 // Lower bound, so we can't fall back to this.
2318 if (ReportMinimum && !DetermineForCompleteObject)
2319 return false;
2320
2321 // Can't read beyond the pointer decl desc.
2322 if (!UseFieldDesc && !ReportMinimum && DeclDesc->getType()->isPointerType())
2323 return false;
2324 } else {
2325 if (isUserWritingOffTheEnd(ASTCtx, Ptr.expand())) {
2326 // If we cannot determine the size of the initial allocation, then we
2327 // can't given an accurate upper-bound. However, we are still able to give
2328 // conservative lower-bounds for Type=3.
2329 if (Kind == 1)
2330 return false;
2331 }
2332 }
2333
2334 const Descriptor *Desc = UseFieldDesc ? Ptr.getFieldDesc() : DeclDesc;
2335 assert(Desc);
2336
2337 std::optional<unsigned> FullSize = computeFullDescSize(ASTCtx, Desc);
2338 if (!FullSize)
2339 return false;
2340
2341 unsigned ByteOffset;
2342 if (UseFieldDesc) {
2343 if (Ptr.isBaseClass())
2344 ByteOffset = computePointerOffset(ASTCtx, Ptr.getBase()) -
2345 computePointerOffset(ASTCtx, Ptr);
2346 else {
2347 if (Ptr.inArray())
2348 ByteOffset =
2349 computePointerOffset(ASTCtx, Ptr) -
2350 computePointerOffset(ASTCtx, Ptr.expand().atIndex(0).narrow());
2351 else
2352 ByteOffset = 0;
2353 }
2354 } else
2355 ByteOffset = computePointerOffset(ASTCtx, Ptr);
2356
2357 assert(ByteOffset <= *FullSize);
2358 unsigned Result = *FullSize - ByteOffset;
2359
2360 pushInteger(S, Result, Call->getType());
2361 return true;
2362 }
2363
2364 static bool interp__builtin_is_within_lifetime(InterpState &S, CodePtr OpPC,
2365 const CallExpr *Call) {
2366
2367 if (!S.inConstantContext())
2368 return false;
2369
2370 const Pointer &Ptr = S.Stk.pop<Pointer>();
2371
2372 auto Error = [&](int Diag) {
2373 bool CalledFromStd = false;
2374 const auto *Callee = S.Current->getCallee();
2375 if (Callee && Callee->isInStdNamespace()) {
2376 const IdentifierInfo *Identifier = Callee->getIdentifier();
2377 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
2378 }
2379 S.CCEDiag(CalledFromStd
2380 ? S.Current->Caller->getSource(S.Current->getRetPC())
2381 : S.Current->getSource(OpPC),
2382 diag::err_invalid_is_within_lifetime)
2383 << (CalledFromStd ? "std::is_within_lifetime"
2384 : "__builtin_is_within_lifetime")
2385 << Diag;
2386 return false;
2387 };
2388
2389 if (Ptr.isZero())
2390 return Error(0);
2391 if (Ptr.isOnePastEnd())
2392 return Error(1);
2393
2394 bool Result = Ptr.getLifetime() != Lifetime::Ended;
2395 if (!Ptr.isActive()) {
2396 Result = false;
2397 } else {
2398 if (!CheckLive(S, OpPC, Ptr, AK_Read))
2399 return false;
2400 if (!CheckMutable(S, OpPC, Ptr))
2401 return false;
2402 if (!CheckDummy(S, OpPC, Ptr.block(), AK_Read))
2403 return false;
2404 }
2405
2406 // Check if we're currently running an initializer.
2407 if (llvm::is_contained(S.InitializingBlocks, Ptr.block()))
2408 return Error(2);
2409 if (S.EvaluatingDecl && Ptr.getDeclDesc()->asVarDecl() == S.EvaluatingDecl)
2410 return Error(2);
2411
2412 pushInteger(S, Result, Call->getType());
2413 return true;
2414 }
2415
2416 static bool interp__builtin_elementwise_int_unaryop(
2417 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2418 llvm::function_ref<APInt(const APSInt &)> Fn) {
2419 assert(Call->getNumArgs() == 1);
2420
2421 // Single integer case.
2422 if (!Call->getArg(0)->getType()->isVectorType()) {
2423 assert(Call->getType()->isIntegerType());
2424 APSInt Src = popToAPSInt(S, Call->getArg(0));
2425 APInt Result = Fn(Src);
2426 pushInteger(S, APSInt(std::move(Result), !Src.isSigned()), Call->getType());
2427 return true;
2428 }
2429
2430 // Vector case.
2431 const Pointer &Arg = S.Stk.pop<Pointer>();
2432 assert(Arg.getFieldDesc()->isPrimitiveArray());
2433 const Pointer &Dst = S.Stk.peek<Pointer>();
2434 assert(Dst.getFieldDesc()->isPrimitiveArray());
2435 assert(Arg.getFieldDesc()->getNumElems() ==
2436 Dst.getFieldDesc()->getNumElems());
2437
2438 QualType ElemType = Arg.getFieldDesc()->getElemQualType();
2439 PrimType ElemT = *S.getContext().classify(ElemType);
2440 unsigned NumElems = Arg.getNumElems();
2441 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2442
2443 for (unsigned I = 0; I != NumElems; ++I) {
2444 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2445 APSInt Src = Arg.elem<T>(I).toAPSInt();
2446 APInt Result = Fn(Src);
2447 Dst.elem<T>(I) = static_cast<T>(APSInt(std::move(Result), DestUnsigned));
2448 });
2449 }
2450 Dst.initializeAllElements();
2451
2452 return true;
2453 }
2454
2455 static bool interp__builtin_elementwise_fp_binop(
2456 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2457 llvm::function_ref<APFloat(const APFloat &, const APFloat &,
2458 std::optional<APSInt> RoundingMode)>
2459 Fn) {
2460 assert((Call->getNumArgs() == 2) || (Call->getNumArgs() == 3));
2461 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2462 assert(VT->getElementType()->isFloatingType());
2463 unsigned NumElems = VT->getNumElements();
2464
2465 // Vector case.
2466 assert(Call->getArg(0)->getType()->isVectorType() &&
2467 Call->getArg(1)->getType()->isVectorType());
2468 assert(VT->getElementType() ==
2469 Call->getArg(1)->getType()->castAs<VectorType>()->getElementType());
2470 assert(VT->getNumElements() ==
2471 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements());
2472
2473 std::optional<APSInt> RoundingMode = std::nullopt;
2474 if (Call->getNumArgs() == 3)
2475 RoundingMode = popToAPSInt(S, Call->getArg(2));
2476
2477 const Pointer &BPtr = S.Stk.pop<Pointer>();
2478 const Pointer &APtr = S.Stk.pop<Pointer>();
2479 const Pointer &Dst = S.Stk.peek<Pointer>();
2480 for (unsigned ElemIdx = 0; ElemIdx != NumElems; ++ElemIdx) {
2481 using T = PrimConv<PT_Float>::T;
2482 APFloat ElemA = APtr.elem<T>(ElemIdx).getAPFloat();
2483 APFloat ElemB = BPtr.elem<T>(ElemIdx).getAPFloat();
2484 if (ElemA.isNaN() || ElemA.isInfinity() || ElemA.isDenormal() ||
2485 ElemB.isNaN() || ElemB.isInfinity() || ElemB.isDenormal())
2486 return false;
2487 Dst.elem<T>(ElemIdx) = static_cast<T>(Fn(ElemA, ElemB, RoundingMode));
2488 }
2489
2490 Dst.initializeAllElements();
2491
2492 return true;
2493 }
2494
2495 static bool interp__builtin_elementwise_int_binop(
2496 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2497 llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
2498 assert(Call->getNumArgs() == 2);
2499
2500 // Single integer case.
2501 if (!Call->getArg(0)->getType()->isVectorType()) {
2502 assert(!Call->getArg(1)->getType()->isVectorType());
2503 APSInt RHS = popToAPSInt(S, Call->getArg(1));
2504 APSInt LHS = popToAPSInt(S, Call->getArg(0));
2505 APInt Result = Fn(LHS, RHS);
2506 pushInteger(S, APSInt(std::move(Result), !LHS.isSigned()), Call->getType());
2507 return true;
2508 }
2509
2510 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2511 assert(VT->getElementType()->isIntegralOrEnumerationType());
2512 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2513 unsigned NumElems = VT->getNumElements();
2514 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2515
2516 // Vector + Scalar case.
2517 if (!Call->getArg(1)->getType()->isVectorType()) {
2518 assert(Call->getArg(1)->getType()->isIntegralOrEnumerationType());
2519
2520 APSInt RHS = popToAPSInt(S, Call->getArg(1));
2521 const Pointer &LHS = S.Stk.pop<Pointer>();
2522 const Pointer &Dst = S.Stk.peek<Pointer>();
2523
2524 for (unsigned I = 0; I != NumElems; ++I) {
2525 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2526 Dst.elem<T>(I) = static_cast<T>(
2527 APSInt(Fn(LHS.elem<T>(I).toAPSInt(), RHS), DestUnsigned));
2528 });
2529 }
2530 Dst.initializeAllElements();
2531 return true;
2532 }
2533
2534 // Vector case.
2535 assert(Call->getArg(0)->getType()->isVectorType() &&
2536 Call->getArg(1)->getType()->isVectorType());
2537 assert(VT->getElementType() ==
2538 Call->getArg(1)->getType()->castAs<VectorType>()->getElementType());
2539 assert(VT->getNumElements() ==
2540 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements());
2541 assert(VT->getElementType()->isIntegralOrEnumerationType());
2542
2543 const Pointer &RHS = S.Stk.pop<Pointer>();
2544 const Pointer &LHS = S.Stk.pop<Pointer>();
2545 const Pointer &Dst = S.Stk.peek<Pointer>();
2546 for (unsigned I = 0; I != NumElems; ++I) {
2547 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2548 APSInt Elem1 = LHS.elem<T>(I).toAPSInt();
2549 APSInt Elem2 = RHS.elem<T>(I).toAPSInt();
2550 Dst.elem<T>(I) = static_cast<T>(APSInt(Fn(Elem1, Elem2), DestUnsigned));
2551 });
2552 }
2553 Dst.initializeAllElements();
2554
2555 return true;
2556 }
2557
2558 static bool
2559 interp__builtin_x86_pack(InterpState &S, CodePtr, const CallExpr *E,
2560 llvm::function_ref<APInt(const APSInt &)> PackFn) {
2561 const auto *VT0 = E->getArg(0)->getType()->castAs<VectorType>();
2562 [[maybe_unused]] const auto *VT1 =
2563 E->getArg(1)->getType()->castAs<VectorType>();
2564 assert(VT0 && VT1 && "pack builtin VT0 and VT1 must be VectorType");
2565 assert(VT0->getElementType() == VT1->getElementType() &&
2566 VT0->getNumElements() == VT1->getNumElements() &&
2567 "pack builtin VT0 and VT1 ElementType must be same");
2568
2569 const Pointer &RHS = S.Stk.pop<Pointer>();
2570 const Pointer &LHS = S.Stk.pop<Pointer>();
2571 const Pointer &Dst = S.Stk.peek<Pointer>();
2572
2573 const ASTContext &ASTCtx = S.getASTContext();
2574 unsigned SrcBits = ASTCtx.getIntWidth(VT0->getElementType());
2575 unsigned LHSVecLen = VT0->getNumElements();
2576 unsigned SrcPerLane = 128 / SrcBits;
2577 unsigned Lanes = LHSVecLen * SrcBits / 128;
2578
2579 PrimType SrcT = *S.getContext().classify(VT0->getElementType());
2580 PrimType DstT = *S.getContext().classify(getElemType(Dst));
2581 bool IsUnsigend = getElemType(Dst)->isUnsignedIntegerType();
2582
2583 for (unsigned Lane = 0; Lane != Lanes; ++Lane) {
2584 unsigned BaseSrc = Lane * SrcPerLane;
2585 unsigned BaseDst = Lane * (2 * SrcPerLane);
2586
2587 for (unsigned I = 0; I != SrcPerLane; ++I) {
2588 INT_TYPE_SWITCH_NO_BOOL(SrcT, {
2589 APSInt A = LHS.elem<T>(BaseSrc + I).toAPSInt();
2590 APSInt B = RHS.elem<T>(BaseSrc + I).toAPSInt();
2591
2592 assignInteger(S, Dst.atIndex(BaseDst + I), DstT,
2593 APSInt(PackFn(A), IsUnsigend));
2594 assignInteger(S, Dst.atIndex(BaseDst + SrcPerLane + I), DstT,
2595 APSInt(PackFn(B), IsUnsigend));
2596 });
2597 }
2598 }
2599
2600 Dst.initializeAllElements();
2601 return true;
2602 }
2603
2604 static bool interp__builtin_elementwise_maxmin(InterpState &S, CodePtr OpPC,
2605 const CallExpr *Call,
2606 unsigned BuiltinID) {
2607 assert(Call->getNumArgs() == 2);
2608
2609 QualType Arg0Type = Call->getArg(0)->getType();
2610
2611 // TODO: Support floating-point types.
2612 if (!(Arg0Type->isIntegerType() ||
2613 (Arg0Type->isVectorType() &&
2614 Arg0Type->castAs<VectorType>()->getElementType()->isIntegerType())))
2615 return false;
2616
2617 if (!Arg0Type->isVectorType()) {
2618 assert(!Call->getArg(1)->getType()->isVectorType());
2619 APSInt RHS = popToAPSInt(S, Call->getArg(1));
2620 APSInt LHS = popToAPSInt(S, Arg0Type);
2621 APInt Result;
2622 if (BuiltinID == Builtin::BI__builtin_elementwise_max) {
2623 Result = std::max(LHS, RHS);
2624 } else if (BuiltinID == Builtin::BI__builtin_elementwise_min) {
2625 Result = std::min(LHS, RHS);
2626 } else {
2627 llvm_unreachable("Wrong builtin ID");
2628 }
2629
2630 pushInteger(S, APSInt(Result, !LHS.isSigned()), Call->getType());
2631 return true;
2632 }
2633
2634 // Vector case.
2635 assert(Call->getArg(0)->getType()->isVectorType() &&
2636 Call->getArg(1)->getType()->isVectorType());
2637 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2638 assert(VT->getElementType() ==
2639 Call->getArg(1)->getType()->castAs<VectorType>()->getElementType());
2640 assert(VT->getNumElements() ==
2641 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements());
2642 assert(VT->getElementType()->isIntegralOrEnumerationType());
2643
2644 const Pointer &RHS = S.Stk.pop<Pointer>();
2645 const Pointer &LHS = S.Stk.pop<Pointer>();
2646 const Pointer &Dst = S.Stk.peek<Pointer>();
2647 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2648 unsigned NumElems = VT->getNumElements();
2649 for (unsigned I = 0; I != NumElems; ++I) {
2650 APSInt Elem1;
2651 APSInt Elem2;
2652 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2653 Elem1 = LHS.elem<T>(I).toAPSInt();
2654 Elem2 = RHS.elem<T>(I).toAPSInt();
2655 });
2656
2657 APSInt Result;
2658 if (BuiltinID == Builtin::BI__builtin_elementwise_max) {
2659 Result = APSInt(std::max(Elem1, Elem2),
2660 Call->getType()->isUnsignedIntegerOrEnumerationType());
2661 } else if (BuiltinID == Builtin::BI__builtin_elementwise_min) {
2662 Result = APSInt(std::min(Elem1, Elem2),
2663 Call->getType()->isUnsignedIntegerOrEnumerationType());
2664 } else {
2665 llvm_unreachable("Wrong builtin ID");
2666 }
2667
2668 INT_TYPE_SWITCH_NO_BOOL(ElemT,
2669 { Dst.elem<T>(I) = static_cast<T>(Result); });
2670 }
2671 Dst.initializeAllElements();
2672
2673 return true;
2674 }
2675
2676 static bool interp__builtin_ia32_pmul(
2677 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2678 llvm::function_ref<APInt(const APSInt &, const APSInt &, const APSInt &,
2679 const APSInt &)>
2680 Fn) {
2681 assert(Call->getArg(0)->getType()->isVectorType() &&
2682 Call->getArg(1)->getType()->isVectorType());
2683 const Pointer &RHS = S.Stk.pop<Pointer>();
2684 const Pointer &LHS = S.Stk.pop<Pointer>();
2685 const Pointer &Dst = S.Stk.peek<Pointer>();
2686
2687 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2688 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2689 unsigned NumElems = VT->getNumElements();
2690 const auto *DestVT = Call->getType()->castAs<VectorType>();
2691 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
2692 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2693
2694 unsigned DstElem = 0;
2695 for (unsigned I = 0; I != NumElems; I += 2) {
2696 APSInt Result;
2697 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2698 APSInt LoLHS = LHS.elem<T>(I).toAPSInt();
2699 APSInt HiLHS = LHS.elem<T>(I + 1).toAPSInt();
2700 APSInt LoRHS = RHS.elem<T>(I).toAPSInt();
2701 APSInt HiRHS = RHS.elem<T>(I + 1).toAPSInt();
2702 Result = APSInt(Fn(LoLHS, HiLHS, LoRHS, HiRHS), DestUnsigned);
2703 });
2704
2705 INT_TYPE_SWITCH_NO_BOOL(DestElemT,
2706 { Dst.elem<T>(DstElem) = static_cast<T>(Result); });
2707 ++DstElem;
2708 }
2709
2710 Dst.initializeAllElements();
2711 return true;
2712 }
2713
2714 static bool interp_builtin_horizontal_int_binop(
2715 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2716 llvm::function_ref<APInt(const APSInt &, const APSInt &)> Fn) {
2717 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2718 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2719 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2720
2721 const Pointer &RHS = S.Stk.pop<Pointer>();
2722 const Pointer &LHS = S.Stk.pop<Pointer>();
2723 const Pointer &Dst = S.Stk.peek<Pointer>();
2724 unsigned NumElts = VT->getNumElements();
2725 unsigned EltBits = S.getASTContext().getIntWidth(VT->getElementType());
2726 unsigned EltsPerLane = 128 / EltBits;
2727 unsigned Lanes = NumElts * EltBits / 128;
2728 unsigned DestIndex = 0;
2729
2730 for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2731 unsigned LaneStart = Lane * EltsPerLane;
2732 for (unsigned I = 0; I < EltsPerLane; I += 2) {
2733 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2734 APSInt Elem1 = LHS.elem<T>(LaneStart + I).toAPSInt();
2735 APSInt Elem2 = LHS.elem<T>(LaneStart + I + 1).toAPSInt();
2736 APSInt ResL = APSInt(Fn(Elem1, Elem2), DestUnsigned);
2737 Dst.elem<T>(DestIndex++) = static_cast<T>(ResL);
2738 });
2739 }
2740
2741 for (unsigned I = 0; I < EltsPerLane; I += 2) {
2742 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2743 APSInt Elem1 = RHS.elem<T>(LaneStart + I).toAPSInt();
2744 APSInt Elem2 = RHS.elem<T>(LaneStart + I + 1).toAPSInt();
2745 APSInt ResR = APSInt(Fn(Elem1, Elem2), DestUnsigned);
2746 Dst.elem<T>(DestIndex++) = static_cast<T>(ResR);
2747 });
2748 }
2749 }
2750 Dst.initializeAllElements();
2751 return true;
2752 }
2753
2754 static bool interp_builtin_horizontal_fp_binop(
2755 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2756 llvm::function_ref<APFloat(const APFloat &, const APFloat &,
2757 llvm::RoundingMode)>
2758 Fn) {
2759 const Pointer &RHS = S.Stk.pop<Pointer>();
2760 const Pointer &LHS = S.Stk.pop<Pointer>();
2761 const Pointer &Dst = S.Stk.peek<Pointer>();
2762 FPOptions FPO = Call->getFPFeaturesInEffect(S.Ctx.getLangOpts());
2763 llvm::RoundingMode RM = getRoundingMode(FPO);
2764 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2765
2766 unsigned NumElts = VT->getNumElements();
2767 unsigned EltBits = S.getASTContext().getTypeSize(VT->getElementType());
2768 unsigned NumLanes = NumElts * EltBits / 128;
2769 unsigned NumElemsPerLane = NumElts / NumLanes;
2770 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
2771
2772 for (unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
2773 using T = PrimConv<PT_Float>::T;
2774 for (unsigned E = 0; E != HalfElemsPerLane; ++E) {
2775 APFloat Elem1 = LHS.elem<T>(L + (2 * E) + 0).getAPFloat();
2776 APFloat Elem2 = LHS.elem<T>(L + (2 * E) + 1).getAPFloat();
2777 Dst.elem<T>(L + E) = static_cast<T>(Fn(Elem1, Elem2, RM));
2778 }
2779 for (unsigned E = 0; E != HalfElemsPerLane; ++E) {
2780 APFloat Elem1 = RHS.elem<T>(L + (2 * E) + 0).getAPFloat();
2781 APFloat Elem2 = RHS.elem<T>(L + (2 * E) + 1).getAPFloat();
2782 Dst.elem<T>(L + E + HalfElemsPerLane) =
2783 static_cast<T>(Fn(Elem1, Elem2, RM));
2784 }
2785 }
2786 Dst.initializeAllElements();
2787 return true;
2788 }
2789
2790 static bool interp__builtin_ia32_addsub(InterpState &S, CodePtr OpPC,
2791 const CallExpr *Call) {
2792 // Addsub: alternates between subtraction and addition
2793 // Result[i] = (i % 2 == 0) ? (a[i] - b[i]) : (a[i] + b[i])
2794 const Pointer &RHS = S.Stk.pop<Pointer>();
2795 const Pointer &LHS = S.Stk.pop<Pointer>();
2796 const Pointer &Dst = S.Stk.peek<Pointer>();
2797 FPOptions FPO = Call->getFPFeaturesInEffect(S.Ctx.getLangOpts());
2798 llvm::RoundingMode RM = getRoundingMode(FPO);
2799 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2800 unsigned NumElems = VT->getNumElements();
2801
2802 using T = PrimConv<PT_Float>::T;
2803 for (unsigned I = 0; I != NumElems; ++I) {
2804 APFloat LElem = LHS.elem<T>(I).getAPFloat();
2805 APFloat RElem = RHS.elem<T>(I).getAPFloat();
2806 if (I % 2 == 0) {
2807 // Even indices: subtract
2808 LElem.subtract(RElem, RM);
2809 } else {
2810 // Odd indices: add
2811 LElem.add(RElem, RM);
2812 }
2813 Dst.elem<T>(I) = static_cast<T>(LElem);
2814 }
2815 Dst.initializeAllElements();
2816 return true;
2817 }
2818
2819 static bool interp__builtin_ia32_pclmulqdq(InterpState &S, CodePtr OpPC,
2820 const CallExpr *Call) {
2821 // PCLMULQDQ: carry-less multiplication of selected 64-bit halves
2822 // imm8 bit 0: selects lower (0) or upper (1) 64 bits of first operand
2823 // imm8 bit 4: selects lower (0) or upper (1) 64 bits of second operand
2824 assert(Call->getArg(0)->getType()->isVectorType() &&
2825 Call->getArg(1)->getType()->isVectorType());
2826
2827 // Extract imm8 argument
2828 APSInt Imm8 = popToAPSInt(S, Call->getArg(2));
2829 bool SelectUpperA = (Imm8 & 0x01) != 0;
2830 bool SelectUpperB = (Imm8 & 0x10) != 0;
2831
2832 const Pointer &RHS = S.Stk.pop<Pointer>();
2833 const Pointer &LHS = S.Stk.pop<Pointer>();
2834 const Pointer &Dst = S.Stk.peek<Pointer>();
2835
2836 const auto *VT = Call->getArg(0)->getType()->castAs<VectorType>();
2837 PrimType ElemT = *S.getContext().classify(VT->getElementType());
2838 unsigned NumElems = VT->getNumElements();
2839 const auto *DestVT = Call->getType()->castAs<VectorType>();
2840 PrimType DestElemT = *S.getContext().classify(DestVT->getElementType());
2841 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
2842
2843 // Process each 128-bit lane (2 elements at a time)
2844 for (unsigned Lane = 0; Lane < NumElems; Lane += 2) {
2845 APSInt A0, A1, B0, B1;
2846 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
2847 A0 = LHS.elem<T>(Lane + 0).toAPSInt();
2848 A1 = LHS.elem<T>(Lane + 1).toAPSInt();
2849 B0 = RHS.elem<T>(Lane + 0).toAPSInt();
2850 B1 = RHS.elem<T>(Lane + 1).toAPSInt();
2851 });
2852
2853 // Select the appropriate 64-bit values based on imm8
2854 APInt A = SelectUpperA ? A1 : A0;
2855 APInt B = SelectUpperB ? B1 : B0;
2856
2857 // Extend both operands to 128 bits for carry-less multiplication
2858 APInt A128 = A.zext(128);
2859 APInt B128 = B.zext(128);
2860
2861 // Use APIntOps::clmul for carry-less multiplication
2862 APInt Result = llvm::APIntOps::clmul(A128, B128);
2863
2864 // Split the 128-bit result into two 64-bit halves
2865 APSInt ResultLow(Result.extractBits(64, 0), DestUnsigned);
2866 APSInt ResultHigh(Result.extractBits(64, 64), DestUnsigned);
2867
2868 INT_TYPE_SWITCH_NO_BOOL(DestElemT, {
2869 Dst.elem<T>(Lane + 0) = static_cast<T>(ResultLow);
2870 Dst.elem<T>(Lane + 1) = static_cast<T>(ResultHigh);
2871 });
2872 }
2873
2874 Dst.initializeAllElements();
2875 return true;
2876 }
2877
2878 static bool interp__builtin_elementwise_triop_fp(
2879 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2880 llvm::function_ref<APFloat(const APFloat &, const APFloat &,
2881 const APFloat &, llvm::RoundingMode)>
2882 Fn) {
2883 assert(Call->getNumArgs() == 3);
2884
2885 FPOptions FPO = Call->getFPFeaturesInEffect(S.Ctx.getLangOpts());
2886 llvm::RoundingMode RM = getRoundingMode(FPO);
2887 QualType Arg1Type = Call->getArg(0)->getType();
2888 QualType Arg2Type = Call->getArg(1)->getType();
2889 QualType Arg3Type = Call->getArg(2)->getType();
2890
2891 // Non-vector floating point types.
2892 if (!Arg1Type->isVectorType()) {
2893 assert(!Arg2Type->isVectorType());
2894 assert(!Arg3Type->isVectorType());
2895 (void)Arg2Type;
2896 (void)Arg3Type;
2897
2898 const Floating &Z = S.Stk.pop<Floating>();
2899 const Floating &Y = S.Stk.pop<Floating>();
2900 const Floating &X = S.Stk.pop<Floating>();
2901 APFloat F = Fn(X.getAPFloat(), Y.getAPFloat(), Z.getAPFloat(), RM);
2902 Floating Result = S.allocFloat(X.getSemantics());
2903 Result.copy(F);
2904 S.Stk.push<Floating>(Result);
2905 return true;
2906 }
2907
2908 // Vector type.
2909 assert(Arg1Type->isVectorType() && Arg2Type->isVectorType() &&
2910 Arg3Type->isVectorType());
2911
2912 const VectorType *VecTy = Arg1Type->castAs<VectorType>();
2913 QualType ElemQT = VecTy->getElementType();
2914 unsigned NumElems = VecTy->getNumElements();
2915
2916 assert(ElemQT == Arg2Type->castAs<VectorType>()->getElementType() &&
2917 ElemQT == Arg3Type->castAs<VectorType>()->getElementType());
2918 assert(NumElems == Arg2Type->castAs<VectorType>()->getNumElements() &&
2919 NumElems == Arg3Type->castAs<VectorType>()->getNumElements());
2920 assert(ElemQT->isRealFloatingType());
2921 (void)ElemQT;
2922
2923 const Pointer &VZ = S.Stk.pop<Pointer>();
2924 const Pointer &VY = S.Stk.pop<Pointer>();
2925 const Pointer &VX = S.Stk.pop<Pointer>();
2926 const Pointer &Dst = S.Stk.peek<Pointer>();
2927 for (unsigned I = 0; I != NumElems; ++I) {
2928 using T = PrimConv<PT_Float>::T;
2929 APFloat X = VX.elem<T>(I).getAPFloat();
2930 APFloat Y = VY.elem<T>(I).getAPFloat();
2931 APFloat Z = VZ.elem<T>(I).getAPFloat();
2932 APFloat F = Fn(X, Y, Z, RM);
2933 Dst.elem<Floating>(I) = Floating(F);
2934 }
2935 Dst.initializeAllElements();
2936 return true;
2937 }
2938
2939 /// AVX512 predicated move: "Result = Mask[] ? LHS[] : RHS[]".
2940 static bool interp__builtin_select(InterpState &S, CodePtr OpPC,
2941 const CallExpr *Call) {
2942 const Pointer &RHS = S.Stk.pop<Pointer>();
2943 const Pointer &LHS = S.Stk.pop<Pointer>();
2944 APSInt Mask = popToAPSInt(S, Call->getArg(0));
2945 const Pointer &Dst = S.Stk.peek<Pointer>();
2946
2947 assert(LHS.getNumElems() == RHS.getNumElems());
2948 assert(LHS.getNumElems() == Dst.getNumElems());
2949 unsigned NumElems = LHS.getNumElems();
2950 PrimType ElemT = LHS.getFieldDesc()->getPrimType();
2951 PrimType DstElemT = Dst.getFieldDesc()->getPrimType();
2952
2953 for (unsigned I = 0; I != NumElems; ++I) {
2954 if (ElemT == PT_Float) {
2955 assert(DstElemT == PT_Float);
2956 Dst.elem<Floating>(I) =
2957 Mask[I] ? LHS.elem<Floating>(I) : RHS.elem<Floating>(I);
2958 } else {
2959 APSInt Elem;
2960 INT_TYPE_SWITCH(ElemT, {
2961 Elem = Mask[I] ? LHS.elem<T>(I).toAPSInt() : RHS.elem<T>(I).toAPSInt();
2962 });
2963 INT_TYPE_SWITCH_NO_BOOL(DstElemT,
2964 { Dst.elem<T>(I) = static_cast<T>(Elem); });
2965 }
2966 }
2967 Dst.initializeAllElements();
2968
2969 return true;
2970 }
2971
2972 /// Scalar variant of AVX512 predicated select:
2973 /// Result[i] = (Mask bit 0) ? LHS[i] : RHS[i], but only element 0 may change.
2974 /// All other elements are taken from RHS.
2975 static bool interp__builtin_select_scalar(InterpState &S,
2976 const CallExpr *Call) {
2977 unsigned N =
2978 Call->getArg(1)->getType()->castAs<VectorType>()->getNumElements();
2979
2980 const Pointer &W = S.Stk.pop<Pointer>();
2981 const Pointer &A = S.Stk.pop<Pointer>();
2982 APSInt U = popToAPSInt(S, Call->getArg(0));
2983 const Pointer &Dst = S.Stk.peek<Pointer>();
2984
2985 bool TakeA0 = U.getZExtValue() & 1ULL;
2986
2987 for (unsigned I = TakeA0; I != N; ++I)
2988 Dst.elem<Floating>(I) = W.elem<Floating>(I);
2989 if (TakeA0)
2990 Dst.elem<Floating>(0) = A.elem<Floating>(0);
2991
2992 Dst.initializeAllElements();
2993 return true;
2994 }
2995
2996 static bool interp__builtin_ia32_test_op(
2997 InterpState &S, CodePtr OpPC, const CallExpr *Call,
2998 llvm::function_ref<bool(const APInt &A, const APInt &B)> Fn) {
2999 const Pointer &RHS = S.Stk.pop<Pointer>();
3000 const Pointer &LHS = S.Stk.pop<Pointer>();
3001
3002 assert(LHS.getNumElems() == RHS.getNumElems());
3003
3004 unsigned SourceLen = LHS.getNumElems();
3005 QualType ElemQT = getElemType(LHS);
3006 OptPrimType ElemPT = S.getContext().classify(ElemQT);
3007 unsigned LaneWidth = S.getASTContext().getTypeSize(ElemQT);
3008
3009 APInt AWide(LaneWidth * SourceLen, 0);
3010 APInt BWide(LaneWidth * SourceLen, 0);
3011
3012 for (unsigned I = 0; I != SourceLen; ++I) {
3013 APInt ALane;
3014 APInt BLane;
3015
3016 if (ElemQT->isIntegerType()) { // Get value.
3017 INT_TYPE_SWITCH_NO_BOOL(*ElemPT, {
3018 ALane = LHS.elem<T>(I).toAPSInt();
3019 BLane = RHS.elem<T>(I).toAPSInt();
3020 });
3021 } else if (ElemQT->isFloatingType()) { // Get only sign bit.
3022 using T = PrimConv<PT_Float>::T;
3023 ALane = LHS.elem<T>(I).getAPFloat().bitcastToAPInt().isNegative();
3024 BLane = RHS.elem<T>(I).getAPFloat().bitcastToAPInt().isNegative();
3025 } else { // Must be integer or floating type.
3026 return false;
3027 }
3028 AWide.insertBits(ALane, I * LaneWidth);
3029 BWide.insertBits(BLane, I * LaneWidth);
3030 }
3031 pushInteger(S, Fn(AWide, BWide), Call->getType());
3032 return true;
3033 }
3034
3035 static bool interp__builtin_ia32_movmsk_op(InterpState &S, CodePtr OpPC,
3036 const CallExpr *Call) {
3037 assert(Call->getNumArgs() == 1);
3038
3039 const Pointer &Source = S.Stk.pop<Pointer>();
3040
3041 unsigned SourceLen = Source.getNumElems();
3042 QualType ElemQT = getElemType(Source);
3043 OptPrimType ElemT = S.getContext().classify(ElemQT);
3044 unsigned ResultLen =
3045 S.getASTContext().getTypeSize(Call->getType()); // Always 32-bit integer.
3046 APInt Result(ResultLen, 0);
3047
3048 for (unsigned I = 0; I != SourceLen; ++I) {
3049 APInt Elem;
3050 if (ElemQT->isIntegerType()) {
3051 INT_TYPE_SWITCH_NO_BOOL(*ElemT, { Elem = Source.elem<T>(I).toAPSInt(); });
3052 } else if (ElemQT->isRealFloatingType()) {
3053 using T = PrimConv<PT_Float>::T;
3054 Elem = Source.elem<T>(I).getAPFloat().bitcastToAPInt();
3055 } else {
3056 return false;
3057 }
3058 Result.setBitVal(I, Elem.isNegative());
3059 }
3060 pushInteger(S, Result, Call->getType());
3061 return true;
3062 }
3063
3064 static bool interp__builtin_elementwise_triop(
3065 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3066 llvm::function_ref<APInt(const APSInt &, const APSInt &, const APSInt &)>
3067 Fn) {
3068 assert(Call->getNumArgs() == 3);
3069
3070 QualType Arg0Type = Call->getArg(0)->getType();
3071 QualType Arg2Type = Call->getArg(2)->getType();
3072 // Non-vector integer types.
3073 if (!Arg0Type->isVectorType()) {
3074 const APSInt &Op2 = popToAPSInt(S, Arg2Type);
3075 const APSInt &Op1 = popToAPSInt(S, Call->getArg(1));
3076 const APSInt &Op0 = popToAPSInt(S, Arg0Type);
3077 APSInt Result = APSInt(Fn(Op0, Op1, Op2), Op0.isUnsigned());
3078 pushInteger(S, Result, Call->getType());
3079 return true;
3080 }
3081
3082 const auto *VecT = Arg0Type->castAs<VectorType>();
3083 PrimType ElemT = *S.getContext().classify(VecT->getElementType());
3084 unsigned NumElems = VecT->getNumElements();
3085 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3086
3087 // Vector + Vector + Scalar case.
3088 if (!Arg2Type->isVectorType()) {
3089 APSInt Op2 = popToAPSInt(S, Arg2Type);
3090
3091 const Pointer &Op1 = S.Stk.pop<Pointer>();
3092 const Pointer &Op0 = S.Stk.pop<Pointer>();
3093 const Pointer &Dst = S.Stk.peek<Pointer>();
3094 for (unsigned I = 0; I != NumElems; ++I) {
3095 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
3096 Dst.elem<T>(I) = static_cast<T>(APSInt(
3097 Fn(Op0.elem<T>(I).toAPSInt(), Op1.elem<T>(I).toAPSInt(), Op2),
3098 DestUnsigned));
3099 });
3100 }
3101 Dst.initializeAllElements();
3102
3103 return true;
3104 }
3105
3106 // Vector type.
3107 const Pointer &Op2 = S.Stk.pop<Pointer>();
3108 const Pointer &Op1 = S.Stk.pop<Pointer>();
3109 const Pointer &Op0 = S.Stk.pop<Pointer>();
3110 const Pointer &Dst = S.Stk.peek<Pointer>();
3111 for (unsigned I = 0; I != NumElems; ++I) {
3112 APSInt Val0, Val1, Val2;
3113 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
3114 Val0 = Op0.elem<T>(I).toAPSInt();
3115 Val1 = Op1.elem<T>(I).toAPSInt();
3116 Val2 = Op2.elem<T>(I).toAPSInt();
3117 });
3118 APSInt Result = APSInt(Fn(Val0, Val1, Val2), Val0.isUnsigned());
3119 INT_TYPE_SWITCH_NO_BOOL(ElemT,
3120 { Dst.elem<T>(I) = static_cast<T>(Result); });
3121 }
3122 Dst.initializeAllElements();
3123
3124 return true;
3125 }
3126
3127 static bool interp__builtin_x86_extract_vector(InterpState &S, CodePtr OpPC,
3128 const CallExpr *Call,
3129 unsigned ID) {
3130 assert(Call->getNumArgs() == 2);
3131
3132 APSInt ImmAPS = popToAPSInt(S, Call->getArg(1));
3133 uint64_t Index = ImmAPS.getZExtValue();
3134
3135 const Pointer &Src = S.Stk.pop<Pointer>();
3136 if (!Src.getFieldDesc()->isPrimitiveArray())
3137 return false;
3138
3139 const Pointer &Dst = S.Stk.peek<Pointer>();
3140 if (!Dst.getFieldDesc()->isPrimitiveArray())
3141 return false;
3142
3143 unsigned SrcElems = Src.getNumElems();
3144 unsigned DstElems = Dst.getNumElems();
3145
3146 unsigned NumLanes = SrcElems / DstElems;
3147 unsigned Lane = static_cast<unsigned>(Index % NumLanes);
3148 unsigned ExtractPos = Lane * DstElems;
3149
3150 PrimType ElemT = Src.getFieldDesc()->getPrimType();
3151
3152 TYPE_SWITCH(ElemT, {
3153 for (unsigned I = 0; I != DstElems; ++I) {
3154 Dst.elem<T>(I) = Src.elem<T>(ExtractPos + I);
3155 }
3156 });
3157
3158 Dst.initializeAllElements();
3159 return true;
3160 }
3161
3162 static bool interp__builtin_x86_extract_vector_masked(InterpState &S,
3163 CodePtr OpPC,
3164 const CallExpr *Call,
3165 unsigned ID) {
3166 assert(Call->getNumArgs() == 4);
3167
3168 APSInt MaskAPS = popToAPSInt(S, Call->getArg(3));
3169 const Pointer &Merge = S.Stk.pop<Pointer>();
3170 APSInt ImmAPS = popToAPSInt(S, Call->getArg(1));
3171 const Pointer &Src = S.Stk.pop<Pointer>();
3172
3173 if (!Src.getFieldDesc()->isPrimitiveArray() ||
3174 !Merge.getFieldDesc()->isPrimitiveArray())
3175 return false;
3176
3177 const Pointer &Dst = S.Stk.peek<Pointer>();
3178 if (!Dst.getFieldDesc()->isPrimitiveArray())
3179 return false;
3180
3181 unsigned SrcElems = Src.getNumElems();
3182 unsigned DstElems = Dst.getNumElems();
3183
3184 unsigned NumLanes = SrcElems / DstElems;
3185 unsigned Lane = static_cast<unsigned>(ImmAPS.getZExtValue() % NumLanes);
3186 unsigned Base = Lane * DstElems;
3187
3188 PrimType ElemT = Src.getFieldDesc()->getPrimType();
3189
3190 TYPE_SWITCH(ElemT, {
3191 for (unsigned I = 0; I != DstElems; ++I) {
3192 if (MaskAPS[I])
3193 Dst.elem<T>(I) = Src.elem<T>(Base + I);
3194 else
3195 Dst.elem<T>(I) = Merge.elem<T>(I);
3196 }
3197 });
3198
3199 Dst.initializeAllElements();
3200 return true;
3201 }
3202
3203 static bool interp__builtin_x86_insert_subvector(InterpState &S, CodePtr OpPC,
3204 const CallExpr *Call,
3205 unsigned ID) {
3206 assert(Call->getNumArgs() == 3);
3207
3208 APSInt ImmAPS = popToAPSInt(S, Call->getArg(2));
3209 uint64_t Index = ImmAPS.getZExtValue();
3210
3211 const Pointer &SubVec = S.Stk.pop<Pointer>();
3212 if (!SubVec.getFieldDesc()->isPrimitiveArray())
3213 return false;
3214
3215 const Pointer &BaseVec = S.Stk.pop<Pointer>();
3216 if (!BaseVec.getFieldDesc()->isPrimitiveArray())
3217 return false;
3218
3219 const Pointer &Dst = S.Stk.peek<Pointer>();
3220
3221 unsigned BaseElements = BaseVec.getNumElems();
3222 unsigned SubElements = SubVec.getNumElems();
3223
3224 assert(SubElements != 0 && BaseElements != 0 &&
3225 (BaseElements % SubElements) == 0);
3226
3227 unsigned NumLanes = BaseElements / SubElements;
3228 unsigned Lane = static_cast<unsigned>(Index % NumLanes);
3229 unsigned InsertPos = Lane * SubElements;
3230
3231 PrimType ElemT = BaseVec.getFieldDesc()->getPrimType();
3232
3233 TYPE_SWITCH(ElemT, {
3234 for (unsigned I = 0; I != BaseElements; ++I)
3235 Dst.elem<T>(I) = BaseVec.elem<T>(I);
3236 for (unsigned I = 0; I != SubElements; ++I)
3237 Dst.elem<T>(InsertPos + I) = SubVec.elem<T>(I);
3238 });
3239
3240 Dst.initializeAllElements();
3241 return true;
3242 }
3243
3244 static bool interp__builtin_ia32_phminposuw(InterpState &S, CodePtr OpPC,
3245 const CallExpr *Call) {
3246 assert(Call->getNumArgs() == 1);
3247
3248 const Pointer &Source = S.Stk.pop<Pointer>();
3249 const Pointer &Dest = S.Stk.peek<Pointer>();
3250
3251 unsigned SourceLen = Source.getNumElems();
3252 QualType ElemQT = getElemType(Source);
3253 OptPrimType ElemT = S.getContext().classify(ElemQT);
3254 unsigned ElemBitWidth = S.getASTContext().getTypeSize(ElemQT);
3255
3256 bool DestUnsigned = Call->getCallReturnType(S.getASTContext())
3257 ->castAs<VectorType>()
3258 ->getElementType()
3259 ->isUnsignedIntegerOrEnumerationType();
3260
3261 INT_TYPE_SWITCH_NO_BOOL(*ElemT, {
3262 APSInt MinIndex(ElemBitWidth, DestUnsigned);
3263 APSInt MinVal = Source.elem<T>(0).toAPSInt();
3264
3265 for (unsigned I = 1; I != SourceLen; ++I) {
3266 APSInt Val = Source.elem<T>(I).toAPSInt();
3267 if (MinVal.ugt(Val)) {
3268 MinVal = Val;
3269 MinIndex = I;
3270 }
3271 }
3272
3273 Dest.elem<T>(0) = static_cast<T>(MinVal);
3274 Dest.elem<T>(1) = static_cast<T>(MinIndex);
3275 for (unsigned I = 2; I != SourceLen; ++I) {
3276 Dest.elem<T>(I) = static_cast<T>(APSInt(ElemBitWidth, DestUnsigned));
3277 }
3278 });
3279 Dest.initializeAllElements();
3280 return true;
3281 }
3282
3283 static bool interp__builtin_ia32_pternlog(InterpState &S, CodePtr OpPC,
3284 const CallExpr *Call, bool MaskZ) {
3285 assert(Call->getNumArgs() == 5);
3286
3287 APInt U = popToAPSInt(S, Call->getArg(4)); // Lane mask
3288 APInt Imm = popToAPSInt(S, Call->getArg(3)); // Ternary truth table
3289 const Pointer &C = S.Stk.pop<Pointer>();
3290 const Pointer &B = S.Stk.pop<Pointer>();
3291 const Pointer &A = S.Stk.pop<Pointer>();
3292 const Pointer &Dst = S.Stk.peek<Pointer>();
3293
3294 unsigned DstLen = A.getNumElems();
3295 QualType ElemQT = getElemType(A);
3296 OptPrimType ElemT = S.getContext().classify(ElemQT);
3297 unsigned LaneWidth = S.getASTContext().getTypeSize(ElemQT);
3298 bool DstUnsigned = ElemQT->isUnsignedIntegerOrEnumerationType();
3299
3300 INT_TYPE_SWITCH_NO_BOOL(*ElemT, {
3301 for (unsigned I = 0; I != DstLen; ++I) {
3302 APInt ALane = A.elem<T>(I).toAPSInt();
3303 APInt BLane = B.elem<T>(I).toAPSInt();
3304 APInt CLane = C.elem<T>(I).toAPSInt();
3305 APInt RLane(LaneWidth, 0);
3306 if (U[I]) { // If lane not masked, compute ternary logic.
3307 for (unsigned Bit = 0; Bit != LaneWidth; ++Bit) {
3308 unsigned ABit = ALane[Bit];
3309 unsigned BBit = BLane[Bit];
3310 unsigned CBit = CLane[Bit];
3311 unsigned Idx = (ABit << 2) | (BBit << 1) | (CBit);
3312 RLane.setBitVal(Bit, Imm[Idx]);
3313 }
3314 Dst.elem<T>(I) = static_cast<T>(APSInt(RLane, DstUnsigned));
3315 } else if (MaskZ) { // If zero masked, zero the lane.
3316 Dst.elem<T>(I) = static_cast<T>(APSInt(RLane, DstUnsigned));
3317 } else { // Just masked, put in A lane.
3318 Dst.elem<T>(I) = static_cast<T>(APSInt(ALane, DstUnsigned));
3319 }
3320 }
3321 });
3322 Dst.initializeAllElements();
3323 return true;
3324 }
3325
3326 static bool interp__builtin_vec_ext(InterpState &S, CodePtr OpPC,
3327 const CallExpr *Call, unsigned ID) {
3328 assert(Call->getNumArgs() == 2);
3329
3330 APSInt ImmAPS = popToAPSInt(S, Call->getArg(1));
3331 const Pointer &Vec = S.Stk.pop<Pointer>();
3332 if (!Vec.getFieldDesc()->isPrimitiveArray())
3333 return false;
3334
3335 unsigned NumElems = Vec.getNumElems();
3336 unsigned Index =
3337 static_cast<unsigned>(ImmAPS.getZExtValue() & (NumElems - 1));
3338
3339 PrimType ElemT = Vec.getFieldDesc()->getPrimType();
3340 // FIXME(#161685): Replace float+int split with a numeric-only type switch
3341 if (ElemT == PT_Float) {
3342 S.Stk.push<Floating>(Vec.elem<Floating>(Index));
3343 return true;
3344 }
3345 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
3346 APSInt V = Vec.elem<T>(Index).toAPSInt();
3347 pushInteger(S, V, Call->getType());
3348 });
3349
3350 return true;
3351 }
3352
3353 static bool interp__builtin_vec_set(InterpState &S, CodePtr OpPC,
3354 const CallExpr *Call, unsigned ID) {
3355 assert(Call->getNumArgs() == 3);
3356
3357 APSInt ImmAPS = popToAPSInt(S, Call->getArg(2));
3358 APSInt ValAPS = popToAPSInt(S, Call->getArg(1));
3359
3360 const Pointer &Base = S.Stk.pop<Pointer>();
3361 if (!Base.getFieldDesc()->isPrimitiveArray())
3362 return false;
3363
3364 const Pointer &Dst = S.Stk.peek<Pointer>();
3365
3366 unsigned NumElems = Base.getNumElems();
3367 unsigned Index =
3368 static_cast<unsigned>(ImmAPS.getZExtValue() & (NumElems - 1));
3369
3370 PrimType ElemT = Base.getFieldDesc()->getPrimType();
3371 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
3372 for (unsigned I = 0; I != NumElems; ++I)
3373 Dst.elem<T>(I) = Base.elem<T>(I);
3374 Dst.elem<T>(Index) = static_cast<T>(ValAPS);
3375 });
3376
3377 Dst.initializeAllElements();
3378 return true;
3379 }
3380
3381 static bool evalICmpImm(uint8_t Imm, const APSInt &A, const APSInt &B,
3382 bool IsUnsigned) {
3383 switch (Imm & 0x7) {
3384 case 0x00: // _MM_CMPINT_EQ
3385 return (A == B);
3386 case 0x01: // _MM_CMPINT_LT
3387 return IsUnsigned ? A.ult(B) : A.slt(B);
3388 case 0x02: // _MM_CMPINT_LE
3389 return IsUnsigned ? A.ule(B) : A.sle(B);
3390 case 0x03: // _MM_CMPINT_FALSE
3391 return false;
3392 case 0x04: // _MM_CMPINT_NE
3393 return (A != B);
3394 case 0x05: // _MM_CMPINT_NLT
3395 return IsUnsigned ? A.ugt(B) : A.sgt(B);
3396 case 0x06: // _MM_CMPINT_NLE
3397 return IsUnsigned ? A.uge(B) : A.sge(B);
3398 case 0x07: // _MM_CMPINT_TRUE
3399 return true;
3400 default:
3401 llvm_unreachable("Invalid Op");
3402 }
3403 }
3404
3405 static bool interp__builtin_ia32_cmp_mask(InterpState &S, CodePtr OpPC,
3406 const CallExpr *Call, unsigned ID,
3407 bool IsUnsigned) {
3408 assert(Call->getNumArgs() == 4);
3409
3410 APSInt Mask = popToAPSInt(S, Call->getArg(3));
3411 APSInt Opcode = popToAPSInt(S, Call->getArg(2));
3412 unsigned CmpOp = static_cast<unsigned>(Opcode.getZExtValue());
3413 const Pointer &RHS = S.Stk.pop<Pointer>();
3414 const Pointer &LHS = S.Stk.pop<Pointer>();
3415
3416 assert(LHS.getNumElems() == RHS.getNumElems());
3417
3418 APInt RetMask = APInt::getZero(LHS.getNumElems());
3419 unsigned VectorLen = LHS.getNumElems();
3420 PrimType ElemT = LHS.getFieldDesc()->getPrimType();
3421
3422 for (unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
3423 APSInt A, B;
3424 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
3425 A = LHS.elem<T>(ElemNum).toAPSInt();
3426 B = RHS.elem<T>(ElemNum).toAPSInt();
3427 });
3428 RetMask.setBitVal(ElemNum,
3429 Mask[ElemNum] && evalICmpImm(CmpOp, A, B, IsUnsigned));
3430 }
3431 pushInteger(S, RetMask, Call->getType());
3432 return true;
3433 }
3434
3435 static bool interp__builtin_ia32_vpconflict(InterpState &S, CodePtr OpPC,
3436 const CallExpr *Call) {
3437 assert(Call->getNumArgs() == 1);
3438
3439 QualType Arg0Type = Call->getArg(0)->getType();
3440 const auto *VecT = Arg0Type->castAs<VectorType>();
3441 PrimType ElemT = *S.getContext().classify(VecT->getElementType());
3442 unsigned NumElems = VecT->getNumElements();
3443 bool DestUnsigned = Call->getType()->isUnsignedIntegerOrEnumerationType();
3444 const Pointer &Src = S.Stk.pop<Pointer>();
3445 const Pointer &Dst = S.Stk.peek<Pointer>();
3446
3447 for (unsigned I = 0; I != NumElems; ++I) {
3448 INT_TYPE_SWITCH_NO_BOOL(ElemT, {
3449 APSInt ElemI = Src.elem<T>(I).toAPSInt();
3450 APInt ConflictMask(ElemI.getBitWidth(), 0);
3451 for (unsigned J = 0; J != I; ++J) {
3452 APSInt ElemJ = Src.elem<T>(J).toAPSInt();
3453 ConflictMask.setBitVal(J, ElemI == ElemJ);
3454 }
3455 Dst.elem<T>(I) = static_cast<T>(APSInt(ConflictMask, DestUnsigned));
3456 });
3457 }
3458 Dst.initializeAllElements();
3459 return true;
3460 }
3461
3462 static bool interp__builtin_ia32_cvt_vec2mask(InterpState &S, CodePtr OpPC,
3463 const CallExpr *Call,
3464 unsigned ID) {
3465 assert(Call->getNumArgs() == 1);
3466
3467 const Pointer &Vec = S.Stk.pop<Pointer>();
3468 unsigned RetWidth = S.getASTContext().getIntWidth(Call->getType());
3469 APInt RetMask(RetWidth, 0);
3470
3471 unsigned VectorLen = Vec.getNumElems();
3472 PrimType ElemT = Vec.getFieldDesc()->getPrimType();
3473
3474 for (unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
3475 APSInt A;
3476 INT_TYPE_SWITCH_NO_BOOL(ElemT, { A = Vec.elem<T>(ElemNum).toAPSInt(); });
3477 unsigned MSB = A[A.getBitWidth() - 1];
3478 RetMask.setBitVal(ElemNum, MSB);
3479 }
3480 pushInteger(S, RetMask, Call->getType());
3481 return true;
3482 }
3483
3484 static bool interp__builtin_ia32_cvt_mask2vec(InterpState &S, CodePtr OpPC,
3485 const CallExpr *Call,
3486 unsigned ID) {
3487 assert(Call->getNumArgs() == 1);
3488
3489 APSInt Mask = popToAPSInt(S, Call->getArg(0));
3490
3491 const Pointer &Vec = S.Stk.peek<Pointer>();
3492 unsigned NumElems = Vec.getNumElems();
3493 PrimType ElemT = Vec.getFieldDesc()->getPrimType();
3494
3495 for (unsigned I = 0; I != NumElems; ++I) {
3496 bool BitSet = Mask[I];
3497
3498 INT_TYPE_SWITCH_NO_BOOL(
3499 ElemT, { Vec.elem<T>(I) = BitSet ? T::from(-1) : T::from(0); });
3500 }
3501
3502 Vec.initializeAllElements();
3503
3504 return true;
3505 }
3506
3507 static bool interp__builtin_ia32_cvtsd2ss(InterpState &S, CodePtr OpPC,
3508 const CallExpr *Call,
3509 bool HasRoundingMask) {
3510 APSInt Rounding, MaskInt;
3511 Pointer Src, B, A;
3512
3513 if (HasRoundingMask) {
3514 assert(Call->getNumArgs() == 5);
3515 Rounding = popToAPSInt(S, Call->getArg(4));
3516 MaskInt = popToAPSInt(S, Call->getArg(3));
3517 Src = S.Stk.pop<Pointer>();
3518 B = S.Stk.pop<Pointer>();
3519 A = S.Stk.pop<Pointer>();
3520 if (!CheckLoad(S, OpPC, A) || !CheckLoad(S, OpPC, B) ||
3521 !CheckLoad(S, OpPC, Src))
3522 return false;
3523 } else {
3524 assert(Call->getNumArgs() == 2);
3525 B = S.Stk.pop<Pointer>();
3526 A = S.Stk.pop<Pointer>();
3527 if (!CheckLoad(S, OpPC, A) || !CheckLoad(S, OpPC, B))
3528 return false;
3529 }
3530
3531 const auto *DstVTy = Call->getType()->castAs<VectorType>();
3532 unsigned NumElems = DstVTy->getNumElements();
3533 const Pointer &Dst = S.Stk.peek<Pointer>();
3534
3535 // Copy all elements except lane 0 (overwritten below) from A to Dst.
3536 for (unsigned I = 1; I != NumElems; ++I)
3537 Dst.elem<Floating>(I) = A.elem<Floating>(I);
3538
3539 // Convert element 0 from double to float, or use Src if masked off.
3540 if (!HasRoundingMask || (MaskInt.getZExtValue() & 0x1)) {
3541 assert(S.getASTContext().FloatTy == DstVTy->getElementType() &&
3542 "cvtsd2ss requires float element type in destination vector");
3543
3544 Floating Conv = S.allocFloat(
3545 S.getASTContext().getFloatTypeSemantics(DstVTy->getElementType()));
3546 APFloat SrcVal = B.elem<Floating>(0).getAPFloat();
3547 if (!convertDoubleToFloatStrict(SrcVal, Conv, S, Call))
3548 return false;
3549 Dst.elem<Floating>(0) = Conv;
3550 } else {
3551 Dst.elem<Floating>(0) = Src.elem<Floating>(0);
3552 }
3553
3554 Dst.initializeAllElements();
3555 return true;
3556 }
3557
3558 static bool interp__builtin_ia32_cvtpd2ps(InterpState &S, CodePtr OpPC,
3559 const CallExpr *Call, bool IsMasked,
3560 bool HasRounding) {
3561
3562 APSInt MaskVal;
3563 Pointer PassThrough;
3564 Pointer Src;
3565 APSInt Rounding;
3566
3567 if (IsMasked) {
3568 // Pop in reverse order.
3569 if (HasRounding) {
3570 Rounding = popToAPSInt(S, Call->getArg(3));
3571 MaskVal = popToAPSInt(S, Call->getArg(2));
3572 PassThrough = S.Stk.pop<Pointer>();
3573 Src = S.Stk.pop<Pointer>();
3574 } else {
3575 MaskVal = popToAPSInt(S, Call->getArg(2));
3576 PassThrough = S.Stk.pop<Pointer>();
3577 Src = S.Stk.pop<Pointer>();
3578 }
3579
3580 if (!CheckLoad(S, OpPC, PassThrough))
3581 return false;
3582 } else {
3583 // Pop source only.
3584 Src = S.Stk.pop<Pointer>();
3585 }
3586
3587 if (!CheckLoad(S, OpPC, Src))
3588 return false;
3589
3590 const auto *RetVTy = Call->getType()->castAs<VectorType>();
3591 unsigned RetElems = RetVTy->getNumElements();
3592 unsigned SrcElems = Src.getNumElems();
3593 const Pointer &Dst = S.Stk.peek<Pointer>();
3594
3595 // Initialize destination with passthrough or zeros.
3596 for (unsigned I = 0; I != RetElems; ++I)
3597 if (IsMasked)
3598 Dst.elem<Floating>(I) = PassThrough.elem<Floating>(I);
3599 else
3600 Dst.elem<Floating>(I) = Floating(APFloat(0.0f));
3601
3602 assert(S.getASTContext().FloatTy == RetVTy->getElementType() &&
3603 "cvtpd2ps requires float element type in return vector");
3604
3605 // Convert double to float for enabled elements (only process source elements
3606 // that exist).
3607 for (unsigned I = 0; I != SrcElems; ++I) {
3608 if (IsMasked && !MaskVal[I])
3609 continue;
3610
3611 APFloat SrcVal = Src.elem<Floating>(I).getAPFloat();
3612
3613 Floating Conv = S.allocFloat(
3614 S.getASTContext().getFloatTypeSemantics(RetVTy->getElementType()));
3615 if (!convertDoubleToFloatStrict(SrcVal, Conv, S, Call))
3616 return false;
3617 Dst.elem<Floating>(I) = Conv;
3618 }
3619
3620 Dst.initializeAllElements();
3621 return true;
3622 }
3623
3624 static bool interp__builtin_ia32_shuffle_generic(
3625 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3626 llvm::function_ref<std::pair<unsigned, int>(unsigned, unsigned)>
3627 GetSourceIndex) {
3628
3629 assert(Call->getNumArgs() == 2 || Call->getNumArgs() == 3);
3630
3631 unsigned ShuffleMask = 0;
3632 Pointer A, MaskVector, B;
3633 bool IsVectorMask = false;
3634 bool IsSingleOperand = (Call->getNumArgs() == 2);
3635
3636 if (IsSingleOperand) {
3637 QualType MaskType = Call->getArg(1)->getType();
3638 if (MaskType->isVectorType()) {
3639 IsVectorMask = true;
3640 MaskVector = S.Stk.pop<Pointer>();
3641 A = S.Stk.pop<Pointer>();
3642 B = A;
3643 } else if (MaskType->isIntegerType()) {
3644 ShuffleMask = popToAPSInt(S, Call->getArg(1)).getZExtValue();
3645 A = S.Stk.pop<Pointer>();
3646 B = A;
3647 } else {
3648 return false;
3649 }
3650 } else {
3651 QualType Arg2Type = Call->getArg(2)->getType();
3652 if (Arg2Type->isVectorType()) {
3653 IsVectorMask = true;
3654 B = S.Stk.pop<Pointer>();
3655 MaskVector = S.Stk.pop<Pointer>();
3656 A = S.Stk.pop<Pointer>();
3657 } else if (Arg2Type->isIntegerType()) {
3658 ShuffleMask = popToAPSInt(S, Call->getArg(2)).getZExtValue();
3659 B = S.Stk.pop<Pointer>();
3660 A = S.Stk.pop<Pointer>();
3661 } else {
3662 return false;
3663 }
3664 }
3665
3666 QualType Arg0Type = Call->getArg(0)->getType();
3667 const auto *VecT = Arg0Type->castAs<VectorType>();
3668 PrimType ElemT = *S.getContext().classify(VecT->getElementType());
3669 unsigned NumElems = VecT->getNumElements();
3670
3671 const Pointer &Dst = S.Stk.peek<Pointer>();
3672
3673 PrimType MaskElemT = PT_Uint32;
3674 if (IsVectorMask) {
3675 QualType Arg1Type = Call->getArg(1)->getType();
3676 const auto *MaskVecT = Arg1Type->castAs<VectorType>();
3677 QualType MaskElemType = MaskVecT->getElementType();
3678 MaskElemT = *S.getContext().classify(MaskElemType);
3679 }
3680
3681 for (unsigned DstIdx = 0; DstIdx != NumElems; ++DstIdx) {
3682 if (IsVectorMask) {
3683 INT_TYPE_SWITCH(MaskElemT, {
3684 ShuffleMask = static_cast<unsigned>(MaskVector.elem<T>(DstIdx));
3685 });
3686 }
3687
3688 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
3689
3690 if (SrcIdx < 0) {
3691 // Zero out this element
3692 if (ElemT == PT_Float) {
3693 Dst.elem<Floating>(DstIdx) = Floating(
3694 S.getASTContext().getFloatTypeSemantics(VecT->getElementType()));
3695 } else {
3696 INT_TYPE_SWITCH_NO_BOOL(ElemT, { Dst.elem<T>(DstIdx) = T::from(0); });
3697 }
3698 } else {
3699 const Pointer &Src = (SrcVecIdx == 0) ? A : B;
3700 TYPE_SWITCH(ElemT, { Dst.elem<T>(DstIdx) = Src.elem<T>(SrcIdx); });
3701 }
3702 }
3703 Dst.initializeAllElements();
3704
3705 return true;
3706 }
3707
3708 static bool interp__builtin_ia32_shift_with_count(
3709 InterpState &S, CodePtr OpPC, const CallExpr *Call,
3710 llvm::function_ref<APInt(const APInt &, uint64_t)> ShiftOp,
3711 llvm::function_ref<APInt(const APInt &, unsigned)> OverflowOp) {
3712
3713 assert(Call->getNumArgs() == 2);
3714
3715 const Pointer &Count = S.Stk.pop<Pointer>();
3716 const Pointer &Source = S.Stk.pop<Pointer>();
3717
3718 QualType SourceType = Call->getArg(0)->getType();
3719 QualType CountType = Call->getArg(1)->getType();
3720 assert(SourceType->isVectorType() && CountType->isVectorType());
3721
3722 const auto *SourceVecT = SourceType->castAs<VectorType>();
3723 const auto *CountVecT = CountType->castAs<VectorType>();
3724 PrimType SourceElemT = *S.getContext().classify(SourceVecT->getElementType());
3725 PrimType CountElemT = *S.getContext().classify(CountVecT->getElementType());
3726
3727 const Pointer &Dst = S.Stk.peek<Pointer>();
3728
3729 unsigned DestEltWidth =
3730 S.getASTContext().getTypeSize(SourceVecT->getElementType());
3731 bool IsDestUnsigned = SourceVecT->getElementType()->isUnsignedIntegerType();
3732 unsigned DestLen = SourceVecT->getNumElements();
3733 unsigned CountEltWidth =
3734 S.getASTContext().getTypeSize(CountVecT->getElementType());
3735 unsigned NumBitsInQWord = 64;
3736 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
3737
3738 uint64_t CountLQWord = 0;
3739 for (unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
3740 uint64_t Elt = 0;
3741 INT_TYPE_SWITCH(CountElemT,
3742 { Elt = static_cast<uint64_t>(Count.elem<T>(EltIdx)); });
3743 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
3744 }
3745
3746 for (unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
3747 APSInt Elt;
3748 INT_TYPE_SWITCH(SourceElemT, { Elt = Source.elem<T>(EltIdx).toAPSInt(); });
3749
3750 APInt Result;
3751 if (CountLQWord < DestEltWidth) {
3752 Result = ShiftOp(Elt, CountLQWord);
3753 } else {
3754 Result = OverflowOp(Elt, DestEltWidth);
3755 }
3756 if (IsDestUnsigned) {
3757 INT_TYPE_SWITCH(SourceElemT, {
3758 Dst.elem<T>(EltIdx) = T::from(Result.getZExtValue());
3759 });
3760 } else {
3761 INT_TYPE_SWITCH(SourceElemT, {
3762 Dst.elem<T>(EltIdx) = T::from(Result.getSExtValue());
3763 });
3764 }
3765 }
3766
3767 Dst.initializeAllElements();
3768 return true;
3769 }
3770
3771 static bool interp__builtin_ia32_shufbitqmb_mask(InterpState &S, CodePtr OpPC,
3772 const CallExpr *Call) {
3773
3774 assert(Call->getNumArgs() == 3);
3775
3776 QualType SourceType = Call->getArg(0)->getType();
3777 QualType ShuffleMaskType = Call->getArg(1)->getType();
3778 QualType ZeroMaskType = Call->getArg(2)->getType();
3779 if (!SourceType->isVectorType() || !ShuffleMaskType->isVectorType() ||
3780 !ZeroMaskType->isIntegerType()) {
3781 return false;
3782 }
3783
3784 Pointer Source, ShuffleMask;
3785 APSInt ZeroMask = popToAPSInt(S, Call->getArg(2));
3786 ShuffleMask = S.Stk.pop<Pointer>();
3787 Source = S.Stk.pop<Pointer>();
3788
3789 const auto *SourceVecT = SourceType->castAs<VectorType>();
3790 const auto *ShuffleMaskVecT = ShuffleMaskType->castAs<VectorType>();
3791 assert(SourceVecT->getNumElements() == ShuffleMaskVecT->getNumElements());
3792 assert(ZeroMask.getBitWidth() == SourceVecT->getNumElements());
3793
3794 PrimType SourceElemT = *S.getContext().classify(SourceVecT->getElementType());
3795 PrimType ShuffleMaskElemT =
3796 *S.getContext().classify(ShuffleMaskVecT->getElementType());
3797
3798 unsigned NumBytesInQWord = 8;
3799 unsigned NumBitsInByte = 8;
3800 unsigned NumBytes = SourceVecT->getNumElements();
3801 unsigned NumQWords = NumBytes / NumBytesInQWord;
3802 unsigned RetWidth = ZeroMask.getBitWidth();
3803 APSInt RetMask(llvm::APInt(RetWidth, 0), /*isUnsigned=*/true);
3804
3805 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
3806 APInt SourceQWord(64, 0);
3807 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
3808 uint64_t Byte = 0;
3809 INT_TYPE_SWITCH(SourceElemT, {
3810 Byte = static_cast<uint64_t>(
3811 Source.elem<T>(QWordId * NumBytesInQWord + ByteIdx));
3812 });
3813 SourceQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
3814 }
3815
3816 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
3817 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
3818 unsigned M = 0;
3819 INT_TYPE_SWITCH(ShuffleMaskElemT, {
3820 M = static_cast<unsigned>(ShuffleMask.elem<T>(SelIdx)) & 0x3F;
3821 });
3822
3823 if (ZeroMask[SelIdx]) {
3824 RetMask.setBitVal(SelIdx, SourceQWord[M]);
3825 }
3826 }
3827 }
3828
3829 pushInteger(S, RetMask, Call->getType());
3830 return true;
3831 }
3832
3833 static bool interp__builtin_ia32_vcvtps2ph(InterpState &S, CodePtr OpPC,
3834 const CallExpr *Call) {
3835 // Arguments are: vector of floats, rounding immediate
3836 assert(Call->getNumArgs() == 2);
3837
3838 APSInt Imm = popToAPSInt(S, Call->getArg(1));
3839 const Pointer &Src = S.Stk.pop<Pointer>();
3840 const Pointer &Dst = S.Stk.peek<Pointer>();
3841
3842 assert(Src.getFieldDesc()->isPrimitiveArray());
3843 assert(Dst.getFieldDesc()->isPrimitiveArray());
3844
3845 const auto *SrcVTy = Call->getArg(0)->getType()->castAs<VectorType>();
3846 unsigned SrcNumElems = SrcVTy->getNumElements();
3847 const auto *DstVTy = Call->getType()->castAs<VectorType>();
3848 unsigned DstNumElems = DstVTy->getNumElements();
3849
3850 const llvm::fltSemantics &HalfSem =
3851 S.getASTContext().getFloatTypeSemantics(S.getASTContext().HalfTy);
3852
3853 // imm[2] == 1 means use MXCSR rounding mode.
3854 // In that case, we can only evaluate if the conversion is exact.
3855 int ImmVal = Imm.getZExtValue();
3856 bool UseMXCSR = (ImmVal & 4) != 0;
3857 bool IsFPConstrained =
3858 Call->getFPFeaturesInEffect(S.getASTContext().getLangOpts())
3859 .isFPConstrained();
3860
3861 llvm::RoundingMode RM;
3862 if (!UseMXCSR) {
3863 switch (ImmVal & 3) {
3864 case 0:
3865 RM = llvm::RoundingMode::NearestTiesToEven;
3866 break;
3867 case 1:
3868 RM = llvm::RoundingMode::TowardNegative;
3869 break;
3870 case 2:
3871 RM = llvm::RoundingMode::TowardPositive;
3872 break;
3873 case 3:
3874 RM = llvm::RoundingMode::TowardZero;
3875 break;
3876 default:
3877 llvm_unreachable("Invalid immediate rounding mode");
3878 }
3879 } else {
3880 // For MXCSR, we must check for exactness. We can use any rounding mode
3881 // for the trial conversion since the result is the same if it's exact.
3882 RM = llvm::RoundingMode::NearestTiesToEven;
3883 }
3884
3885 QualType DstElemQT = Dst.getFieldDesc()->getElemQualType();
3886 PrimType DstElemT = *S.getContext().classify(DstElemQT);
3887
3888 for (unsigned I = 0; I != SrcNumElems; ++I) {
3889 Floating SrcVal = Src.elem<Floating>(I);
3890 APFloat DstVal = SrcVal.getAPFloat();
3891
3892 bool LostInfo;
3893 APFloat::opStatus St = DstVal.convert(HalfSem, RM, &LostInfo);
3894
3895 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
3896 S.FFDiag(S.Current->getSource(OpPC),
3897 diag::note_constexpr_dynamic_rounding);
3898 return false;
3899 }
3900
3901 INT_TYPE_SWITCH_NO_BOOL(DstElemT, {
3902 // Convert the destination value's bit pattern to an unsigned integer,
3903 // then reconstruct the element using the target type's 'from' method.
3904 uint64_t RawBits = DstVal.bitcastToAPInt().getZExtValue();
3905 Dst.elem<T>(I) = T::from(RawBits);
3906 });
3907 }
3908
3909 // Zero out remaining elements if the destination has more elements
3910 // (e.g., vcvtps2ph converting 4 floats to 8 shorts).
3911 if (DstNumElems > SrcNumElems) {
3912 for (unsigned I = SrcNumElems; I != DstNumElems; ++I) {
3913 INT_TYPE_SWITCH_NO_BOOL(DstElemT, { Dst.elem<T>(I) = T::from(0); });
3914 }
3915 }
3916
3917 Dst.initializeAllElements();
3918 return true;
3919 }
3920
3921 static bool interp__builtin_ia32_multishiftqb(InterpState &S, CodePtr OpPC,
3922 const CallExpr *Call) {
3923 assert(Call->getNumArgs() == 2);
3924
3925 QualType ATy = Call->getArg(0)->getType();
3926 QualType BTy = Call->getArg(1)->getType();
3927 if (!ATy->isVectorType() || !BTy->isVectorType()) {
3928 return false;
3929 }
3930
3931 const Pointer &BPtr = S.Stk.pop<Pointer>();
3932 const Pointer &APtr = S.Stk.pop<Pointer>();
3933 const auto *AVecT = ATy->castAs<VectorType>();
3934 assert(AVecT->getNumElements() ==
3935 BTy->castAs<VectorType>()->getNumElements());
3936
3937 PrimType ElemT = *S.getContext().classify(AVecT->getElementType());
3938
3939 unsigned NumBytesInQWord = 8;
3940 unsigned NumBitsInByte = 8;
3941 unsigned NumBytes = AVecT->getNumElements();
3942 unsigned NumQWords = NumBytes / NumBytesInQWord;
3943 const Pointer &Dst = S.Stk.peek<Pointer>();
3944
3945 for (unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
3946 APInt BQWord(64, 0);
3947 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
3948 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
3949 INT_TYPE_SWITCH(ElemT, {
3950 uint64_t Byte = static_cast<uint64_t>(BPtr.elem<T>(Idx));
3951 BQWord.insertBits(APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
3952 });
3953 }
3954
3955 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
3956 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
3957 uint64_t Ctrl = 0;
3958 INT_TYPE_SWITCH(
3959 ElemT, { Ctrl = static_cast<uint64_t>(APtr.elem<T>(Idx)) & 0x3F; });
3960
3961 APInt Byte(8, 0);
3962 for (unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
3963 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
3964 }
3965 INT_TYPE_SWITCH(ElemT,
3966 { Dst.elem<T>(Idx) = T::from(Byte.getZExtValue()); });
3967 }
3968 }
3969
3970 Dst.initializeAllElements();
3971
3972 return true;
3973 }
3974
3975 static bool interp_builtin_ia32_gfni_affine(InterpState &S, CodePtr OpPC,
3976 const CallExpr *Call,
3977 bool Inverse) {
3978 assert(Call->getNumArgs() == 3);
3979 QualType XType = Call->getArg(0)->getType();
3980 QualType AType = Call->getArg(1)->getType();
3981 QualType ImmType = Call->getArg(2)->getType();
3982 if (!XType->isVectorType() || !AType->isVectorType() ||
3983 !ImmType->isIntegerType()) {
3984 return false;
3985 }
3986
3987 Pointer X, A;
3988 APSInt Imm = popToAPSInt(S, Call->getArg(2));
3989 A = S.Stk.pop<Pointer>();
3990 X = S.Stk.pop<Pointer>();
3991
3992 const Pointer &Dst = S.Stk.peek<Pointer>();
3993 const auto *AVecT = AType->castAs<VectorType>();
3994 assert(XType->castAs<VectorType>()->getNumElements() ==
3995 AVecT->getNumElements());
3996 unsigned NumBytesInQWord = 8;
3997 unsigned NumBytes = AVecT->getNumElements();
3998 unsigned NumBitsInQWord = 64;
3999 unsigned NumQWords = NumBytes / NumBytesInQWord;
4000 unsigned NumBitsInByte = 8;
4001 PrimType AElemT = *S.getContext().classify(AVecT->getElementType());
4002
4003 // computing A*X + Imm
4004 for (unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
4005 // Extract the QWords from X, A
4006 APInt XQWord(NumBitsInQWord, 0);
4007 APInt AQWord(NumBitsInQWord, 0);
4008 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4009 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
4010 uint8_t XByte;
4011 uint8_t AByte;
4012 INT_TYPE_SWITCH(AElemT, {
4013 XByte = static_cast<uint8_t>(X.elem<T>(Idx));
4014 AByte = static_cast<uint8_t>(A.elem<T>(Idx));
4015 });
4016
4017 XQWord.insertBits(APInt(NumBitsInByte, XByte), ByteIdx * NumBitsInByte);
4018 AQWord.insertBits(APInt(NumBitsInByte, AByte), ByteIdx * NumBitsInByte);
4019 }
4020
4021 for (unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
4022 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
4023 uint8_t XByte =
4024 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
4025 INT_TYPE_SWITCH(AElemT, {
4026 Dst.elem<T>(Idx) = T::from(GFNIAffine(XByte, AQWord, Imm, Inverse));
4027 });
4028 }
4029 }
4030 Dst.initializeAllElements();
4031 return true;
4032 }
4033
4034 static bool interp__builtin_ia32_gfni_mul(InterpState &S, CodePtr OpPC,
4035 const CallExpr *Call) {
4036 assert(Call->getNumArgs() == 2);
4037
4038 QualType AType = Call->getArg(0)->getType();
4039 QualType BType = Call->getArg(1)->getType();
4040 if (!AType->isVectorType() || !BType->isVectorType()) {
4041 return false;
4042 }
4043
4044 Pointer A, B;
4045 B = S.Stk.pop<Pointer>();
4046 A = S.Stk.pop<Pointer>();
4047
4048 const Pointer &Dst = S.Stk.peek<Pointer>();
4049 const auto *AVecT = AType->castAs<VectorType>();
4050 assert(AVecT->getNumElements() ==
4051 BType->castAs<VectorType>()->getNumElements());
4052
4053 PrimType AElemT = *S.getContext().classify(AVecT->getElementType());
4054 unsigned NumBytes = A.getNumElems();
4055
4056 for (unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
4057 uint8_t AByte, BByte;
4058 INT_TYPE_SWITCH(AElemT, {
4059 AByte = static_cast<uint8_t>(A.elem<T>(ByteIdx));
4060 BByte = static_cast<uint8_t>(B.elem<T>(ByteIdx));
4061 Dst.elem<T>(ByteIdx) = T::from(GFNIMul(AByte, BByte));
4062 });
4063 }
4064
4065 Dst.initializeAllElements();
4066 return true;
4067 }
4068
4069 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call,
4070 uint32_t BuiltinID) {
4071 if (!S.getASTContext().BuiltinInfo.isConstantEvaluated(BuiltinID))
4072 return Invalid(S, OpPC);
4073
4074 const InterpFrame *Frame = S.Current;
4075 switch (BuiltinID) {
4076 case Builtin::BI__builtin_is_constant_evaluated:
4077 return interp__builtin_is_constant_evaluated(S, OpPC, Frame, Call);
4078
4079 case Builtin::BI__builtin_assume:
4080 case Builtin::BI__assume:
4081 return interp__builtin_assume(S, OpPC, Frame, Call);
4082
4083 case Builtin::BI__builtin_strcmp:
4084 case Builtin::BIstrcmp:
4085 case Builtin::BI__builtin_strncmp:
4086 case Builtin::BIstrncmp:
4087 case Builtin::BI__builtin_wcsncmp:
4088 case Builtin::BIwcsncmp:
4089 case Builtin::BI__builtin_wcscmp:
4090 case Builtin::BIwcscmp:
4091 return interp__builtin_strcmp(S, OpPC, Frame, Call, BuiltinID);
4092
4093 case Builtin::BI__builtin_strlen:
4094 case Builtin::BIstrlen:
4095 case Builtin::BI__builtin_wcslen:
4096 case Builtin::BIwcslen:
4097 return interp__builtin_strlen(S, OpPC, Frame, Call, BuiltinID);
4098
4099 case Builtin::BI__builtin_nan:
4100 case Builtin::BI__builtin_nanf:
4101 case Builtin::BI__builtin_nanl:
4102 case Builtin::BI__builtin_nanf16:
4103 case Builtin::BI__builtin_nanf128:
4104 return interp__builtin_nan(S, OpPC, Frame, Call, /*Signaling=*/false);
4105
4106 case Builtin::BI__builtin_nans:
4107 case Builtin::BI__builtin_nansf:
4108 case Builtin::BI__builtin_nansl:
4109 case Builtin::BI__builtin_nansf16:
4110 case Builtin::BI__builtin_nansf128:
4111 return interp__builtin_nan(S, OpPC, Frame, Call, /*Signaling=*/true);
4112
4113 case Builtin::BI__builtin_huge_val:
4114 case Builtin::BI__builtin_huge_valf:
4115 case Builtin::BI__builtin_huge_vall:
4116 case Builtin::BI__builtin_huge_valf16:
4117 case Builtin::BI__builtin_huge_valf128:
4118 case Builtin::BI__builtin_inf:
4119 case Builtin::BI__builtin_inff:
4120 case Builtin::BI__builtin_infl:
4121 case Builtin::BI__builtin_inff16:
4122 case Builtin::BI__builtin_inff128:
4123 return interp__builtin_inf(S, OpPC, Frame, Call);
4124
4125 case Builtin::BI__builtin_copysign:
4126 case Builtin::BI__builtin_copysignf:
4127 case Builtin::BI__builtin_copysignl:
4128 case Builtin::BI__builtin_copysignf128:
4129 return interp__builtin_copysign(S, OpPC, Frame);
4130
4131 case Builtin::BI__builtin_fmin:
4132 case Builtin::BI__builtin_fminf:
4133 case Builtin::BI__builtin_fminl:
4134 case Builtin::BI__builtin_fminf16:
4135 case Builtin::BI__builtin_fminf128:
4136 return interp__builtin_fmin(S, OpPC, Frame, /*IsNumBuiltin=*/false);
4137
4138 case Builtin::BI__builtin_fminimum_num:
4139 case Builtin::BI__builtin_fminimum_numf:
4140 case Builtin::BI__builtin_fminimum_numl:
4141 case Builtin::BI__builtin_fminimum_numf16:
4142 case Builtin::BI__builtin_fminimum_numf128:
4143 return interp__builtin_fmin(S, OpPC, Frame, /*IsNumBuiltin=*/true);
4144
4145 case Builtin::BI__builtin_fmax:
4146 case Builtin::BI__builtin_fmaxf:
4147 case Builtin::BI__builtin_fmaxl:
4148 case Builtin::BI__builtin_fmaxf16:
4149 case Builtin::BI__builtin_fmaxf128:
4150 return interp__builtin_fmax(S, OpPC, Frame, /*IsNumBuiltin=*/false);
4151
4152 case Builtin::BI__builtin_fmaximum_num:
4153 case Builtin::BI__builtin_fmaximum_numf:
4154 case Builtin::BI__builtin_fmaximum_numl:
4155 case Builtin::BI__builtin_fmaximum_numf16:
4156 case Builtin::BI__builtin_fmaximum_numf128:
4157 return interp__builtin_fmax(S, OpPC, Frame, /*IsNumBuiltin=*/true);
4158
4159 case Builtin::BI__builtin_isnan:
4160 return interp__builtin_isnan(S, OpPC, Frame, Call);
4161
4162 case Builtin::BI__builtin_issignaling:
4163 return interp__builtin_issignaling(S, OpPC, Frame, Call);
4164
4165 case Builtin::BI__builtin_isinf:
4166 return interp__builtin_isinf(S, OpPC, Frame, /*Sign=*/false, Call);
4167
4168 case Builtin::BI__builtin_isinf_sign:
4169 return interp__builtin_isinf(S, OpPC, Frame, /*Sign=*/true, Call);
4170
4171 case Builtin::BI__builtin_isfinite:
4172 return interp__builtin_isfinite(S, OpPC, Frame, Call);
4173
4174 case Builtin::BI__builtin_isnormal:
4175 return interp__builtin_isnormal(S, OpPC, Frame, Call);
4176
4177 case Builtin::BI__builtin_issubnormal:
4178 return interp__builtin_issubnormal(S, OpPC, Frame, Call);
4179
4180 case Builtin::BI__builtin_iszero:
4181 return interp__builtin_iszero(S, OpPC, Frame, Call);
4182
4183 case Builtin::BI__builtin_signbit:
4184 case Builtin::BI__builtin_signbitf:
4185 case Builtin::BI__builtin_signbitl:
4186 return interp__builtin_signbit(S, OpPC, Frame, Call);
4187
4188 case Builtin::BI__builtin_isgreater:
4189 case Builtin::BI__builtin_isgreaterequal:
4190 case Builtin::BI__builtin_isless:
4191 case Builtin::BI__builtin_islessequal:
4192 case Builtin::BI__builtin_islessgreater:
4193 case Builtin::BI__builtin_isunordered:
4194 return interp_floating_comparison(S, OpPC, Call, BuiltinID);
4195
4196 case Builtin::BI__builtin_isfpclass:
4197 return interp__builtin_isfpclass(S, OpPC, Frame, Call);
4198
4199 case Builtin::BI__builtin_fpclassify:
4200 return interp__builtin_fpclassify(S, OpPC, Frame, Call);
4201
4202 case Builtin::BI__builtin_fabs:
4203 case Builtin::BI__builtin_fabsf:
4204 case Builtin::BI__builtin_fabsl:
4205 case Builtin::BI__builtin_fabsf128:
4206 return interp__builtin_fabs(S, OpPC, Frame);
4207
4208 case Builtin::BI__builtin_abs:
4209 case Builtin::BI__builtin_labs:
4210 case Builtin::BI__builtin_llabs:
4211 return interp__builtin_abs(S, OpPC, Frame, Call);
4212
4213 case Builtin::BI__builtin_popcount:
4214 case Builtin::BI__builtin_popcountl:
4215 case Builtin::BI__builtin_popcountll:
4216 case Builtin::BI__builtin_popcountg:
4217 case Builtin::BI__popcnt16: // Microsoft variants of popcount
4218 case Builtin::BI__popcnt:
4219 case Builtin::BI__popcnt64:
4220 return interp__builtin_popcount(S, OpPC, Frame, Call);
4221
4222 case Builtin::BI__builtin_parity:
4223 case Builtin::BI__builtin_parityl:
4224 case Builtin::BI__builtin_parityll:
4225 return interp__builtin_elementwise_int_unaryop(
4226 S, OpPC, Call, [](const APSInt &Val) {
4227 return APInt(Val.getBitWidth(), Val.popcount() % 2);
4228 });
4229 case Builtin::BI__builtin_clrsb:
4230 case Builtin::BI__builtin_clrsbl:
4231 case Builtin::BI__builtin_clrsbll:
4232 return interp__builtin_elementwise_int_unaryop(
4233 S, OpPC, Call, [](const APSInt &Val) {
4234 return APInt(Val.getBitWidth(),
4235 Val.getBitWidth() - Val.getSignificantBits());
4236 });
4237 case Builtin::BI__builtin_bitreverse8:
4238 case Builtin::BI__builtin_bitreverse16:
4239 case Builtin::BI__builtin_bitreverse32:
4240 case Builtin::BI__builtin_bitreverse64:
4241 return interp__builtin_elementwise_int_unaryop(
4242 S, OpPC, Call, [](const APSInt &Val) { return Val.reverseBits(); });
4243
4244 case Builtin::BI__builtin_classify_type:
4245 return interp__builtin_classify_type(S, OpPC, Frame, Call);
4246
4247 case Builtin::BI__builtin_expect:
4248 case Builtin::BI__builtin_expect_with_probability:
4249 return interp__builtin_expect(S, OpPC, Frame, Call);
4250
4251 case Builtin::BI__builtin_rotateleft8:
4252 case Builtin::BI__builtin_rotateleft16:
4253 case Builtin::BI__builtin_rotateleft32:
4254 case Builtin::BI__builtin_rotateleft64:
4255 case Builtin::BI_rotl8: // Microsoft variants of rotate left
4256 case Builtin::BI_rotl16:
4257 case Builtin::BI_rotl:
4258 case Builtin::BI_lrotl:
4259 case Builtin::BI_rotl64:
4260 return interp__builtin_elementwise_int_binop(
4261 S, OpPC, Call, [](const APSInt &Value, const APSInt &Amount) {
4262 return Value.rotl(Amount);
4263 });
4264
4265 case Builtin::BI__builtin_rotateright8:
4266 case Builtin::BI__builtin_rotateright16:
4267 case Builtin::BI__builtin_rotateright32:
4268 case Builtin::BI__builtin_rotateright64:
4269 case Builtin::BI_rotr8: // Microsoft variants of rotate right
4270 case Builtin::BI_rotr16:
4271 case Builtin::BI_rotr:
4272 case Builtin::BI_lrotr:
4273 case Builtin::BI_rotr64:
4274 return interp__builtin_elementwise_int_binop(
4275 S, OpPC, Call, [](const APSInt &Value, const APSInt &Amount) {
4276 return Value.rotr(Amount);
4277 });
4278
4279 case Builtin::BI__builtin_ffs:
4280 case Builtin::BI__builtin_ffsl:
4281 case Builtin::BI__builtin_ffsll:
4282 return interp__builtin_elementwise_int_unaryop(
4283 S, OpPC, Call, [](const APSInt &Val) {
4284 return APInt(Val.getBitWidth(),
4285 Val.isZero() ? 0u : Val.countTrailingZeros() + 1u);
4286 });
4287
4288 case Builtin::BIaddressof:
4289 case Builtin::BI__addressof:
4290 case Builtin::BI__builtin_addressof:
4291 assert(isNoopBuiltin(BuiltinID));
4292 return interp__builtin_addressof(S, OpPC, Frame, Call);
4293
4294 case Builtin::BIas_const:
4295 case Builtin::BIforward:
4296 case Builtin::BIforward_like:
4297 case Builtin::BImove:
4298 case Builtin::BImove_if_noexcept:
4299 assert(isNoopBuiltin(BuiltinID));
4300 return interp__builtin_move(S, OpPC, Frame, Call);
4301
4302 case Builtin::BI__builtin_eh_return_data_regno:
4303 return interp__builtin_eh_return_data_regno(S, OpPC, Frame, Call);
4304
4305 case Builtin::BI__builtin_launder:
4306 assert(isNoopBuiltin(BuiltinID));
4307 return true;
4308
4309 case Builtin::BI__builtin_add_overflow:
4310 case Builtin::BI__builtin_sub_overflow:
4311 case Builtin::BI__builtin_mul_overflow:
4312 case Builtin::BI__builtin_sadd_overflow:
4313 case Builtin::BI__builtin_uadd_overflow:
4314 case Builtin::BI__builtin_uaddl_overflow:
4315 case Builtin::BI__builtin_uaddll_overflow:
4316 case Builtin::BI__builtin_usub_overflow:
4317 case Builtin::BI__builtin_usubl_overflow:
4318 case Builtin::BI__builtin_usubll_overflow:
4319 case Builtin::BI__builtin_umul_overflow:
4320 case Builtin::BI__builtin_umull_overflow:
4321 case Builtin::BI__builtin_umulll_overflow:
4322 case Builtin::BI__builtin_saddl_overflow:
4323 case Builtin::BI__builtin_saddll_overflow:
4324 case Builtin::BI__builtin_ssub_overflow:
4325 case Builtin::BI__builtin_ssubl_overflow:
4326 case Builtin::BI__builtin_ssubll_overflow:
4327 case Builtin::BI__builtin_smul_overflow:
4328 case Builtin::BI__builtin_smull_overflow:
4329 case Builtin::BI__builtin_smulll_overflow:
4330 return interp__builtin_overflowop(S, OpPC, Call, BuiltinID);
4331
4332 case Builtin::BI__builtin_addcb:
4333 case Builtin::BI__builtin_addcs:
4334 case Builtin::BI__builtin_addc:
4335 case Builtin::BI__builtin_addcl:
4336 case Builtin::BI__builtin_addcll:
4337 case Builtin::BI__builtin_subcb:
4338 case Builtin::BI__builtin_subcs:
4339 case Builtin::BI__builtin_subc:
4340 case Builtin::BI__builtin_subcl:
4341 case Builtin::BI__builtin_subcll:
4342 return interp__builtin_carryop(S, OpPC, Frame, Call, BuiltinID);
4343
4344 case Builtin::BI__builtin_clz:
4345 case Builtin::BI__builtin_clzl:
4346 case Builtin::BI__builtin_clzll:
4347 case Builtin::BI__builtin_clzs:
4348 case Builtin::BI__builtin_clzg:
4349 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
4350 case Builtin::BI__lzcnt:
4351 case Builtin::BI__lzcnt64:
4352 return interp__builtin_clz(S, OpPC, Frame, Call, BuiltinID);
4353
4354 case Builtin::BI__builtin_ctz:
4355 case Builtin::BI__builtin_ctzl:
4356 case Builtin::BI__builtin_ctzll:
4357 case Builtin::BI__builtin_ctzs:
4358 case Builtin::BI__builtin_ctzg:
4359 return interp__builtin_ctz(S, OpPC, Frame, Call, BuiltinID);
4360
4361 case Builtin::BI__builtin_elementwise_clzg:
4362 case Builtin::BI__builtin_elementwise_ctzg:
4363 return interp__builtin_elementwise_countzeroes(S, OpPC, Frame, Call,
4364 BuiltinID);
4365 case Builtin::BI__builtin_bswapg:
4366 case Builtin::BI__builtin_bswap16:
4367 case Builtin::BI__builtin_bswap32:
4368 case Builtin::BI__builtin_bswap64:
4369 return interp__builtin_bswap(S, OpPC, Frame, Call);
4370
4371 case Builtin::BI__atomic_always_lock_free:
4372 case Builtin::BI__atomic_is_lock_free:
4373 return interp__builtin_atomic_lock_free(S, OpPC, Frame, Call, BuiltinID);
4374
4375 case Builtin::BI__c11_atomic_is_lock_free:
4376 return interp__builtin_c11_atomic_is_lock_free(S, OpPC, Frame, Call);
4377
4378 case Builtin::BI__builtin_complex:
4379 return interp__builtin_complex(S, OpPC, Frame, Call);
4380
4381 case Builtin::BI__builtin_is_aligned:
4382 case Builtin::BI__builtin_align_up:
4383 case Builtin::BI__builtin_align_down:
4384 return interp__builtin_is_aligned_up_down(S, OpPC, Frame, Call, BuiltinID);
4385
4386 case Builtin::BI__builtin_assume_aligned:
4387 return interp__builtin_assume_aligned(S, OpPC, Frame, Call);
4388
4389 case clang::X86::BI__builtin_ia32_bextr_u32:
4390 case clang::X86::BI__builtin_ia32_bextr_u64:
4391 case clang::X86::BI__builtin_ia32_bextri_u32:
4392 case clang::X86::BI__builtin_ia32_bextri_u64:
4393 return interp__builtin_elementwise_int_binop(
4394 S, OpPC, Call, [](const APSInt &Val, const APSInt &Idx) {
4395 unsigned BitWidth = Val.getBitWidth();
4396 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
4397 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
4398 if (Length > BitWidth) {
4399 Length = BitWidth;
4400 }
4401
4402 // Handle out of bounds cases.
4403 if (Length == 0 || Shift >= BitWidth)
4404 return APInt(BitWidth, 0);
4405
4406 uint64_t Result = Val.getZExtValue() >> Shift;
4407 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
4408 return APInt(BitWidth, Result);
4409 });
4410
4411 case clang::X86::BI__builtin_ia32_bzhi_si:
4412 case clang::X86::BI__builtin_ia32_bzhi_di:
4413 return interp__builtin_elementwise_int_binop(
4414 S, OpPC, Call, [](const APSInt &Val, const APSInt &Idx) {
4415 unsigned BitWidth = Val.getBitWidth();
4416 uint64_t Index = Idx.extractBitsAsZExtValue(8, 0);
4417 APSInt Result = Val;
4418
4419 if (Index < BitWidth)
4420 Result.clearHighBits(BitWidth - Index);
4421
4422 return Result;
4423 });
4424
4425 case clang::X86::BI__builtin_ia32_ktestcqi:
4426 case clang::X86::BI__builtin_ia32_ktestchi:
4427 case clang::X86::BI__builtin_ia32_ktestcsi:
4428 case clang::X86::BI__builtin_ia32_ktestcdi:
4429 return interp__builtin_elementwise_int_binop(
4430 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
4431 return APInt(sizeof(unsigned char) * 8, (~A & B) == 0);
4432 });
4433
4434 case clang::X86::BI__builtin_ia32_ktestzqi:
4435 case clang::X86::BI__builtin_ia32_ktestzhi:
4436 case clang::X86::BI__builtin_ia32_ktestzsi:
4437 case clang::X86::BI__builtin_ia32_ktestzdi:
4438 return interp__builtin_elementwise_int_binop(
4439 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
4440 return APInt(sizeof(unsigned char) * 8, (A & B) == 0);
4441 });
4442
4443 case clang::X86::BI__builtin_ia32_kortestcqi:
4444 case clang::X86::BI__builtin_ia32_kortestchi:
4445 case clang::X86::BI__builtin_ia32_kortestcsi:
4446 case clang::X86::BI__builtin_ia32_kortestcdi:
4447 return interp__builtin_elementwise_int_binop(
4448 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
4449 return APInt(sizeof(unsigned char) * 8, ~(A | B) == 0);
4450 });
4451
4452 case clang::X86::BI__builtin_ia32_kortestzqi:
4453 case clang::X86::BI__builtin_ia32_kortestzhi:
4454 case clang::X86::BI__builtin_ia32_kortestzsi:
4455 case clang::X86::BI__builtin_ia32_kortestzdi:
4456 return interp__builtin_elementwise_int_binop(
4457 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
4458 return APInt(sizeof(unsigned char) * 8, (A | B) == 0);
4459 });
4460
4461 case clang::X86::BI__builtin_ia32_kshiftliqi:
4462 case clang::X86::BI__builtin_ia32_kshiftlihi:
4463 case clang::X86::BI__builtin_ia32_kshiftlisi:
4464 case clang::X86::BI__builtin_ia32_kshiftlidi:
4465 return interp__builtin_elementwise_int_binop(
4466 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4467 unsigned Amt = RHS.getZExtValue() & 0xFF;
4468 if (Amt >= LHS.getBitWidth())
4469 return APInt::getZero(LHS.getBitWidth());
4470 return LHS.shl(Amt);
4471 });
4472
4473 case clang::X86::BI__builtin_ia32_kshiftriqi:
4474 case clang::X86::BI__builtin_ia32_kshiftrihi:
4475 case clang::X86::BI__builtin_ia32_kshiftrisi:
4476 case clang::X86::BI__builtin_ia32_kshiftridi:
4477 return interp__builtin_elementwise_int_binop(
4478 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4479 unsigned Amt = RHS.getZExtValue() & 0xFF;
4480 if (Amt >= LHS.getBitWidth())
4481 return APInt::getZero(LHS.getBitWidth());
4482 return LHS.lshr(Amt);
4483 });
4484
4485 case clang::X86::BI__builtin_ia32_lzcnt_u16:
4486 case clang::X86::BI__builtin_ia32_lzcnt_u32:
4487 case clang::X86::BI__builtin_ia32_lzcnt_u64:
4488 return interp__builtin_elementwise_int_unaryop(
4489 S, OpPC, Call, [](const APSInt &Src) {
4490 return APInt(Src.getBitWidth(), Src.countLeadingZeros());
4491 });
4492
4493 case clang::X86::BI__builtin_ia32_tzcnt_u16:
4494 case clang::X86::BI__builtin_ia32_tzcnt_u32:
4495 case clang::X86::BI__builtin_ia32_tzcnt_u64:
4496 return interp__builtin_elementwise_int_unaryop(
4497 S, OpPC, Call, [](const APSInt &Src) {
4498 return APInt(Src.getBitWidth(), Src.countTrailingZeros());
4499 });
4500
4501 case clang::X86::BI__builtin_ia32_pdep_si:
4502 case clang::X86::BI__builtin_ia32_pdep_di:
4503 return interp__builtin_elementwise_int_binop(
4504 S, OpPC, Call, [](const APSInt &Val, const APSInt &Mask) {
4505 unsigned BitWidth = Val.getBitWidth();
4506 APInt Result = APInt::getZero(BitWidth);
4507
4508 for (unsigned I = 0, P = 0; I != BitWidth; ++I) {
4509 if (Mask[I])
4510 Result.setBitVal(I, Val[P++]);
4511 }
4512
4513 return Result;
4514 });
4515
4516 case clang::X86::BI__builtin_ia32_pext_si:
4517 case clang::X86::BI__builtin_ia32_pext_di:
4518 return interp__builtin_elementwise_int_binop(
4519 S, OpPC, Call, [](const APSInt &Val, const APSInt &Mask) {
4520 unsigned BitWidth = Val.getBitWidth();
4521 APInt Result = APInt::getZero(BitWidth);
4522
4523 for (unsigned I = 0, P = 0; I != BitWidth; ++I) {
4524 if (Mask[I])
4525 Result.setBitVal(P++, Val[I]);
4526 }
4527
4528 return Result;
4529 });
4530
4531 case clang::X86::BI__builtin_ia32_addcarryx_u32:
4532 case clang::X86::BI__builtin_ia32_addcarryx_u64:
4533 case clang::X86::BI__builtin_ia32_subborrow_u32:
4534 case clang::X86::BI__builtin_ia32_subborrow_u64:
4535 return interp__builtin_ia32_addcarry_subborrow(S, OpPC, Frame, Call,
4536 BuiltinID);
4537
4538 case Builtin::BI__builtin_os_log_format_buffer_size:
4539 return interp__builtin_os_log_format_buffer_size(S, OpPC, Frame, Call);
4540
4541 case Builtin::BI__builtin_ptrauth_string_discriminator:
4542 return interp__builtin_ptrauth_string_discriminator(S, OpPC, Frame, Call);
4543
4544 case Builtin::BI__builtin_infer_alloc_token:
4545 return interp__builtin_infer_alloc_token(S, OpPC, Frame, Call);
4546
4547 case Builtin::BI__noop:
4548 pushInteger(S, 0, Call->getType());
4549 return true;
4550
4551 case Builtin::BI__builtin_operator_new:
4552 return interp__builtin_operator_new(S, OpPC, Frame, Call);
4553
4554 case Builtin::BI__builtin_operator_delete:
4555 return interp__builtin_operator_delete(S, OpPC, Frame, Call);
4556
4557 case Builtin::BI__arithmetic_fence:
4558 return interp__builtin_arithmetic_fence(S, OpPC, Frame, Call);
4559
4560 case Builtin::BI__builtin_reduce_add:
4561 case Builtin::BI__builtin_reduce_mul:
4562 case Builtin::BI__builtin_reduce_and:
4563 case Builtin::BI__builtin_reduce_or:
4564 case Builtin::BI__builtin_reduce_xor:
4565 case Builtin::BI__builtin_reduce_min:
4566 case Builtin::BI__builtin_reduce_max:
4567 return interp__builtin_vector_reduce(S, OpPC, Call, BuiltinID);
4568
4569 case Builtin::BI__builtin_elementwise_popcount:
4570 return interp__builtin_elementwise_int_unaryop(
4571 S, OpPC, Call, [](const APSInt &Src) {
4572 return APInt(Src.getBitWidth(), Src.popcount());
4573 });
4574 case Builtin::BI__builtin_elementwise_bitreverse:
4575 return interp__builtin_elementwise_int_unaryop(
4576 S, OpPC, Call, [](const APSInt &Src) { return Src.reverseBits(); });
4577
4578 case Builtin::BI__builtin_elementwise_abs:
4579 return interp__builtin_elementwise_abs(S, OpPC, Frame, Call, BuiltinID);
4580
4581 case Builtin::BI__builtin_memcpy:
4582 case Builtin::BImemcpy:
4583 case Builtin::BI__builtin_wmemcpy:
4584 case Builtin::BIwmemcpy:
4585 case Builtin::BI__builtin_memmove:
4586 case Builtin::BImemmove:
4587 case Builtin::BI__builtin_wmemmove:
4588 case Builtin::BIwmemmove:
4589 return interp__builtin_memcpy(S, OpPC, Frame, Call, BuiltinID);
4590
4591 case Builtin::BI__builtin_memcmp:
4592 case Builtin::BImemcmp:
4593 case Builtin::BI__builtin_bcmp:
4594 case Builtin::BIbcmp:
4595 case Builtin::BI__builtin_wmemcmp:
4596 case Builtin::BIwmemcmp:
4597 return interp__builtin_memcmp(S, OpPC, Frame, Call, BuiltinID);
4598
4599 case Builtin::BImemchr:
4600 case Builtin::BI__builtin_memchr:
4601 case Builtin::BIstrchr:
4602 case Builtin::BI__builtin_strchr:
4603 case Builtin::BIwmemchr:
4604 case Builtin::BI__builtin_wmemchr:
4605 case Builtin::BIwcschr:
4606 case Builtin::BI__builtin_wcschr:
4607 case Builtin::BI__builtin_char_memchr:
4608 return interp__builtin_memchr(S, OpPC, Call, BuiltinID);
4609
4610 case Builtin::BI__builtin_object_size:
4611 case Builtin::BI__builtin_dynamic_object_size:
4612 return interp__builtin_object_size(S, OpPC, Frame, Call);
4613
4614 case Builtin::BI__builtin_is_within_lifetime:
4615 return interp__builtin_is_within_lifetime(S, OpPC, Call);
4616
4617 case Builtin::BI__builtin_elementwise_add_sat:
4618 return interp__builtin_elementwise_int_binop(
4619 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4620 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
4621 });
4622
4623 case Builtin::BI__builtin_elementwise_sub_sat:
4624 return interp__builtin_elementwise_int_binop(
4625 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4626 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
4627 });
4628 case X86::BI__builtin_ia32_extract128i256:
4629 case X86::BI__builtin_ia32_vextractf128_pd256:
4630 case X86::BI__builtin_ia32_vextractf128_ps256:
4631 case X86::BI__builtin_ia32_vextractf128_si256:
4632 return interp__builtin_x86_extract_vector(S, OpPC, Call, BuiltinID);
4633
4634 case X86::BI__builtin_ia32_extractf32x4_256_mask:
4635 case X86::BI__builtin_ia32_extractf32x4_mask:
4636 case X86::BI__builtin_ia32_extractf32x8_mask:
4637 case X86::BI__builtin_ia32_extractf64x2_256_mask:
4638 case X86::BI__builtin_ia32_extractf64x2_512_mask:
4639 case X86::BI__builtin_ia32_extractf64x4_mask:
4640 case X86::BI__builtin_ia32_extracti32x4_256_mask:
4641 case X86::BI__builtin_ia32_extracti32x4_mask:
4642 case X86::BI__builtin_ia32_extracti32x8_mask:
4643 case X86::BI__builtin_ia32_extracti64x2_256_mask:
4644 case X86::BI__builtin_ia32_extracti64x2_512_mask:
4645 case X86::BI__builtin_ia32_extracti64x4_mask:
4646 return interp__builtin_x86_extract_vector_masked(S, OpPC, Call, BuiltinID);
4647
4648 case clang::X86::BI__builtin_ia32_pmulhrsw128:
4649 case clang::X86::BI__builtin_ia32_pmulhrsw256:
4650 case clang::X86::BI__builtin_ia32_pmulhrsw512:
4651 return interp__builtin_elementwise_int_binop(
4652 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4653 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
4654 .extractBits(16, 1);
4655 });
4656
4657 case clang::X86::BI__builtin_ia32_movmskps:
4658 case clang::X86::BI__builtin_ia32_movmskpd:
4659 case clang::X86::BI__builtin_ia32_pmovmskb128:
4660 case clang::X86::BI__builtin_ia32_pmovmskb256:
4661 case clang::X86::BI__builtin_ia32_movmskps256:
4662 case clang::X86::BI__builtin_ia32_movmskpd256: {
4663 return interp__builtin_ia32_movmsk_op(S, OpPC, Call);
4664 }
4665
4666 case X86::BI__builtin_ia32_psignb128:
4667 case X86::BI__builtin_ia32_psignb256:
4668 case X86::BI__builtin_ia32_psignw128:
4669 case X86::BI__builtin_ia32_psignw256:
4670 case X86::BI__builtin_ia32_psignd128:
4671 case X86::BI__builtin_ia32_psignd256:
4672 return interp__builtin_elementwise_int_binop(
4673 S, OpPC, Call, [](const APInt &AElem, const APInt &BElem) {
4674 if (BElem.isZero())
4675 return APInt::getZero(AElem.getBitWidth());
4676 if (BElem.isNegative())
4677 return -AElem;
4678 return AElem;
4679 });
4680
4681 case clang::X86::BI__builtin_ia32_pavgb128:
4682 case clang::X86::BI__builtin_ia32_pavgw128:
4683 case clang::X86::BI__builtin_ia32_pavgb256:
4684 case clang::X86::BI__builtin_ia32_pavgw256:
4685 case clang::X86::BI__builtin_ia32_pavgb512:
4686 case clang::X86::BI__builtin_ia32_pavgw512:
4687 return interp__builtin_elementwise_int_binop(S, OpPC, Call,
4688 llvm::APIntOps::avgCeilU);
4689
4690 case clang::X86::BI__builtin_ia32_pmaddubsw128:
4691 case clang::X86::BI__builtin_ia32_pmaddubsw256:
4692 case clang::X86::BI__builtin_ia32_pmaddubsw512:
4693 return interp__builtin_ia32_pmul(
4694 S, OpPC, Call,
4695 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
4696 const APSInt &HiRHS) {
4697 unsigned BitWidth = 2 * LoLHS.getBitWidth();
4698 return (LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
4699 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth)));
4700 });
4701
4702 case clang::X86::BI__builtin_ia32_pmaddwd128:
4703 case clang::X86::BI__builtin_ia32_pmaddwd256:
4704 case clang::X86::BI__builtin_ia32_pmaddwd512:
4705 return interp__builtin_ia32_pmul(
4706 S, OpPC, Call,
4707 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
4708 const APSInt &HiRHS) {
4709 unsigned BitWidth = 2 * LoLHS.getBitWidth();
4710 return (LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
4711 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth));
4712 });
4713
4714 case clang::X86::BI__builtin_ia32_pmulhuw128:
4715 case clang::X86::BI__builtin_ia32_pmulhuw256:
4716 case clang::X86::BI__builtin_ia32_pmulhuw512:
4717 return interp__builtin_elementwise_int_binop(S, OpPC, Call,
4718 llvm::APIntOps::mulhu);
4719
4720 case clang::X86::BI__builtin_ia32_pmulhw128:
4721 case clang::X86::BI__builtin_ia32_pmulhw256:
4722 case clang::X86::BI__builtin_ia32_pmulhw512:
4723 return interp__builtin_elementwise_int_binop(S, OpPC, Call,
4724 llvm::APIntOps::mulhs);
4725
4726 case clang::X86::BI__builtin_ia32_psllv2di:
4727 case clang::X86::BI__builtin_ia32_psllv4di:
4728 case clang::X86::BI__builtin_ia32_psllv4si:
4729 case clang::X86::BI__builtin_ia32_psllv8di:
4730 case clang::X86::BI__builtin_ia32_psllv8hi:
4731 case clang::X86::BI__builtin_ia32_psllv8si:
4732 case clang::X86::BI__builtin_ia32_psllv16hi:
4733 case clang::X86::BI__builtin_ia32_psllv16si:
4734 case clang::X86::BI__builtin_ia32_psllv32hi:
4735 case clang::X86::BI__builtin_ia32_psllwi128:
4736 case clang::X86::BI__builtin_ia32_psllwi256:
4737 case clang::X86::BI__builtin_ia32_psllwi512:
4738 case clang::X86::BI__builtin_ia32_pslldi128:
4739 case clang::X86::BI__builtin_ia32_pslldi256:
4740 case clang::X86::BI__builtin_ia32_pslldi512:
4741 case clang::X86::BI__builtin_ia32_psllqi128:
4742 case clang::X86::BI__builtin_ia32_psllqi256:
4743 case clang::X86::BI__builtin_ia32_psllqi512:
4744 return interp__builtin_elementwise_int_binop(
4745 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4746 if (RHS.uge(LHS.getBitWidth())) {
4747 return APInt::getZero(LHS.getBitWidth());
4748 }
4749 return LHS.shl(RHS.getZExtValue());
4750 });
4751
4752 case clang::X86::BI__builtin_ia32_psrav4si:
4753 case clang::X86::BI__builtin_ia32_psrav8di:
4754 case clang::X86::BI__builtin_ia32_psrav8hi:
4755 case clang::X86::BI__builtin_ia32_psrav8si:
4756 case clang::X86::BI__builtin_ia32_psrav16hi:
4757 case clang::X86::BI__builtin_ia32_psrav16si:
4758 case clang::X86::BI__builtin_ia32_psrav32hi:
4759 case clang::X86::BI__builtin_ia32_psravq128:
4760 case clang::X86::BI__builtin_ia32_psravq256:
4761 case clang::X86::BI__builtin_ia32_psrawi128:
4762 case clang::X86::BI__builtin_ia32_psrawi256:
4763 case clang::X86::BI__builtin_ia32_psrawi512:
4764 case clang::X86::BI__builtin_ia32_psradi128:
4765 case clang::X86::BI__builtin_ia32_psradi256:
4766 case clang::X86::BI__builtin_ia32_psradi512:
4767 case clang::X86::BI__builtin_ia32_psraqi128:
4768 case clang::X86::BI__builtin_ia32_psraqi256:
4769 case clang::X86::BI__builtin_ia32_psraqi512:
4770 return interp__builtin_elementwise_int_binop(
4771 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4772 if (RHS.uge(LHS.getBitWidth())) {
4773 return LHS.ashr(LHS.getBitWidth() - 1);
4774 }
4775 return LHS.ashr(RHS.getZExtValue());
4776 });
4777
4778 case clang::X86::BI__builtin_ia32_psrlv2di:
4779 case clang::X86::BI__builtin_ia32_psrlv4di:
4780 case clang::X86::BI__builtin_ia32_psrlv4si:
4781 case clang::X86::BI__builtin_ia32_psrlv8di:
4782 case clang::X86::BI__builtin_ia32_psrlv8hi:
4783 case clang::X86::BI__builtin_ia32_psrlv8si:
4784 case clang::X86::BI__builtin_ia32_psrlv16hi:
4785 case clang::X86::BI__builtin_ia32_psrlv16si:
4786 case clang::X86::BI__builtin_ia32_psrlv32hi:
4787 case clang::X86::BI__builtin_ia32_psrlwi128:
4788 case clang::X86::BI__builtin_ia32_psrlwi256:
4789 case clang::X86::BI__builtin_ia32_psrlwi512:
4790 case clang::X86::BI__builtin_ia32_psrldi128:
4791 case clang::X86::BI__builtin_ia32_psrldi256:
4792 case clang::X86::BI__builtin_ia32_psrldi512:
4793 case clang::X86::BI__builtin_ia32_psrlqi128:
4794 case clang::X86::BI__builtin_ia32_psrlqi256:
4795 case clang::X86::BI__builtin_ia32_psrlqi512:
4796 return interp__builtin_elementwise_int_binop(
4797 S, OpPC, Call, [](const APSInt &LHS, const APSInt &RHS) {
4798 if (RHS.uge(LHS.getBitWidth())) {
4799 return APInt::getZero(LHS.getBitWidth());
4800 }
4801 return LHS.lshr(RHS.getZExtValue());
4802 });
4803 case clang::X86::BI__builtin_ia32_packsswb128:
4804 case clang::X86::BI__builtin_ia32_packsswb256:
4805 case clang::X86::BI__builtin_ia32_packsswb512:
4806 case clang::X86::BI__builtin_ia32_packssdw128:
4807 case clang::X86::BI__builtin_ia32_packssdw256:
4808 case clang::X86::BI__builtin_ia32_packssdw512:
4809 return interp__builtin_x86_pack(S, OpPC, Call, [](const APSInt &Src) {
4810 return APInt(Src).truncSSat(Src.getBitWidth() / 2);
4811 });
4812 case clang::X86::BI__builtin_ia32_packusdw128:
4813 case clang::X86::BI__builtin_ia32_packusdw256:
4814 case clang::X86::BI__builtin_ia32_packusdw512:
4815 case clang::X86::BI__builtin_ia32_packuswb128:
4816 case clang::X86::BI__builtin_ia32_packuswb256:
4817 case clang::X86::BI__builtin_ia32_packuswb512:
4818 return interp__builtin_x86_pack(S, OpPC, Call, [](const APSInt &Src) {
4819 unsigned DstBits = Src.getBitWidth() / 2;
4820 if (Src.isNegative())
4821 return APInt::getZero(DstBits);
4822 if (Src.isIntN(DstBits))
4823 return APInt(Src).trunc(DstBits);
4824 return APInt::getAllOnes(DstBits);
4825 });
4826
4827 case clang::X86::BI__builtin_ia32_selectss_128:
4828 case clang::X86::BI__builtin_ia32_selectsd_128:
4829 case clang::X86::BI__builtin_ia32_selectsh_128:
4830 case clang::X86::BI__builtin_ia32_selectsbf_128:
4831 return interp__builtin_select_scalar(S, Call);
4832 case clang::X86::BI__builtin_ia32_vprotbi:
4833 case clang::X86::BI__builtin_ia32_vprotdi:
4834 case clang::X86::BI__builtin_ia32_vprotqi:
4835 case clang::X86::BI__builtin_ia32_vprotwi:
4836 case clang::X86::BI__builtin_ia32_prold128:
4837 case clang::X86::BI__builtin_ia32_prold256:
4838 case clang::X86::BI__builtin_ia32_prold512:
4839 case clang::X86::BI__builtin_ia32_prolq128:
4840 case clang::X86::BI__builtin_ia32_prolq256:
4841 case clang::X86::BI__builtin_ia32_prolq512:
4842 return interp__builtin_elementwise_int_binop(
4843 S, OpPC, Call,
4844 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotl(RHS); });
4845
4846 case clang::X86::BI__builtin_ia32_prord128:
4847 case clang::X86::BI__builtin_ia32_prord256:
4848 case clang::X86::BI__builtin_ia32_prord512:
4849 case clang::X86::BI__builtin_ia32_prorq128:
4850 case clang::X86::BI__builtin_ia32_prorq256:
4851 case clang::X86::BI__builtin_ia32_prorq512:
4852 return interp__builtin_elementwise_int_binop(
4853 S, OpPC, Call,
4854 [](const APSInt &LHS, const APSInt &RHS) { return LHS.rotr(RHS); });
4855
4856 case Builtin::BI__builtin_elementwise_max:
4857 case Builtin::BI__builtin_elementwise_min:
4858 return interp__builtin_elementwise_maxmin(S, OpPC, Call, BuiltinID);
4859
4860 case clang::X86::BI__builtin_ia32_phaddw128:
4861 case clang::X86::BI__builtin_ia32_phaddw256:
4862 case clang::X86::BI__builtin_ia32_phaddd128:
4863 case clang::X86::BI__builtin_ia32_phaddd256:
4864 return interp_builtin_horizontal_int_binop(
4865 S, OpPC, Call,
4866 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
4867 case clang::X86::BI__builtin_ia32_phaddsw128:
4868 case clang::X86::BI__builtin_ia32_phaddsw256:
4869 return interp_builtin_horizontal_int_binop(
4870 S, OpPC, Call,
4871 [](const APSInt &LHS, const APSInt &RHS) { return LHS.sadd_sat(RHS); });
4872 case clang::X86::BI__builtin_ia32_phsubw128:
4873 case clang::X86::BI__builtin_ia32_phsubw256:
4874 case clang::X86::BI__builtin_ia32_phsubd128:
4875 case clang::X86::BI__builtin_ia32_phsubd256:
4876 return interp_builtin_horizontal_int_binop(
4877 S, OpPC, Call,
4878 [](const APSInt &LHS, const APSInt &RHS) { return LHS - RHS; });
4879 case clang::X86::BI__builtin_ia32_phsubsw128:
4880 case clang::X86::BI__builtin_ia32_phsubsw256:
4881 return interp_builtin_horizontal_int_binop(
4882 S, OpPC, Call,
4883 [](const APSInt &LHS, const APSInt &RHS) { return LHS.ssub_sat(RHS); });
4884 case clang::X86::BI__builtin_ia32_haddpd:
4885 case clang::X86::BI__builtin_ia32_haddps:
4886 case clang::X86::BI__builtin_ia32_haddpd256:
4887 case clang::X86::BI__builtin_ia32_haddps256:
4888 return interp_builtin_horizontal_fp_binop(
4889 S, OpPC, Call,
4890 [](const APFloat &LHS, const APFloat &RHS, llvm::RoundingMode RM) {
4891 APFloat F = LHS;
4892 F.add(RHS, RM);
4893 return F;
4894 });
4895 case clang::X86::BI__builtin_ia32_hsubpd:
4896 case clang::X86::BI__builtin_ia32_hsubps:
4897 case clang::X86::BI__builtin_ia32_hsubpd256:
4898 case clang::X86::BI__builtin_ia32_hsubps256:
4899 return interp_builtin_horizontal_fp_binop(
4900 S, OpPC, Call,
4901 [](const APFloat &LHS, const APFloat &RHS, llvm::RoundingMode RM) {
4902 APFloat F = LHS;
4903 F.subtract(RHS, RM);
4904 return F;
4905 });
4906 case clang::X86::BI__builtin_ia32_addsubpd:
4907 case clang::X86::BI__builtin_ia32_addsubps:
4908 case clang::X86::BI__builtin_ia32_addsubpd256:
4909 case clang::X86::BI__builtin_ia32_addsubps256:
4910 return interp__builtin_ia32_addsub(S, OpPC, Call);
4911
4912 case clang::X86::BI__builtin_ia32_pmuldq128:
4913 case clang::X86::BI__builtin_ia32_pmuldq256:
4914 case clang::X86::BI__builtin_ia32_pmuldq512:
4915 return interp__builtin_ia32_pmul(
4916 S, OpPC, Call,
4917 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
4918 const APSInt &HiRHS) {
4919 return llvm::APIntOps::mulsExtended(LoLHS, LoRHS);
4920 });
4921
4922 case clang::X86::BI__builtin_ia32_pmuludq128:
4923 case clang::X86::BI__builtin_ia32_pmuludq256:
4924 case clang::X86::BI__builtin_ia32_pmuludq512:
4925 return interp__builtin_ia32_pmul(
4926 S, OpPC, Call,
4927 [](const APSInt &LoLHS, const APSInt &HiLHS, const APSInt &LoRHS,
4928 const APSInt &HiRHS) {
4929 return llvm::APIntOps::muluExtended(LoLHS, LoRHS);
4930 });
4931
4932 case clang::X86::BI__builtin_ia32_pclmulqdq128:
4933 case clang::X86::BI__builtin_ia32_pclmulqdq256:
4934 case clang::X86::BI__builtin_ia32_pclmulqdq512:
4935 return interp__builtin_ia32_pclmulqdq(S, OpPC, Call);
4936
4937 case Builtin::BI__builtin_elementwise_fma:
4938 return interp__builtin_elementwise_triop_fp(
4939 S, OpPC, Call,
4940 [](const APFloat &X, const APFloat &Y, const APFloat &Z,
4941 llvm::RoundingMode RM) {
4942 APFloat F = X;
4943 F.fusedMultiplyAdd(Y, Z, RM);
4944 return F;
4945 });
4946
4947 case X86::BI__builtin_ia32_vpmadd52luq128:
4948 case X86::BI__builtin_ia32_vpmadd52luq256:
4949 case X86::BI__builtin_ia32_vpmadd52luq512:
4950 return interp__builtin_elementwise_triop(
4951 S, OpPC, Call, [](const APSInt &A, const APSInt &B, const APSInt &C) {
4952 return A + (B.trunc(52) * C.trunc(52)).zext(64);
4953 });
4954 case X86::BI__builtin_ia32_vpmadd52huq128:
4955 case X86::BI__builtin_ia32_vpmadd52huq256:
4956 case X86::BI__builtin_ia32_vpmadd52huq512:
4957 return interp__builtin_elementwise_triop(
4958 S, OpPC, Call, [](const APSInt &A, const APSInt &B, const APSInt &C) {
4959 return A + llvm::APIntOps::mulhu(B.trunc(52), C.trunc(52)).zext(64);
4960 });
4961
4962 case X86::BI__builtin_ia32_vpshldd128:
4963 case X86::BI__builtin_ia32_vpshldd256:
4964 case X86::BI__builtin_ia32_vpshldd512:
4965 case X86::BI__builtin_ia32_vpshldq128:
4966 case X86::BI__builtin_ia32_vpshldq256:
4967 case X86::BI__builtin_ia32_vpshldq512:
4968 case X86::BI__builtin_ia32_vpshldw128:
4969 case X86::BI__builtin_ia32_vpshldw256:
4970 case X86::BI__builtin_ia32_vpshldw512:
4971 return interp__builtin_elementwise_triop(
4972 S, OpPC, Call,
4973 [](const APSInt &Hi, const APSInt &Lo, const APSInt &Amt) {
4974 return llvm::APIntOps::fshl(Hi, Lo, Amt);
4975 });
4976
4977 case X86::BI__builtin_ia32_vpshrdd128:
4978 case X86::BI__builtin_ia32_vpshrdd256:
4979 case X86::BI__builtin_ia32_vpshrdd512:
4980 case X86::BI__builtin_ia32_vpshrdq128:
4981 case X86::BI__builtin_ia32_vpshrdq256:
4982 case X86::BI__builtin_ia32_vpshrdq512:
4983 case X86::BI__builtin_ia32_vpshrdw128:
4984 case X86::BI__builtin_ia32_vpshrdw256:
4985 case X86::BI__builtin_ia32_vpshrdw512:
4986 // NOTE: Reversed Hi/Lo operands.
4987 return interp__builtin_elementwise_triop(
4988 S, OpPC, Call,
4989 [](const APSInt &Lo, const APSInt &Hi, const APSInt &Amt) {
4990 return llvm::APIntOps::fshr(Hi, Lo, Amt);
4991 });
4992 case X86::BI__builtin_ia32_vpconflictsi_128:
4993 case X86::BI__builtin_ia32_vpconflictsi_256:
4994 case X86::BI__builtin_ia32_vpconflictsi_512:
4995 case X86::BI__builtin_ia32_vpconflictdi_128:
4996 case X86::BI__builtin_ia32_vpconflictdi_256:
4997 case X86::BI__builtin_ia32_vpconflictdi_512:
4998 return interp__builtin_ia32_vpconflict(S, OpPC, Call);
4999 case clang::X86::BI__builtin_ia32_blendpd:
5000 case clang::X86::BI__builtin_ia32_blendpd256:
5001 case clang::X86::BI__builtin_ia32_blendps:
5002 case clang::X86::BI__builtin_ia32_blendps256:
5003 case clang::X86::BI__builtin_ia32_pblendw128:
5004 case clang::X86::BI__builtin_ia32_pblendw256:
5005 case clang::X86::BI__builtin_ia32_pblendd128:
5006 case clang::X86::BI__builtin_ia32_pblendd256:
5007 return interp__builtin_ia32_shuffle_generic(
5008 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5009 // Bit index for mask.
5010 unsigned MaskBit = (ShuffleMask >> (DstIdx % 8)) & 0x1;
5011 unsigned SrcVecIdx = MaskBit ? 1 : 0; // 1 = TrueVec, 0 = FalseVec
5012 return std::pair<unsigned, int>{SrcVecIdx, static_cast<int>(DstIdx)};
5013 });
5014
5015
5016
5017 case clang::X86::BI__builtin_ia32_blendvpd:
5018 case clang::X86::BI__builtin_ia32_blendvpd256:
5019 case clang::X86::BI__builtin_ia32_blendvps:
5020 case clang::X86::BI__builtin_ia32_blendvps256:
5021 return interp__builtin_elementwise_triop_fp(
5022 S, OpPC, Call,
5023 [](const APFloat &F, const APFloat &T, const APFloat &C,
5024 llvm::RoundingMode) { return C.isNegative() ? T : F; });
5025
5026 case clang::X86::BI__builtin_ia32_pblendvb128:
5027 case clang::X86::BI__builtin_ia32_pblendvb256:
5028 return interp__builtin_elementwise_triop(
5029 S, OpPC, Call, [](const APSInt &F, const APSInt &T, const APSInt &C) {
5030 return ((APInt)C).isNegative() ? T : F;
5031 });
5032 case X86::BI__builtin_ia32_ptestz128:
5033 case X86::BI__builtin_ia32_ptestz256:
5034 case X86::BI__builtin_ia32_vtestzps:
5035 case X86::BI__builtin_ia32_vtestzps256:
5036 case X86::BI__builtin_ia32_vtestzpd:
5037 case X86::BI__builtin_ia32_vtestzpd256:
5038 return interp__builtin_ia32_test_op(
5039 S, OpPC, Call,
5040 [](const APInt &A, const APInt &B) { return (A & B) == 0; });
5041 case X86::BI__builtin_ia32_ptestc128:
5042 case X86::BI__builtin_ia32_ptestc256:
5043 case X86::BI__builtin_ia32_vtestcps:
5044 case X86::BI__builtin_ia32_vtestcps256:
5045 case X86::BI__builtin_ia32_vtestcpd:
5046 case X86::BI__builtin_ia32_vtestcpd256:
5047 return interp__builtin_ia32_test_op(
5048 S, OpPC, Call,
5049 [](const APInt &A, const APInt &B) { return (~A & B) == 0; });
5050 case X86::BI__builtin_ia32_ptestnzc128:
5051 case X86::BI__builtin_ia32_ptestnzc256:
5052 case X86::BI__builtin_ia32_vtestnzcps:
5053 case X86::BI__builtin_ia32_vtestnzcps256:
5054 case X86::BI__builtin_ia32_vtestnzcpd:
5055 case X86::BI__builtin_ia32_vtestnzcpd256:
5056 return interp__builtin_ia32_test_op(
5057 S, OpPC, Call, [](const APInt &A, const APInt &B) {
5058 return ((A & B) != 0) && ((~A & B) != 0);
5059 });
5060 case X86::BI__builtin_ia32_selectb_128:
5061 case X86::BI__builtin_ia32_selectb_256:
5062 case X86::BI__builtin_ia32_selectb_512:
5063 case X86::BI__builtin_ia32_selectw_128:
5064 case X86::BI__builtin_ia32_selectw_256:
5065 case X86::BI__builtin_ia32_selectw_512:
5066 case X86::BI__builtin_ia32_selectd_128:
5067 case X86::BI__builtin_ia32_selectd_256:
5068 case X86::BI__builtin_ia32_selectd_512:
5069 case X86::BI__builtin_ia32_selectq_128:
5070 case X86::BI__builtin_ia32_selectq_256:
5071 case X86::BI__builtin_ia32_selectq_512:
5072 case X86::BI__builtin_ia32_selectph_128:
5073 case X86::BI__builtin_ia32_selectph_256:
5074 case X86::BI__builtin_ia32_selectph_512:
5075 case X86::BI__builtin_ia32_selectpbf_128:
5076 case X86::BI__builtin_ia32_selectpbf_256:
5077 case X86::BI__builtin_ia32_selectpbf_512:
5078 case X86::BI__builtin_ia32_selectps_128:
5079 case X86::BI__builtin_ia32_selectps_256:
5080 case X86::BI__builtin_ia32_selectps_512:
5081 case X86::BI__builtin_ia32_selectpd_128:
5082 case X86::BI__builtin_ia32_selectpd_256:
5083 case X86::BI__builtin_ia32_selectpd_512:
5084 return interp__builtin_select(S, OpPC, Call);
5085
5086 case X86::BI__builtin_ia32_shufps:
5087 case X86::BI__builtin_ia32_shufps256:
5088 case X86::BI__builtin_ia32_shufps512:
5089 return interp__builtin_ia32_shuffle_generic(
5090 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5091 unsigned NumElemPerLane = 4;
5092 unsigned NumSelectableElems = NumElemPerLane / 2;
5093 unsigned BitsPerElem = 2;
5094 unsigned IndexMask = 0x3;
5095 unsigned MaskBits = 8;
5096 unsigned Lane = DstIdx / NumElemPerLane;
5097 unsigned ElemInLane = DstIdx % NumElemPerLane;
5098 unsigned LaneOffset = Lane * NumElemPerLane;
5099 unsigned SrcIdx = ElemInLane >= NumSelectableElems ? 1 : 0;
5100 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
5101 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
5102 return std::pair<unsigned, int>{SrcIdx,
5103 static_cast<int>(LaneOffset + Index)};
5104 });
5105 case X86::BI__builtin_ia32_shufpd:
5106 case X86::BI__builtin_ia32_shufpd256:
5107 case X86::BI__builtin_ia32_shufpd512:
5108 return interp__builtin_ia32_shuffle_generic(
5109 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5110 unsigned NumElemPerLane = 2;
5111 unsigned NumSelectableElems = NumElemPerLane / 2;
5112 unsigned BitsPerElem = 1;
5113 unsigned IndexMask = 0x1;
5114 unsigned MaskBits = 8;
5115 unsigned Lane = DstIdx / NumElemPerLane;
5116 unsigned ElemInLane = DstIdx % NumElemPerLane;
5117 unsigned LaneOffset = Lane * NumElemPerLane;
5118 unsigned SrcIdx = ElemInLane >= NumSelectableElems ? 1 : 0;
5119 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
5120 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
5121 return std::pair<unsigned, int>{SrcIdx,
5122 static_cast<int>(LaneOffset + Index)};
5123 });
5124
5125 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
5126 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
5127 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
5128 return interp_builtin_ia32_gfni_affine(S, OpPC, Call, true);
5129 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
5130 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
5131 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi:
5132 return interp_builtin_ia32_gfni_affine(S, OpPC, Call, false);
5133
5134 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
5135 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
5136 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi:
5137 return interp__builtin_ia32_gfni_mul(S, OpPC, Call);
5138
5139 case X86::BI__builtin_ia32_insertps128:
5140 return interp__builtin_ia32_shuffle_generic(
5141 S, OpPC, Call, [](unsigned DstIdx, unsigned Mask) {
5142 // Bits [3:0]: zero mask - if bit is set, zero this element
5143 if ((Mask & (1 << DstIdx)) != 0) {
5144 return std::pair<unsigned, int>{0, -1};
5145 }
5146 // Bits [7:6]: select element from source vector Y (0-3)
5147 // Bits [5:4]: select destination position (0-3)
5148 unsigned SrcElem = (Mask >> 6) & 0x3;
5149 unsigned DstElem = (Mask >> 4) & 0x3;
5150 if (DstIdx == DstElem) {
5151 // Insert element from source vector (B) at this position
5152 return std::pair<unsigned, int>{1, static_cast<int>(SrcElem)};
5153 } else {
5154 // Copy from destination vector (A)
5155 return std::pair<unsigned, int>{0, static_cast<int>(DstIdx)};
5156 }
5157 });
5158 case X86::BI__builtin_ia32_permvarsi256:
5159 case X86::BI__builtin_ia32_permvarsf256:
5160 case X86::BI__builtin_ia32_permvardf512:
5161 case X86::BI__builtin_ia32_permvardi512:
5162 case X86::BI__builtin_ia32_permvarhi128:
5163 return interp__builtin_ia32_shuffle_generic(
5164 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5165 int Offset = ShuffleMask & 0x7;
5166 return std::pair<unsigned, int>{0, Offset};
5167 });
5168 case X86::BI__builtin_ia32_permvarqi128:
5169 case X86::BI__builtin_ia32_permvarhi256:
5170 case X86::BI__builtin_ia32_permvarsi512:
5171 case X86::BI__builtin_ia32_permvarsf512:
5172 return interp__builtin_ia32_shuffle_generic(
5173 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5174 int Offset = ShuffleMask & 0xF;
5175 return std::pair<unsigned, int>{0, Offset};
5176 });
5177 case X86::BI__builtin_ia32_permvardi256:
5178 case X86::BI__builtin_ia32_permvardf256:
5179 return interp__builtin_ia32_shuffle_generic(
5180 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5181 int Offset = ShuffleMask & 0x3;
5182 return std::pair<unsigned, int>{0, Offset};
5183 });
5184 case X86::BI__builtin_ia32_permvarqi256:
5185 case X86::BI__builtin_ia32_permvarhi512:
5186 return interp__builtin_ia32_shuffle_generic(
5187 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5188 int Offset = ShuffleMask & 0x1F;
5189 return std::pair<unsigned, int>{0, Offset};
5190 });
5191 case X86::BI__builtin_ia32_permvarqi512:
5192 return interp__builtin_ia32_shuffle_generic(
5193 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5194 int Offset = ShuffleMask & 0x3F;
5195 return std::pair<unsigned, int>{0, Offset};
5196 });
5197 case X86::BI__builtin_ia32_vpermi2varq128:
5198 case X86::BI__builtin_ia32_vpermi2varpd128:
5199 return interp__builtin_ia32_shuffle_generic(
5200 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5201 int Offset = ShuffleMask & 0x1;
5202 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
5203 return std::pair<unsigned, int>{SrcIdx, Offset};
5204 });
5205 case X86::BI__builtin_ia32_vpermi2vard128:
5206 case X86::BI__builtin_ia32_vpermi2varps128:
5207 case X86::BI__builtin_ia32_vpermi2varq256:
5208 case X86::BI__builtin_ia32_vpermi2varpd256:
5209 return interp__builtin_ia32_shuffle_generic(
5210 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5211 int Offset = ShuffleMask & 0x3;
5212 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
5213 return std::pair<unsigned, int>{SrcIdx, Offset};
5214 });
5215 case X86::BI__builtin_ia32_vpermi2varhi128:
5216 case X86::BI__builtin_ia32_vpermi2vard256:
5217 case X86::BI__builtin_ia32_vpermi2varps256:
5218 case X86::BI__builtin_ia32_vpermi2varq512:
5219 case X86::BI__builtin_ia32_vpermi2varpd512:
5220 return interp__builtin_ia32_shuffle_generic(
5221 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5222 int Offset = ShuffleMask & 0x7;
5223 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
5224 return std::pair<unsigned, int>{SrcIdx, Offset};
5225 });
5226 case X86::BI__builtin_ia32_vpermi2varqi128:
5227 case X86::BI__builtin_ia32_vpermi2varhi256:
5228 case X86::BI__builtin_ia32_vpermi2vard512:
5229 case X86::BI__builtin_ia32_vpermi2varps512:
5230 return interp__builtin_ia32_shuffle_generic(
5231 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5232 int Offset = ShuffleMask & 0xF;
5233 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
5234 return std::pair<unsigned, int>{SrcIdx, Offset};
5235 });
5236 case X86::BI__builtin_ia32_vpermi2varqi256:
5237 case X86::BI__builtin_ia32_vpermi2varhi512:
5238 return interp__builtin_ia32_shuffle_generic(
5239 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5240 int Offset = ShuffleMask & 0x1F;
5241 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
5242 return std::pair<unsigned, int>{SrcIdx, Offset};
5243 });
5244 case X86::BI__builtin_ia32_vpermi2varqi512:
5245 return interp__builtin_ia32_shuffle_generic(
5246 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5247 int Offset = ShuffleMask & 0x3F;
5248 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
5249 return std::pair<unsigned, int>{SrcIdx, Offset};
5250 });
5251 case X86::BI__builtin_ia32_vperm2f128_pd256:
5252 case X86::BI__builtin_ia32_vperm2f128_ps256:
5253 case X86::BI__builtin_ia32_vperm2f128_si256:
5254 case X86::BI__builtin_ia32_permti256: {
5255 unsigned NumElements =
5256 Call->getArg(0)->getType()->castAs<VectorType>()->getNumElements();
5257 unsigned PreservedBitsCnt = NumElements >> 2;
5258 return interp__builtin_ia32_shuffle_generic(
5259 S, OpPC, Call,
5260 [PreservedBitsCnt](unsigned DstIdx, unsigned ShuffleMask) {
5261 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
5262 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
5263
5264 if (ControlBits & 0b1000)
5265 return std::make_pair(0u, -1);
5266
5267 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
5268 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
5269 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
5270 (DstIdx & PreservedBitsMask);
5271 return std::make_pair(SrcVecIdx, SrcIdx);
5272 });
5273 }
5274 case X86::BI__builtin_ia32_pshufb128:
5275 case X86::BI__builtin_ia32_pshufb256:
5276 case X86::BI__builtin_ia32_pshufb512:
5277 return interp__builtin_ia32_shuffle_generic(
5278 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5279 uint8_t Ctlb = static_cast<uint8_t>(ShuffleMask);
5280 if (Ctlb & 0x80)
5281 return std::make_pair(0, -1);
5282
5283 unsigned LaneBase = (DstIdx / 16) * 16;
5284 unsigned SrcOffset = Ctlb & 0x0F;
5285 unsigned SrcIdx = LaneBase + SrcOffset;
5286 return std::make_pair(0, static_cast<int>(SrcIdx));
5287 });
5288
5289 case X86::BI__builtin_ia32_pshuflw:
5290 case X86::BI__builtin_ia32_pshuflw256:
5291 case X86::BI__builtin_ia32_pshuflw512:
5292 return interp__builtin_ia32_shuffle_generic(
5293 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5294 unsigned LaneBase = (DstIdx / 8) * 8;
5295 unsigned LaneIdx = DstIdx % 8;
5296 if (LaneIdx < 4) {
5297 unsigned Sel = (ShuffleMask >> (2 * LaneIdx)) & 0x3;
5298 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
5299 }
5300
5301 return std::make_pair(0, static_cast<int>(DstIdx));
5302 });
5303
5304 case X86::BI__builtin_ia32_pshufhw:
5305 case X86::BI__builtin_ia32_pshufhw256:
5306 case X86::BI__builtin_ia32_pshufhw512:
5307 return interp__builtin_ia32_shuffle_generic(
5308 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5309 unsigned LaneBase = (DstIdx / 8) * 8;
5310 unsigned LaneIdx = DstIdx % 8;
5311 if (LaneIdx >= 4) {
5312 unsigned Sel = (ShuffleMask >> (2 * (LaneIdx - 4))) & 0x3;
5313 return std::make_pair(0, static_cast<int>(LaneBase + 4 + Sel));
5314 }
5315
5316 return std::make_pair(0, static_cast<int>(DstIdx));
5317 });
5318
5319 case X86::BI__builtin_ia32_pshufd:
5320 case X86::BI__builtin_ia32_pshufd256:
5321 case X86::BI__builtin_ia32_pshufd512:
5322 case X86::BI__builtin_ia32_vpermilps:
5323 case X86::BI__builtin_ia32_vpermilps256:
5324 case X86::BI__builtin_ia32_vpermilps512:
5325 return interp__builtin_ia32_shuffle_generic(
5326 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5327 unsigned LaneBase = (DstIdx / 4) * 4;
5328 unsigned LaneIdx = DstIdx % 4;
5329 unsigned Sel = (ShuffleMask >> (2 * LaneIdx)) & 0x3;
5330 return std::make_pair(0, static_cast<int>(LaneBase + Sel));
5331 });
5332
5333 case X86::BI__builtin_ia32_vpermilvarpd:
5334 case X86::BI__builtin_ia32_vpermilvarpd256:
5335 case X86::BI__builtin_ia32_vpermilvarpd512:
5336 return interp__builtin_ia32_shuffle_generic(
5337 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5338 unsigned NumElemPerLane = 2;
5339 unsigned Lane = DstIdx / NumElemPerLane;
5340 unsigned Offset = ShuffleMask & 0b10 ? 1 : 0;
5341 return std::make_pair(
5342 0, static_cast<int>(Lane * NumElemPerLane + Offset));
5343 });
5344
5345 case X86::BI__builtin_ia32_vpermilvarps:
5346 case X86::BI__builtin_ia32_vpermilvarps256:
5347 case X86::BI__builtin_ia32_vpermilvarps512:
5348 return interp__builtin_ia32_shuffle_generic(
5349 S, OpPC, Call, [](unsigned DstIdx, unsigned ShuffleMask) {
5350 unsigned NumElemPerLane = 4;
5351 unsigned Lane = DstIdx / NumElemPerLane;
5352 unsigned Offset = ShuffleMask & 0b11;
5353 return std::make_pair(
5354 0, static_cast<int>(Lane * NumElemPerLane + Offset));
5355 });
5356
5357 case X86::BI__builtin_ia32_vpermilpd:
5358 case X86::BI__builtin_ia32_vpermilpd256:
5359 case X86::BI__builtin_ia32_vpermilpd512:
5360 return interp__builtin_ia32_shuffle_generic(
5361 S, OpPC, Call, [](unsigned DstIdx, unsigned Control) {
5362 unsigned NumElemPerLane = 2;
5363 unsigned BitsPerElem = 1;
5364 unsigned MaskBits = 8;
5365 unsigned IndexMask = 0x1;
5366 unsigned Lane = DstIdx / NumElemPerLane;
5367 unsigned LaneOffset = Lane * NumElemPerLane;
5368 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
5369 unsigned Index = (Control >> BitIndex) & IndexMask;
5370 return std::make_pair(0, static_cast<int>(LaneOffset + Index));
5371 });
5372
5373 case X86::BI__builtin_ia32_permdf256:
5374 case X86::BI__builtin_ia32_permdi256:
5375 return interp__builtin_ia32_shuffle_generic(
5376 S, OpPC, Call, [](unsigned DstIdx, unsigned Control) {
5377 // permute4x64 operates on 4 64-bit elements
5378 // For element i (0-3), extract bits [2*i+1:2*i] from Control
5379 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
5380 return std::make_pair(0, static_cast<int>(Index));
5381 });
5382
5383 case X86::BI__builtin_ia32_vpmultishiftqb128:
5384 case X86::BI__builtin_ia32_vpmultishiftqb256:
5385 case X86::BI__builtin_ia32_vpmultishiftqb512:
5386 return interp__builtin_ia32_multishiftqb(S, OpPC, Call);
5387 case X86::BI__builtin_ia32_kandqi:
5388 case X86::BI__builtin_ia32_kandhi:
5389 case X86::BI__builtin_ia32_kandsi:
5390 case X86::BI__builtin_ia32_kanddi:
5391 return interp__builtin_elementwise_int_binop(
5392 S, OpPC, Call,
5393 [](const APSInt &LHS, const APSInt &RHS) { return LHS & RHS; });
5394
5395 case X86::BI__builtin_ia32_kandnqi:
5396 case X86::BI__builtin_ia32_kandnhi:
5397 case X86::BI__builtin_ia32_kandnsi:
5398 case X86::BI__builtin_ia32_kandndi:
5399 return interp__builtin_elementwise_int_binop(
5400 S, OpPC, Call,
5401 [](const APSInt &LHS, const APSInt &RHS) { return ~LHS & RHS; });
5402
5403 case X86::BI__builtin_ia32_korqi:
5404 case X86::BI__builtin_ia32_korhi:
5405 case X86::BI__builtin_ia32_korsi:
5406 case X86::BI__builtin_ia32_kordi:
5407 return interp__builtin_elementwise_int_binop(
5408 S, OpPC, Call,
5409 [](const APSInt &LHS, const APSInt &RHS) { return LHS | RHS; });
5410
5411 case X86::BI__builtin_ia32_kxnorqi:
5412 case X86::BI__builtin_ia32_kxnorhi:
5413 case X86::BI__builtin_ia32_kxnorsi:
5414 case X86::BI__builtin_ia32_kxnordi:
5415 return interp__builtin_elementwise_int_binop(
5416 S, OpPC, Call,
5417 [](const APSInt &LHS, const APSInt &RHS) { return ~(LHS ^ RHS); });
5418
5419 case X86::BI__builtin_ia32_kxorqi:
5420 case X86::BI__builtin_ia32_kxorhi:
5421 case X86::BI__builtin_ia32_kxorsi:
5422 case X86::BI__builtin_ia32_kxordi:
5423 return interp__builtin_elementwise_int_binop(
5424 S, OpPC, Call,
5425 [](const APSInt &LHS, const APSInt &RHS) { return LHS ^ RHS; });
5426
5427 case X86::BI__builtin_ia32_knotqi:
5428 case X86::BI__builtin_ia32_knothi:
5429 case X86::BI__builtin_ia32_knotsi:
5430 case X86::BI__builtin_ia32_knotdi:
5431 return interp__builtin_elementwise_int_unaryop(
5432 S, OpPC, Call, [](const APSInt &Src) { return ~Src; });
5433
5434 case X86::BI__builtin_ia32_kaddqi:
5435 case X86::BI__builtin_ia32_kaddhi:
5436 case X86::BI__builtin_ia32_kaddsi:
5437 case X86::BI__builtin_ia32_kadddi:
5438 return interp__builtin_elementwise_int_binop(
5439 S, OpPC, Call,
5440 [](const APSInt &LHS, const APSInt &RHS) { return LHS + RHS; });
5441
5442 case X86::BI__builtin_ia32_kmovb:
5443 case X86::BI__builtin_ia32_kmovw:
5444 case X86::BI__builtin_ia32_kmovd:
5445 case X86::BI__builtin_ia32_kmovq:
5446 return interp__builtin_elementwise_int_unaryop(
5447 S, OpPC, Call, [](const APSInt &Src) { return Src; });
5448
5449 case X86::BI__builtin_ia32_kunpckhi:
5450 case X86::BI__builtin_ia32_kunpckdi:
5451 case X86::BI__builtin_ia32_kunpcksi:
5452 return interp__builtin_elementwise_int_binop(
5453 S, OpPC, Call, [](const APSInt &A, const APSInt &B) {
5454 // Generic kunpack: extract lower half of each operand and concatenate
5455 // Result = A[HalfWidth-1:0] concat B[HalfWidth-1:0]
5456 unsigned BW = A.getBitWidth();
5457 return APSInt(A.trunc(BW / 2).concat(B.trunc(BW / 2)),
5458 A.isUnsigned());
5459 });
5460
5461 case X86::BI__builtin_ia32_phminposuw128:
5462 return interp__builtin_ia32_phminposuw(S, OpPC, Call);
5463
5464 case X86::BI__builtin_ia32_psraq128:
5465 case X86::BI__builtin_ia32_psraq256:
5466 case X86::BI__builtin_ia32_psraq512:
5467 case X86::BI__builtin_ia32_psrad128:
5468 case X86::BI__builtin_ia32_psrad256:
5469 case X86::BI__builtin_ia32_psrad512:
5470 case X86::BI__builtin_ia32_psraw128:
5471 case X86::BI__builtin_ia32_psraw256:
5472 case X86::BI__builtin_ia32_psraw512:
5473 return interp__builtin_ia32_shift_with_count(
5474 S, OpPC, Call,
5475 [](const APInt &Elt, uint64_t Count) { return Elt.ashr(Count); },
5476 [](const APInt &Elt, unsigned Width) { return Elt.ashr(Width - 1); });
5477
5478 case X86::BI__builtin_ia32_psllq128:
5479 case X86::BI__builtin_ia32_psllq256:
5480 case X86::BI__builtin_ia32_psllq512:
5481 case X86::BI__builtin_ia32_pslld128:
5482 case X86::BI__builtin_ia32_pslld256:
5483 case X86::BI__builtin_ia32_pslld512:
5484 case X86::BI__builtin_ia32_psllw128:
5485 case X86::BI__builtin_ia32_psllw256:
5486 case X86::BI__builtin_ia32_psllw512:
5487 return interp__builtin_ia32_shift_with_count(
5488 S, OpPC, Call,
5489 [](const APInt &Elt, uint64_t Count) { return Elt.shl(Count); },
5490 [](const APInt &Elt, unsigned Width) { return APInt::getZero(Width); });
5491
5492 case X86::BI__builtin_ia32_psrlq128:
5493 case X86::BI__builtin_ia32_psrlq256:
5494 case X86::BI__builtin_ia32_psrlq512:
5495 case X86::BI__builtin_ia32_psrld128:
5496 case X86::BI__builtin_ia32_psrld256:
5497 case X86::BI__builtin_ia32_psrld512:
5498 case X86::BI__builtin_ia32_psrlw128:
5499 case X86::BI__builtin_ia32_psrlw256:
5500 case X86::BI__builtin_ia32_psrlw512:
5501 return interp__builtin_ia32_shift_with_count(
5502 S, OpPC, Call,
5503 [](const APInt &Elt, uint64_t Count) { return Elt.lshr(Count); },
5504 [](const APInt &Elt, unsigned Width) { return APInt::getZero(Width); });
5505
5506 case X86::BI__builtin_ia32_pternlogd128_mask:
5507 case X86::BI__builtin_ia32_pternlogd256_mask:
5508 case X86::BI__builtin_ia32_pternlogd512_mask:
5509 case X86::BI__builtin_ia32_pternlogq128_mask:
5510 case X86::BI__builtin_ia32_pternlogq256_mask:
5511 case X86::BI__builtin_ia32_pternlogq512_mask:
5512 return interp__builtin_ia32_pternlog(S, OpPC, Call, /*MaskZ=*/false);
5513 case X86::BI__builtin_ia32_pternlogd128_maskz:
5514 case X86::BI__builtin_ia32_pternlogd256_maskz:
5515 case X86::BI__builtin_ia32_pternlogd512_maskz:
5516 case X86::BI__builtin_ia32_pternlogq128_maskz:
5517 case X86::BI__builtin_ia32_pternlogq256_maskz:
5518 case X86::BI__builtin_ia32_pternlogq512_maskz:
5519 return interp__builtin_ia32_pternlog(S, OpPC, Call, /*MaskZ=*/true);
5520 case Builtin::BI__builtin_elementwise_fshl:
5521 return interp__builtin_elementwise_triop(S, OpPC, Call,
5522 llvm::APIntOps::fshl);
5523 case Builtin::BI__builtin_elementwise_fshr:
5524 return interp__builtin_elementwise_triop(S, OpPC, Call,
5525 llvm::APIntOps::fshr);
5526
5527 case X86::BI__builtin_ia32_shuf_f32x4_256:
5528 case X86::BI__builtin_ia32_shuf_i32x4_256:
5529 case X86::BI__builtin_ia32_shuf_f64x2_256:
5530 case X86::BI__builtin_ia32_shuf_i64x2_256:
5531 case X86::BI__builtin_ia32_shuf_f32x4:
5532 case X86::BI__builtin_ia32_shuf_i32x4:
5533 case X86::BI__builtin_ia32_shuf_f64x2:
5534 case X86::BI__builtin_ia32_shuf_i64x2: {
5535 // Destination and sources A, B all have the same type.
5536 QualType VecQT = Call->getArg(0)->getType();
5537 const auto *VecT = VecQT->castAs<VectorType>();
5538 unsigned NumElems = VecT->getNumElements();
5539 unsigned ElemBits = S.getASTContext().getTypeSize(VecT->getElementType());
5540 unsigned LaneBits = 128u;
5541 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
5542 unsigned NumElemsPerLane = LaneBits / ElemBits;
5543
5544 return interp__builtin_ia32_shuffle_generic(
5545 S, OpPC, Call,
5546 [NumLanes, NumElemsPerLane](unsigned DstIdx, unsigned ShuffleMask) {
5547 // DstIdx determines source. ShuffleMask selects lane in source.
5548 unsigned BitsPerElem = NumLanes / 2;
5549 unsigned IndexMask = (1u << BitsPerElem) - 1;
5550 unsigned Lane = DstIdx / NumElemsPerLane;
5551 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
5552 unsigned BitIdx = BitsPerElem * Lane;
5553 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
5554 unsigned ElemInLane = DstIdx % NumElemsPerLane;
5555 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
5556 return std::pair<unsigned, int>{SrcIdx, IdxToPick};
5557 });
5558 }
5559
5560 case X86::BI__builtin_ia32_insertf32x4_256:
5561 case X86::BI__builtin_ia32_inserti32x4_256:
5562 case X86::BI__builtin_ia32_insertf64x2_256:
5563 case X86::BI__builtin_ia32_inserti64x2_256:
5564 case X86::BI__builtin_ia32_insertf32x4:
5565 case X86::BI__builtin_ia32_inserti32x4:
5566 case X86::BI__builtin_ia32_insertf64x2_512:
5567 case X86::BI__builtin_ia32_inserti64x2_512:
5568 case X86::BI__builtin_ia32_insertf32x8:
5569 case X86::BI__builtin_ia32_inserti32x8:
5570 case X86::BI__builtin_ia32_insertf64x4:
5571 case X86::BI__builtin_ia32_inserti64x4:
5572 case X86::BI__builtin_ia32_vinsertf128_ps256:
5573 case X86::BI__builtin_ia32_vinsertf128_pd256:
5574 case X86::BI__builtin_ia32_vinsertf128_si256:
5575 case X86::BI__builtin_ia32_insert128i256:
5576 return interp__builtin_x86_insert_subvector(S, OpPC, Call, BuiltinID);
5577
5578 case clang::X86::BI__builtin_ia32_vcvtps2ph:
5579 case clang::X86::BI__builtin_ia32_vcvtps2ph256:
5580 return interp__builtin_ia32_vcvtps2ph(S, OpPC, Call);
5581
5582 case X86::BI__builtin_ia32_vec_ext_v4hi:
5583 case X86::BI__builtin_ia32_vec_ext_v16qi:
5584 case X86::BI__builtin_ia32_vec_ext_v8hi:
5585 case X86::BI__builtin_ia32_vec_ext_v4si:
5586 case X86::BI__builtin_ia32_vec_ext_v2di:
5587 case X86::BI__builtin_ia32_vec_ext_v32qi:
5588 case X86::BI__builtin_ia32_vec_ext_v16hi:
5589 case X86::BI__builtin_ia32_vec_ext_v8si:
5590 case X86::BI__builtin_ia32_vec_ext_v4di:
5591 case X86::BI__builtin_ia32_vec_ext_v4sf:
5592 return interp__builtin_vec_ext(S, OpPC, Call, BuiltinID);
5593
5594 case X86::BI__builtin_ia32_vec_set_v4hi:
5595 case X86::BI__builtin_ia32_vec_set_v16qi:
5596 case X86::BI__builtin_ia32_vec_set_v8hi:
5597 case X86::BI__builtin_ia32_vec_set_v4si:
5598 case X86::BI__builtin_ia32_vec_set_v2di:
5599 case X86::BI__builtin_ia32_vec_set_v32qi:
5600 case X86::BI__builtin_ia32_vec_set_v16hi:
5601 case X86::BI__builtin_ia32_vec_set_v8si:
5602 case X86::BI__builtin_ia32_vec_set_v4di:
5603 return interp__builtin_vec_set(S, OpPC, Call, BuiltinID);
5604
5605 case X86::BI__builtin_ia32_cvtb2mask128:
5606 case X86::BI__builtin_ia32_cvtb2mask256:
5607 case X86::BI__builtin_ia32_cvtb2mask512:
5608 case X86::BI__builtin_ia32_cvtw2mask128:
5609 case X86::BI__builtin_ia32_cvtw2mask256:
5610 case X86::BI__builtin_ia32_cvtw2mask512:
5611 case X86::BI__builtin_ia32_cvtd2mask128:
5612 case X86::BI__builtin_ia32_cvtd2mask256:
5613 case X86::BI__builtin_ia32_cvtd2mask512:
5614 case X86::BI__builtin_ia32_cvtq2mask128:
5615 case X86::BI__builtin_ia32_cvtq2mask256:
5616 case X86::BI__builtin_ia32_cvtq2mask512:
5617 return interp__builtin_ia32_cvt_vec2mask(S, OpPC, Call, BuiltinID);
5618
5619 case X86::BI__builtin_ia32_cvtmask2b128:
5620 case X86::BI__builtin_ia32_cvtmask2b256:
5621 case X86::BI__builtin_ia32_cvtmask2b512:
5622 case X86::BI__builtin_ia32_cvtmask2w128:
5623 case X86::BI__builtin_ia32_cvtmask2w256:
5624 case X86::BI__builtin_ia32_cvtmask2w512:
5625 case X86::BI__builtin_ia32_cvtmask2d128:
5626 case X86::BI__builtin_ia32_cvtmask2d256:
5627 case X86::BI__builtin_ia32_cvtmask2d512:
5628 case X86::BI__builtin_ia32_cvtmask2q128:
5629 case X86::BI__builtin_ia32_cvtmask2q256:
5630 case X86::BI__builtin_ia32_cvtmask2q512:
5631 return interp__builtin_ia32_cvt_mask2vec(S, OpPC, Call, BuiltinID);
5632
5633 case X86::BI__builtin_ia32_cvtsd2ss:
5634 return interp__builtin_ia32_cvtsd2ss(S, OpPC, Call, false);
5635
5636 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
5637 return interp__builtin_ia32_cvtsd2ss(S, OpPC, Call, true);
5638
5639 case X86::BI__builtin_ia32_cvtpd2ps:
5640 case X86::BI__builtin_ia32_cvtpd2ps256:
5641 return interp__builtin_ia32_cvtpd2ps(S, OpPC, Call, false, false);
5642 case X86::BI__builtin_ia32_cvtpd2ps_mask:
5643 return interp__builtin_ia32_cvtpd2ps(S, OpPC, Call, true, false);
5644 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
5645 return interp__builtin_ia32_cvtpd2ps(S, OpPC, Call, true, true);
5646
5647 case X86::BI__builtin_ia32_cmpb128_mask:
5648 case X86::BI__builtin_ia32_cmpw128_mask:
5649 case X86::BI__builtin_ia32_cmpd128_mask:
5650 case X86::BI__builtin_ia32_cmpq128_mask:
5651 case X86::BI__builtin_ia32_cmpb256_mask:
5652 case X86::BI__builtin_ia32_cmpw256_mask:
5653 case X86::BI__builtin_ia32_cmpd256_mask:
5654 case X86::BI__builtin_ia32_cmpq256_mask:
5655 case X86::BI__builtin_ia32_cmpb512_mask:
5656 case X86::BI__builtin_ia32_cmpw512_mask:
5657 case X86::BI__builtin_ia32_cmpd512_mask:
5658 case X86::BI__builtin_ia32_cmpq512_mask:
5659 return interp__builtin_ia32_cmp_mask(S, OpPC, Call, BuiltinID,
5660 /*IsUnsigned=*/false);
5661
5662 case X86::BI__builtin_ia32_ucmpb128_mask:
5663 case X86::BI__builtin_ia32_ucmpw128_mask:
5664 case X86::BI__builtin_ia32_ucmpd128_mask:
5665 case X86::BI__builtin_ia32_ucmpq128_mask:
5666 case X86::BI__builtin_ia32_ucmpb256_mask:
5667 case X86::BI__builtin_ia32_ucmpw256_mask:
5668 case X86::BI__builtin_ia32_ucmpd256_mask:
5669 case X86::BI__builtin_ia32_ucmpq256_mask:
5670 case X86::BI__builtin_ia32_ucmpb512_mask:
5671 case X86::BI__builtin_ia32_ucmpw512_mask:
5672 case X86::BI__builtin_ia32_ucmpd512_mask:
5673 case X86::BI__builtin_ia32_ucmpq512_mask:
5674 return interp__builtin_ia32_cmp_mask(S, OpPC, Call, BuiltinID,
5675 /*IsUnsigned=*/true);
5676
5677 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
5678 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
5679 case X86::BI__builtin_ia32_vpshufbitqmb512_mask:
5680 return interp__builtin_ia32_shufbitqmb_mask(S, OpPC, Call);
5681
5682 case X86::BI__builtin_ia32_pslldqi128_byteshift:
5683 case X86::BI__builtin_ia32_pslldqi256_byteshift:
5684 case X86::BI__builtin_ia32_pslldqi512_byteshift:
5685 // These SLLDQ intrinsics always operate on byte elements (8 bits).
5686 // The lane width is hardcoded to 16 to match the SIMD register size,
5687 // but the algorithm processes one byte per iteration,
5688 // so APInt(8, ...) is correct and intentional.
5689 return interp__builtin_ia32_shuffle_generic(
5690 S, OpPC, Call,
5691 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
5692 unsigned LaneBase = (DstIdx / 16) * 16;
5693 unsigned LaneIdx = DstIdx % 16;
5694 if (LaneIdx < Shift)
5695 return std::make_pair(0, -1);
5696
5697 return std::make_pair(0,
5698 static_cast<int>(LaneBase + LaneIdx - Shift));
5699 });
5700
5701 case X86::BI__builtin_ia32_psrldqi128_byteshift:
5702 case X86::BI__builtin_ia32_psrldqi256_byteshift:
5703 case X86::BI__builtin_ia32_psrldqi512_byteshift:
5704 // These SRLDQ intrinsics always operate on byte elements (8 bits).
5705 // The lane width is hardcoded to 16 to match the SIMD register size,
5706 // but the algorithm processes one byte per iteration,
5707 // so APInt(8, ...) is correct and intentional.
5708 return interp__builtin_ia32_shuffle_generic(
5709 S, OpPC, Call,
5710 [](unsigned DstIdx, unsigned Shift) -> std::pair<unsigned, int> {
5711 unsigned LaneBase = (DstIdx / 16) * 16;
5712 unsigned LaneIdx = DstIdx % 16;
5713 if (LaneIdx + Shift < 16)
5714 return std::make_pair(0,
5715 static_cast<int>(LaneBase + LaneIdx + Shift));
5716
5717 return std::make_pair(0, -1);
5718 });
5719
5720 case X86::BI__builtin_ia32_palignr128:
5721 case X86::BI__builtin_ia32_palignr256:
5722 case X86::BI__builtin_ia32_palignr512:
5723 return interp__builtin_ia32_shuffle_generic(
5724 S, OpPC, Call, [](unsigned DstIdx, unsigned Shift) {
5725 // Default to -1 → zero-fill this destination element
5726 unsigned VecIdx = 1;
5727 int ElemIdx = -1;
5728
5729 int Lane = DstIdx / 16;
5730 int Offset = DstIdx % 16;
5731
5732 // Elements come from VecB first, then VecA after the shift boundary
5733 unsigned ShiftedIdx = Offset + (Shift & 0xFF);
5734 if (ShiftedIdx < 16) { // from VecB
5735 ElemIdx = ShiftedIdx + (Lane * 16);
5736 } else if (ShiftedIdx < 32) { // from VecA
5737 VecIdx = 0;
5738 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
5739 }
5740
5741 return std::pair<unsigned, int>{VecIdx, ElemIdx};
5742 });
5743
5744 case X86::BI__builtin_ia32_alignd128:
5745 case X86::BI__builtin_ia32_alignd256:
5746 case X86::BI__builtin_ia32_alignd512:
5747 case X86::BI__builtin_ia32_alignq128:
5748 case X86::BI__builtin_ia32_alignq256:
5749 case X86::BI__builtin_ia32_alignq512: {
5750 unsigned NumElems = Call->getType()->castAs<VectorType>()->getNumElements();
5751 return interp__builtin_ia32_shuffle_generic(
5752 S, OpPC, Call, [NumElems](unsigned DstIdx, unsigned Shift) {
5753 unsigned Imm = Shift & 0xFF;
5754 unsigned EffectiveShift = Imm & (NumElems - 1);
5755 unsigned SourcePos = DstIdx + EffectiveShift;
5756 unsigned VecIdx = SourcePos < NumElems ? 1u : 0u;
5757 unsigned ElemIdx = SourcePos & (NumElems - 1);
5758 return std::pair<unsigned, int>{VecIdx, static_cast<int>(ElemIdx)};
5759 });
5760 }
5761
5762 case clang::X86::BI__builtin_ia32_minps:
5763 case clang::X86::BI__builtin_ia32_minpd:
5764 case clang::X86::BI__builtin_ia32_minph128:
5765 case clang::X86::BI__builtin_ia32_minph256:
5766 case clang::X86::BI__builtin_ia32_minps256:
5767 case clang::X86::BI__builtin_ia32_minpd256:
5768 case clang::X86::BI__builtin_ia32_minps512:
5769 case clang::X86::BI__builtin_ia32_minpd512:
5770 case clang::X86::BI__builtin_ia32_minph512:
5771 return interp__builtin_elementwise_fp_binop(
5772 S, OpPC, Call,
5773 [](const APFloat &A, const APFloat &B, std::optional<APSInt>) {
5774 if (A.isZero() && B.isZero())
5775 return B;
5776 return llvm::minimum(A, B);
5777 });
5778
5779 case clang::X86::BI__builtin_ia32_maxps:
5780 case clang::X86::BI__builtin_ia32_maxpd:
5781 case clang::X86::BI__builtin_ia32_maxph128:
5782 case clang::X86::BI__builtin_ia32_maxph256:
5783 case clang::X86::BI__builtin_ia32_maxps256:
5784 case clang::X86::BI__builtin_ia32_maxpd256:
5785 case clang::X86::BI__builtin_ia32_maxps512:
5786 case clang::X86::BI__builtin_ia32_maxpd512:
5787 case clang::X86::BI__builtin_ia32_maxph512:
5788 return interp__builtin_elementwise_fp_binop(
5789 S, OpPC, Call,
5790 [](const APFloat &A, const APFloat &B, std::optional<APSInt>) {
5791 if (A.isZero() && B.isZero())
5792 return B;
5793 return llvm::maximum(A, B);
5794 });
5795
5796 default:
5797 S.FFDiag(S.Current->getLocation(OpPC),
5798 diag::note_invalid_subexpr_in_const_expr)
5799 << S.Current->getRange(OpPC);
5800
5801 return false;
5802 }
5803
5804 llvm_unreachable("Unhandled builtin ID");
5805 }
5806
5807 bool InterpretOffsetOf(InterpState &S, CodePtr OpPC, const OffsetOfExpr *E,
5808 ArrayRef<int64_t> ArrayIndices, int64_t &IntResult) {
5809 CharUnits Result;
5810 unsigned N = E->getNumComponents();
5811 assert(N > 0);
5812
5813 unsigned ArrayIndex = 0;
5814 QualType CurrentType = E->getTypeSourceInfo()->getType();
5815 for (unsigned I = 0; I != N; ++I) {
5816 const OffsetOfNode &Node = E->getComponent(I);
5817 switch (Node.getKind()) {
5818 case OffsetOfNode::Field: {
5819 const FieldDecl *MemberDecl = Node.getField();
5820 const auto *RD = CurrentType->getAsRecordDecl();
5821 if (!RD || RD->isInvalidDecl())
5822 return false;
5823 const ASTRecordLayout &RL = S.getASTContext().getASTRecordLayout(RD);
5824 unsigned FieldIndex = MemberDecl->getFieldIndex();
5825 assert(FieldIndex < RL.getFieldCount() && "offsetof field in wrong type");
5826 Result +=
5827 S.getASTContext().toCharUnitsFromBits(RL.getFieldOffset(FieldIndex));
5828 CurrentType = MemberDecl->getType().getNonReferenceType();
5829 break;
5830 }
5831 case OffsetOfNode::Array: {
5832 // When generating bytecode, we put all the index expressions as Sint64 on
5833 // the stack.
5834 int64_t Index = ArrayIndices[ArrayIndex];
5835 const ArrayType *AT = S.getASTContext().getAsArrayType(CurrentType);
5836 if (!AT)
5837 return false;
5838 CurrentType = AT->getElementType();
5839 CharUnits ElementSize = S.getASTContext().getTypeSizeInChars(CurrentType);
5840 Result += Index * ElementSize;
5841 ++ArrayIndex;
5842 break;
5843 }
5844 case OffsetOfNode::Base: {
5845 const CXXBaseSpecifier *BaseSpec = Node.getBase();
5846 if (BaseSpec->isVirtual())
5847 return false;
5848
5849 // Find the layout of the class whose base we are looking into.
5850 const auto *RD = CurrentType->getAsCXXRecordDecl();
5851 if (!RD || RD->isInvalidDecl())
5852 return false;
5853 const ASTRecordLayout &RL = S.getASTContext().getASTRecordLayout(RD);
5854
5855 // Find the base class itself.
5856 CurrentType = BaseSpec->getType();
5857 const auto *BaseRD = CurrentType->getAsCXXRecordDecl();
5858 if (!BaseRD)
5859 return false;
5860
5861 // Add the offset to the base.
5862 Result += RL.getBaseClassOffset(BaseRD);
5863 break;
5864 }
5865 case OffsetOfNode::Identifier:
5866 llvm_unreachable("Dependent OffsetOfExpr?");
5867 }
5868 }
5869
5870 IntResult = Result.getQuantity();
5871
5872 return true;
5873 }
5874
5875 bool SetThreeWayComparisonField(InterpState &S, CodePtr OpPC,
5876 const Pointer &Ptr, const APSInt &IntValue) {
5877
5878 const Record *R = Ptr.getRecord();
5879 assert(R);
5880 assert(R->getNumFields() == 1);
5881
5882 unsigned FieldOffset = R->getField(0u)->Offset;
5883 const Pointer &FieldPtr = Ptr.atField(FieldOffset);
5884 PrimType FieldT = *S.getContext().classify(FieldPtr.getType());
5885
5886 INT_TYPE_SWITCH(FieldT,
5887 FieldPtr.deref<T>() = T::from(IntValue.getSExtValue()));
5888 FieldPtr.initialize();
5889 return true;
5890 }
5891
5892 static void zeroAll(Pointer &Dest) {
5893 const Descriptor *Desc = Dest.getFieldDesc();
5894
5895 if (Desc->isPrimitive()) {
5896 TYPE_SWITCH(Desc->getPrimType(), {
5897 Dest.deref<T>().~T();
5898 new (&Dest.deref<T>()) T();
5899 });
5900 return;
5901 }
5902
5903 if (Desc->isRecord()) {
5904 const Record *R = Desc->ElemRecord;
5905 for (const Record::Field &F : R->fields()) {
5906 Pointer FieldPtr = Dest.atField(F.Offset);
5907 zeroAll(FieldPtr);
5908 }
5909 return;
5910 }
5911
5912 if (Desc->isPrimitiveArray()) {
5913 for (unsigned I = 0, N = Desc->getNumElems(); I != N; ++I) {
5914 TYPE_SWITCH(Desc->getPrimType(), {
5915 Dest.deref<T>().~T();
5916 new (&Dest.deref<T>()) T();
5917 });
5918 }
5919 return;
5920 }
5921
5922 if (Desc->isCompositeArray()) {
5923 for (unsigned I = 0, N = Desc->getNumElems(); I != N; ++I) {
5924 Pointer ElemPtr = Dest.atIndex(I).narrow();
5925 zeroAll(ElemPtr);
5926 }
5927 return;
5928 }
5929 }
5930
5931 static bool copyComposite(InterpState &S, CodePtr OpPC, const Pointer &Src,
5932 Pointer &Dest, bool Activate);
5933 static bool copyRecord(InterpState &S, CodePtr OpPC, const Pointer &Src,
5934 Pointer &Dest, bool Activate = false) {
5935 [[maybe_unused]] const Descriptor *SrcDesc = Src.getFieldDesc();
5936 const Descriptor *DestDesc = Dest.getFieldDesc();
5937
5938 auto copyField = [&](const Record::Field &F, bool Activate) -> bool {
5939 Pointer DestField = Dest.atField(F.Offset);
5940 if (OptPrimType FT = S.Ctx.classify(F.Decl->getType())) {
5941 TYPE_SWITCH(*FT, {
5942 DestField.deref<T>() = Src.atField(F.Offset).deref<T>();
5943 if (Src.atField(F.Offset).isInitialized())
5944 DestField.initialize();
5945 if (Activate)
5946 DestField.activate();
5947 });
5948 return true;
5949 }
5950 // Composite field.
5951 return copyComposite(S, OpPC, Src.atField(F.Offset), DestField, Activate);
5952 };
5953
5954 assert(SrcDesc->isRecord());
5955 assert(SrcDesc->ElemRecord == DestDesc->ElemRecord);
5956 const Record *R = DestDesc->ElemRecord;
5957 for (const Record::Field &F : R->fields()) {
5958 if (R->isUnion()) {
5959 // For unions, only copy the active field. Zero all others.
5960 const Pointer &SrcField = Src.atField(F.Offset);
5961 if (SrcField.isActive()) {
5962 if (!copyField(F, /*Activate=*/true))
5963 return false;
5964 } else {
5965 if (!CheckMutable(S, OpPC, Src.atField(F.Offset)))
5966 return false;
5967 Pointer DestField = Dest.atField(F.Offset);
5968 zeroAll(DestField);
5969 }
5970 } else {
5971 if (!copyField(F, Activate))
5972 return false;
5973 }
5974 }
5975
5976 for (const Record::Base &B : R->bases()) {
5977 Pointer DestBase = Dest.atField(B.Offset);
5978 if (!copyRecord(S, OpPC, Src.atField(B.Offset), DestBase, Activate))
5979 return false;
5980 }
5981
5982 Dest.initialize();
5983 return true;
5984 }
5985
5986 static bool copyComposite(InterpState &S, CodePtr OpPC, const Pointer &Src,
5987 Pointer &Dest, bool Activate = false) {
5988 assert(Src.isLive() && Dest.isLive());
5989
5990 [[maybe_unused]] const Descriptor *SrcDesc = Src.getFieldDesc();
5991 const Descriptor *DestDesc = Dest.getFieldDesc();
5992
5993 assert(!DestDesc->isPrimitive() && !SrcDesc->isPrimitive());
5994
5995 if (DestDesc->isPrimitiveArray()) {
5996 assert(SrcDesc->isPrimitiveArray());
5997 assert(SrcDesc->getNumElems() == DestDesc->getNumElems());
5998 PrimType ET = DestDesc->getPrimType();
5999 for (unsigned I = 0, N = DestDesc->getNumElems(); I != N; ++I) {
6000 Pointer DestElem = Dest.atIndex(I);
6001 TYPE_SWITCH(ET, {
6002 DestElem.deref<T>() = Src.elem<T>(I);
6003 DestElem.initialize();
6004 });
6005 }
6006 return true;
6007 }
6008
6009 if (DestDesc->isCompositeArray()) {
6010 assert(SrcDesc->isCompositeArray());
6011 assert(SrcDesc->getNumElems() == DestDesc->getNumElems());
6012 for (unsigned I = 0, N = DestDesc->getNumElems(); I != N; ++I) {
6013 const Pointer &SrcElem = Src.atIndex(I).narrow();
6014 Pointer DestElem = Dest.atIndex(I).narrow();
6015 if (!copyComposite(S, OpPC, SrcElem, DestElem, Activate))
6016 return false;
6017 }
6018 return true;
6019 }
6020
6021 if (DestDesc->isRecord())
6022 return copyRecord(S, OpPC, Src, Dest, Activate);
6023 return Invalid(S, OpPC);
6024 }
6025
6026 bool DoMemcpy(InterpState &S, CodePtr OpPC, const Pointer &Src, Pointer &Dest) {
6027 return copyComposite(S, OpPC, Src, Dest);
6028 }
6029
6030 } // namespace interp
6031 } // namespace clang