clang 24.0.0git
CGBuiltin.cpp
Go to the documentation of this file.
1//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Builtin calls as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBuiltin.h"
14#include "ABIInfo.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.h"
17#include "CGDebugInfo.h"
18#include "CGObjCRuntime.h"
19#include "CGOpenCLRuntime.h"
20#include "CGRecordLayout.h"
21#include "CGValue.h"
22#include "CodeGenFunction.h"
23#include "CodeGenModule.h"
24#include "ConstantEmitter.h"
25#include "PatternInit.h"
26#include "TargetInfo.h"
27#include "clang/AST/OSLog.h"
31#include "llvm/ADT/APFloat.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/IntrinsicsX86.h"
36#include "llvm/IR/MatrixBuilder.h"
37#include "llvm/Support/ConvertUTF.h"
38#include "llvm/Support/ScopedPrinter.h"
39#include <algorithm>
40#include <optional>
41#include <utility>
42
43using namespace clang;
44using namespace CodeGen;
45using namespace llvm;
46
47/// Some builtins do not have library implementation on some targets and
48/// are instead emitted as LLVM IRs by some target builtin emitters.
49/// FIXME: Remove this when library support is added
50static bool shouldEmitBuiltinAsIR(unsigned BuiltinID,
51 const Builtin::Context &BI,
52 const CodeGenFunction &CGF) {
53 if (!CGF.CGM.getLangOpts().MathErrno &&
57 switch (BuiltinID) {
58 default:
59 return false;
60 case Builtin::BIlogbf:
61 case Builtin::BI__builtin_logbf:
62 case Builtin::BIlogb:
63 case Builtin::BI__builtin_logb:
64 case Builtin::BIscalbnf:
65 case Builtin::BI__builtin_scalbnf:
66 case Builtin::BIscalbn:
67 case Builtin::BI__builtin_scalbn:
68 return true;
69 }
70 }
71 return false;
72}
73
75 unsigned BuiltinID, const CallExpr *E,
76 ReturnValueSlot ReturnValue,
77 llvm::Triple::ArchType Arch) {
78 // When compiling in HipStdPar mode we have to be conservative in rejecting
79 // target specific features in the FE, and defer the possible error to the
80 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
81 // referenced by an accelerator executable function, we emit an error.
82 // Returning nullptr here leads to the builtin being handled in
83 // EmitStdParUnsupportedBuiltin.
84 if (CGF->getLangOpts().HIPStdPar && CGF->getLangOpts().CUDAIsDevice &&
85 Arch != CGF->getTarget().getTriple().getArch())
86 return nullptr;
87
88 switch (Arch) {
89 case llvm::Triple::arm:
90 case llvm::Triple::armeb:
91 case llvm::Triple::thumb:
92 case llvm::Triple::thumbeb:
93 return CGF->EmitARMBuiltinExpr(BuiltinID, E, ReturnValue, Arch);
94 case llvm::Triple::aarch64:
95 case llvm::Triple::aarch64_32:
96 case llvm::Triple::aarch64_be:
97 return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
98 case llvm::Triple::bpfeb:
99 case llvm::Triple::bpfel:
100 return CGF->EmitBPFBuiltinExpr(BuiltinID, E);
101 case llvm::Triple::dxil:
102 return CGF->EmitDirectXBuiltinExpr(BuiltinID, E);
103 case llvm::Triple::x86:
104 case llvm::Triple::x86_64:
105 return CGF->EmitX86BuiltinExpr(BuiltinID, E);
106 case llvm::Triple::ppc:
107 case llvm::Triple::ppcle:
108 case llvm::Triple::ppc64:
109 case llvm::Triple::ppc64le:
110 return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
111 case llvm::Triple::amdgpu:
112 case llvm::Triple::r600:
113 return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
114 case llvm::Triple::systemz:
115 return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
116 case llvm::Triple::nvptx:
117 case llvm::Triple::nvptx64:
118 return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
119 case llvm::Triple::wasm32:
120 case llvm::Triple::wasm64:
121 return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
122 case llvm::Triple::hexagon:
123 return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
124 case llvm::Triple::riscv32:
125 case llvm::Triple::riscv64:
126 case llvm::Triple::riscv32be:
127 case llvm::Triple::riscv64be:
128 return CGF->EmitRISCVBuiltinExpr(BuiltinID, E, ReturnValue);
129 case llvm::Triple::spirv32:
130 case llvm::Triple::spirv64:
131 if (CGF->getTarget().getTriple().getOS() == llvm::Triple::OSType::AMDHSA)
132 return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
133 [[fallthrough]];
134 case llvm::Triple::spirv:
135 return CGF->EmitSPIRVBuiltinExpr(BuiltinID, E);
136 case llvm::Triple::avr:
137 return CGF->EmitAVRBuiltinExpr(BuiltinID, E);
138 default:
139 return nullptr;
140 }
141}
142
144 const CallExpr *E,
146 if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
147 assert(getContext().getAuxTargetInfo() && "Missing aux target info");
149 this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
150 ReturnValue, getContext().getAuxTargetInfo()->getTriple().getArch());
151 }
152
153 return EmitTargetArchBuiltinExpr(this, BuiltinID, E, ReturnValue,
154 getTarget().getTriple().getArch());
155}
156
157static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
158 Align AlignmentInBytes) {
159 ConstantInt *Byte;
160 switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
162 // Nothing to initialize.
163 return;
165 Byte = CGF.Builder.getInt8(0x00);
166 break;
168 llvm::Type *Int8 = llvm::IntegerType::getInt8Ty(CGF.CGM.getLLVMContext());
169 Byte = llvm::dyn_cast<llvm::ConstantInt>(
170 initializationPatternFor(CGF.CGM, Int8));
171 break;
172 }
173 }
174 if (CGF.CGM.stopAutoInit())
175 return;
176 auto *I = CGF.Builder.CreateMemSet(AI, Byte, Size, AlignmentInBytes);
177 I->addAnnotationMetadata("auto-init");
178}
179
180/// getBuiltinLibFunction - Given a builtin id for a function like
181/// "__builtin_fabsf", return a Function* for "fabsf".
183 unsigned BuiltinID) {
184 assert(Context.BuiltinInfo.isLibFunction(BuiltinID));
185
186 // Get the name, skip over the __builtin_ prefix (if necessary). We may have
187 // to build this up so provide a small stack buffer to handle the vast
188 // majority of names.
190 GlobalDecl D(FD);
191
192 // TODO: This list should be expanded or refactored after all GCC-compatible
193 // std libcall builtins are implemented.
194 static const SmallDenseMap<unsigned, StringRef, 64> F128Builtins{
195 {Builtin::BI__builtin___fprintf_chk, "__fprintf_chkieee128"},
196 {Builtin::BI__builtin___printf_chk, "__printf_chkieee128"},
197 {Builtin::BI__builtin___snprintf_chk, "__snprintf_chkieee128"},
198 {Builtin::BI__builtin___sprintf_chk, "__sprintf_chkieee128"},
199 {Builtin::BI__builtin___vfprintf_chk, "__vfprintf_chkieee128"},
200 {Builtin::BI__builtin___vprintf_chk, "__vprintf_chkieee128"},
201 {Builtin::BI__builtin___vsnprintf_chk, "__vsnprintf_chkieee128"},
202 {Builtin::BI__builtin___vsprintf_chk, "__vsprintf_chkieee128"},
203 {Builtin::BI__builtin_fprintf, "__fprintfieee128"},
204 {Builtin::BI__builtin_printf, "__printfieee128"},
205 {Builtin::BI__builtin_snprintf, "__snprintfieee128"},
206 {Builtin::BI__builtin_sprintf, "__sprintfieee128"},
207 {Builtin::BI__builtin_vfprintf, "__vfprintfieee128"},
208 {Builtin::BI__builtin_vprintf, "__vprintfieee128"},
209 {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128"},
210 {Builtin::BI__builtin_vsprintf, "__vsprintfieee128"},
211 {Builtin::BI__builtin_fscanf, "__fscanfieee128"},
212 {Builtin::BI__builtin_scanf, "__scanfieee128"},
213 {Builtin::BI__builtin_sscanf, "__sscanfieee128"},
214 {Builtin::BI__builtin_vfscanf, "__vfscanfieee128"},
215 {Builtin::BI__builtin_vscanf, "__vscanfieee128"},
216 {Builtin::BI__builtin_vsscanf, "__vsscanfieee128"},
217 {Builtin::BI__builtin_nexttowardf128, "__nexttowardieee128"},
218 };
219
220 // The AIX library functions frexpl, ldexpl, and modfl are for 128-bit
221 // IBM 'long double' (i.e. __ibm128). Map to the 'double' versions
222 // if it is 64-bit 'long double' mode.
223 static const SmallDenseMap<unsigned, StringRef, 4> AIXLongDouble64Builtins{
224 {Builtin::BI__builtin_frexpl, "frexp"},
225 {Builtin::BI__builtin_ldexpl, "ldexp"},
226 {Builtin::BI__builtin_modfl, "modf"},
227 };
228
229 // If the builtin has been declared explicitly with an assembler label,
230 // use the mangled name. This differs from the plain label on platforms
231 // that prefix labels.
232 if (FD->hasAttr<AsmLabelAttr>())
233 Name = getMangledName(D);
234 else {
235 // TODO: This mutation should also be applied to other targets other than
236 // PPC, after backend supports IEEE 128-bit style libcalls.
237 if (getTriple().isPPC64() &&
238 &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() &&
239 F128Builtins.contains(BuiltinID))
240 Name = F128Builtins.lookup(BuiltinID);
241 else if (getTriple().isOSAIX() &&
242 &getTarget().getLongDoubleFormat() ==
243 &llvm::APFloat::IEEEdouble() &&
244 AIXLongDouble64Builtins.contains(BuiltinID))
245 Name = AIXLongDouble64Builtins.lookup(BuiltinID);
246 else
247 Name = Context.BuiltinInfo.getName(BuiltinID).substr(10);
248 }
249
250 llvm::FunctionType *Ty =
251 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
252
253 return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
254}
255
257 llvm::Function *F) {
258 llvm::FunctionType *FTy = F->getFunctionType();
259 unsigned NumParams = FTy->getNumParams();
260 if (Args.size() >= NumParams)
261 return;
262
263 auto [FirstDefault, Defaults] =
264 Intrinsic::getAllDefaultArgValues(F->getIntrinsicID());
265 assert(Args.size() >= FirstDefault &&
266 "builtin passes fewer arguments than the intrinsic requires");
267
268 for (unsigned I = Args.size(); I != NumParams; ++I) {
269 llvm::Type *ParamTy = FTy->getParamType(I);
270 unsigned DefaultIdx = I - FirstDefault;
271 assert(ParamTy->isIntegerTy() &&
272 "intrinsic default arguments must be integer-typed");
273 Args.push_back(llvm::ConstantInt::get(ParamTy, Defaults[DefaultIdx]));
274 }
275}
276
277/// Emit the conversions required to turn the given value into an
278/// integer of the given size.
279Value *EmitToInt(CodeGenFunction &CGF, llvm::Value *V,
280 QualType T, llvm::IntegerType *IntType) {
281 V = CGF.EmitToMemory(V, T);
282
283 if (V->getType()->isPointerTy())
284 return CGF.Builder.CreatePtrToInt(V, IntType);
285
286 assert(V->getType() == IntType);
287 return V;
288}
289
290Value *EmitFromInt(CodeGenFunction &CGF, llvm::Value *V,
291 QualType T, llvm::Type *ResultType) {
292 V = CGF.EmitFromMemory(V, T);
293
294 if (ResultType->isPointerTy())
295 return CGF.Builder.CreateIntToPtr(V, ResultType);
296
297 assert(V->getType() == ResultType);
298 return V;
299}
300
302 ASTContext &Ctx = CGF.getContext();
303 Address Ptr = CGF.EmitPointerWithAlignment(E->getArg(0));
304 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
305 unsigned Bytes = Ptr.getElementType()->isPointerTy()
307 : DL.getTypeStoreSize(Ptr.getElementType());
308 unsigned Align = Ptr.getAlignment().getQuantity();
309 if (Align % Bytes != 0) {
310 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
311 Diags.Report(E->getBeginLoc(), diag::warn_sync_op_misaligned);
312 // Force address to be at least naturally-aligned.
313 return Ptr.withAlignment(CharUnits::fromQuantity(Bytes));
314 }
315 return Ptr;
316}
317
318/// Utility to insert an atomic instruction based on Intrinsic::ID
319/// and the expression node.
321 CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
322 AtomicOrdering Ordering) {
323
324 QualType T = E->getType();
325 assert(E->getArg(0)->getType()->isPointerType());
327 E->getArg(0)->getType()->getPointeeType()));
328 assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
329
330 Address DestAddr = CheckAtomicAlignment(CGF, E);
331
332 llvm::IntegerType *IntType = llvm::IntegerType::get(
333 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
334
335 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(1));
336 llvm::Type *ValueType = Val->getType();
337 Val = EmitToInt(CGF, Val, T, IntType);
338
339 llvm::Value *Result =
340 CGF.Builder.CreateAtomicRMW(Kind, DestAddr, Val, Ordering);
341 // Consider atomics to be volatile in MS kernel mode.
342 if (CGF.CGM.getLangOpts().Kernel)
343 cast<llvm::AtomicRMWInst>(Result)->setVolatile(true);
344 return EmitFromInt(CGF, Result, T, ValueType);
345}
346
348 Value *Val = CGF.EmitScalarExpr(E->getArg(0));
350
351 Val = CGF.EmitToMemory(Val, E->getArg(0)->getType());
352 LValue LV = CGF.MakeAddrLValue(Addr, E->getArg(0)->getType());
353 LV.setNontemporal(true);
354 CGF.EmitStoreOfScalar(Val, LV, false);
355 return nullptr;
356}
357
360
361 LValue LV = CGF.MakeAddrLValue(Addr, E->getType());
362 LV.setNontemporal(true);
363 return CGF.EmitLoadOfScalar(LV, E->getExprLoc());
364}
365
367 llvm::AtomicRMWInst::BinOp Kind,
368 const CallExpr *E) {
369 return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E));
370}
371
372/// Utility to insert an atomic instruction based Intrinsic::ID and
373/// the expression node, where the return value is the result of the
374/// operation.
376 llvm::AtomicRMWInst::BinOp Kind,
377 const CallExpr *E,
378 Instruction::BinaryOps Op,
379 bool Invert = false) {
380 QualType T = E->getType();
381 assert(E->getArg(0)->getType()->isPointerType());
383 E->getArg(0)->getType()->getPointeeType()));
384 assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
385
386 Address DestAddr = CheckAtomicAlignment(CGF, E);
387
388 llvm::IntegerType *IntType = llvm::IntegerType::get(
389 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
390
391 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(1));
392 llvm::Type *ValueType = Val->getType();
393 Val = EmitToInt(CGF, Val, T, IntType);
394
395 llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
396 Kind, DestAddr, Val, llvm::AtomicOrdering::SequentiallyConsistent);
397 Result = CGF.Builder.CreateBinOp(Op, Result, Val);
398 if (Invert)
399 Result =
400 CGF.Builder.CreateBinOp(llvm::Instruction::Xor, Result,
401 llvm::ConstantInt::getAllOnesValue(IntType));
402 Result = EmitFromInt(CGF, Result, T, ValueType);
403 return RValue::get(Result);
404}
405
406/// Utility to insert an atomic cmpxchg instruction.
407///
408/// @param CGF The current codegen function.
409/// @param E Builtin call expression to convert to cmpxchg.
410/// arg0 - address to operate on
411/// arg1 - value to compare with
412/// arg2 - new value
413/// @param ReturnBool Specifies whether to return success flag of
414/// cmpxchg result or the old value.
415///
416/// @returns result of cmpxchg, according to ReturnBool
417///
418/// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics
419/// invoke the function EmitAtomicCmpXchgForMSIntrin.
421 bool ReturnBool,
422 llvm::AtomicOrdering SuccessOrdering,
423 llvm::AtomicOrdering FailureOrdering) {
424 QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType();
425 Address DestAddr = CheckAtomicAlignment(CGF, E);
426
427 llvm::IntegerType *IntType = llvm::IntegerType::get(
428 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
429
430 Value *Cmp = CGF.EmitScalarExpr(E->getArg(1));
431 llvm::Type *ValueType = Cmp->getType();
432 Cmp = EmitToInt(CGF, Cmp, T, IntType);
433 Value *New = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType);
434
436 DestAddr, Cmp, New, SuccessOrdering, FailureOrdering);
437 if (ReturnBool)
438 // Extract boolean success flag and zext it to int.
439 return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1),
440 CGF.ConvertType(E->getType()));
441 else
442 // Extract old value and emit it using the same type as compare value.
443 return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T,
444 ValueType);
445}
446
447/// This function should be invoked to emit atomic cmpxchg for Microsoft's
448/// _InterlockedCompareExchange* intrinsics which have the following signature:
449/// T _InterlockedCompareExchange(T volatile *Destination,
450/// T Exchange,
451/// T Comparand);
452///
453/// Whereas the llvm 'cmpxchg' instruction has the following syntax:
454/// cmpxchg *Destination, Comparand, Exchange.
455/// So we need to swap Comparand and Exchange when invoking
456/// CreateAtomicCmpXchg. That is the reason we could not use the above utility
457/// function MakeAtomicCmpXchgValue since it expects the arguments to be
458/// already swapped.
459
460static
462 AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) {
463 assert(E->getArg(0)->getType()->isPointerType());
465 E->getType(), E->getArg(0)->getType()->getPointeeType()));
466 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
467 E->getArg(1)->getType()));
468 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
469 E->getArg(2)->getType()));
470
471 Address DestAddr = CheckAtomicAlignment(CGF, E);
472
473 auto *Exchange = CGF.EmitScalarExpr(E->getArg(1));
474 auto *RTy = Exchange->getType();
475
476 auto *Comparand = CGF.EmitScalarExpr(E->getArg(2));
477
478 if (RTy->isPointerTy()) {
479 Exchange = CGF.Builder.CreatePtrToInt(Exchange, CGF.IntPtrTy);
480 Comparand = CGF.Builder.CreatePtrToInt(Comparand, CGF.IntPtrTy);
481 }
482
483 // For Release ordering, the failure ordering should be Monotonic.
484 auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ?
485 AtomicOrdering::Monotonic :
486 SuccessOrdering;
487
488 // The atomic instruction is marked volatile for consistency with MSVC. This
489 // blocks the few atomics optimizations that LLVM has. If we want to optimize
490 // _Interlocked* operations in the future, we will have to remove the volatile
491 // marker.
492 auto *CmpXchg = CGF.Builder.CreateAtomicCmpXchg(
493 DestAddr, Comparand, Exchange, SuccessOrdering, FailureOrdering);
494 CmpXchg->setVolatile(true);
495
496 auto *Result = CGF.Builder.CreateExtractValue(CmpXchg, 0);
497 if (RTy->isPointerTy()) {
498 Result = CGF.Builder.CreateIntToPtr(Result, RTy);
499 }
500
501 return Result;
502}
503
504// 64-bit Microsoft platforms support 128 bit cmpxchg operations. They are
505// prototyped like this:
506//
507// unsigned char _InterlockedCompareExchange128...(
508// __int64 volatile * _Destination,
509// __int64 _ExchangeHigh,
510// __int64 _ExchangeLow,
511// __int64 * _ComparandResult);
512//
513// Note that Destination is assumed to be at least 16-byte aligned, despite
514// being typed int64.
515
517 const CallExpr *E,
518 AtomicOrdering SuccessOrdering) {
519 assert(E->getNumArgs() == 4);
520 llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
521 llvm::Value *ExchangeHigh = CGF.EmitScalarExpr(E->getArg(1));
522 llvm::Value *ExchangeLow = CGF.EmitScalarExpr(E->getArg(2));
523 Address ComparandAddr = CGF.EmitPointerWithAlignment(E->getArg(3));
524
525 assert(DestPtr->getType()->isPointerTy());
526 assert(!ExchangeHigh->getType()->isPointerTy());
527 assert(!ExchangeLow->getType()->isPointerTy());
528
529 // For Release ordering, the failure ordering should be Monotonic.
530 auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release
531 ? AtomicOrdering::Monotonic
532 : SuccessOrdering;
533
534 // Convert to i128 pointers and values. Alignment is also overridden for
535 // destination pointer.
536 llvm::Type *Int128Ty = llvm::IntegerType::get(CGF.getLLVMContext(), 128);
537 Address DestAddr(DestPtr, Int128Ty,
539 ComparandAddr = ComparandAddr.withElementType(Int128Ty);
540
541 // (((i128)hi) << 64) | ((i128)lo)
542 ExchangeHigh = CGF.Builder.CreateZExt(ExchangeHigh, Int128Ty);
543 ExchangeLow = CGF.Builder.CreateZExt(ExchangeLow, Int128Ty);
544 ExchangeHigh =
545 CGF.Builder.CreateShl(ExchangeHigh, llvm::ConstantInt::get(Int128Ty, 64));
546 llvm::Value *Exchange = CGF.Builder.CreateOr(ExchangeHigh, ExchangeLow);
547
548 // Load the comparand for the instruction.
549 llvm::Value *Comparand = CGF.Builder.CreateLoad(ComparandAddr);
550
551 auto *CXI = CGF.Builder.CreateAtomicCmpXchg(DestAddr, Comparand, Exchange,
552 SuccessOrdering, FailureOrdering);
553
554 // The atomic instruction is marked volatile for consistency with MSVC. This
555 // blocks the few atomics optimizations that LLVM has. If we want to optimize
556 // _Interlocked* operations in the future, we will have to remove the volatile
557 // marker.
558 CXI->setVolatile(true);
559
560 // Store the result as an outparameter.
561 CGF.Builder.CreateStore(CGF.Builder.CreateExtractValue(CXI, 0),
562 ComparandAddr);
563
564 // Get the success boolean and zero extend it to i8.
565 Value *Success = CGF.Builder.CreateExtractValue(CXI, 1);
566 return CGF.Builder.CreateZExt(Success, CGF.Int8Ty);
567}
568
570 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
571 assert(E->getArg(0)->getType()->isPointerType());
572
573 auto *IntTy = CGF.ConvertType(E->getType());
574 Address DestAddr = CheckAtomicAlignment(CGF, E);
575 auto *Result = CGF.Builder.CreateAtomicRMW(
576 AtomicRMWInst::Add, DestAddr, ConstantInt::get(IntTy, 1), Ordering);
577 return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1));
578}
579
581 CodeGenFunction &CGF, const CallExpr *E,
582 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
583 assert(E->getArg(0)->getType()->isPointerType());
584
585 auto *IntTy = CGF.ConvertType(E->getType());
586 Address DestAddr = CheckAtomicAlignment(CGF, E);
587 auto *Result = CGF.Builder.CreateAtomicRMW(
588 AtomicRMWInst::Sub, DestAddr, ConstantInt::get(IntTy, 1), Ordering);
589 return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1));
590}
591
592// Build a plain volatile load.
594 Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
595 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
596 CharUnits LoadSize = CGF.getContext().getTypeSizeInChars(ElTy);
597 llvm::Type *ITy =
598 llvm::IntegerType::get(CGF.getLLVMContext(), LoadSize.getQuantity() * 8);
599 llvm::LoadInst *Load = CGF.Builder.CreateAlignedLoad(ITy, Ptr, LoadSize);
600 Load->setAtomic(llvm::AtomicOrdering::Monotonic);
601 Load->setVolatile(true);
602 return Load;
603}
604
605// Build a plain volatile store.
607 Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
608 Value *Value = CGF.EmitScalarExpr(E->getArg(1));
609 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
610 CharUnits StoreSize = CGF.getContext().getTypeSizeInChars(ElTy);
611 llvm::StoreInst *Store =
612 CGF.Builder.CreateAlignedStore(Value, Ptr, StoreSize);
613 Store->setAtomic(llvm::AtomicOrdering::Monotonic);
614 Store->setVolatile(true);
615 return Store;
616}
617
618// Emit a simple mangled intrinsic that has 1 argument and a return type
619// matching the argument type. Depending on mode, this may be a constrained
620// floating-point intrinsic.
622 const CallExpr *E, unsigned IntrinsicID,
623 unsigned ConstrainedIntrinsicID) {
624 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
625
626 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
627 if (CGF.Builder.getIsFPConstrained()) {
628 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
629 return CGF.Builder.CreateConstrainedFPCall(F, { Src0 });
630 } else {
631 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
632 return CGF.Builder.CreateCall(F, Src0);
633 }
634}
635
636// Emit an intrinsic that has 2 operands of the same type as its result.
637// Depending on mode, this may be a constrained floating-point intrinsic.
639 const CallExpr *E, unsigned IntrinsicID,
640 unsigned ConstrainedIntrinsicID) {
641 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
642 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
643
644 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
645 if (CGF.Builder.getIsFPConstrained()) {
646 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
647 return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1 });
648 } else {
649 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
650 return CGF.Builder.CreateCall(F, { Src0, Src1 });
651 }
652}
653
654// Has second type mangled argument.
655static Value *
657 Intrinsic::ID IntrinsicID,
658 Intrinsic::ID ConstrainedIntrinsicID) {
659 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
660 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
661
662 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
663 if (CGF.Builder.getIsFPConstrained()) {
664 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
665 {Src0->getType(), Src1->getType()});
666 return CGF.Builder.CreateConstrainedFPCall(F, {Src0, Src1});
667 }
668
669 Function *F =
670 CGF.CGM.getIntrinsic(IntrinsicID, {Src0->getType(), Src1->getType()});
671 return CGF.Builder.CreateCall(F, {Src0, Src1});
672}
673
674// Emit an intrinsic that has 3 operands of the same type as its result.
675// Depending on mode, this may be a constrained floating-point intrinsic.
677 const CallExpr *E, unsigned IntrinsicID,
678 unsigned ConstrainedIntrinsicID) {
679 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
680 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
681 llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
682
683 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
684 if (CGF.Builder.getIsFPConstrained()) {
685 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
686 return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1, Src2 });
687 } else {
688 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
689 return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
690 }
691}
692
693// Emit an intrinsic that has overloaded integer result and fp operand.
694static Value *
696 unsigned IntrinsicID,
697 unsigned ConstrainedIntrinsicID) {
698 llvm::Type *ResultType = CGF.ConvertType(E->getType());
699 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
700
701 if (CGF.Builder.getIsFPConstrained()) {
702 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
703 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
704 {ResultType, Src0->getType()});
705 return CGF.Builder.CreateConstrainedFPCall(F, {Src0});
706 } else {
707 Function *F =
708 CGF.CGM.getIntrinsic(IntrinsicID, {ResultType, Src0->getType()});
709 return CGF.Builder.CreateCall(F, Src0);
710 }
711}
712
714 Intrinsic::ID IntrinsicID) {
715 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
716 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
717
718 QualType IntPtrTy = E->getArg(1)->getType()->getPointeeType();
719 llvm::Type *IntTy = CGF.ConvertType(IntPtrTy);
720 llvm::Function *F =
721 CGF.CGM.getIntrinsic(IntrinsicID, {Src0->getType(), IntTy});
722 llvm::Value *Call = CGF.Builder.CreateCall(F, Src0);
723
724 llvm::Value *Exp = CGF.Builder.CreateExtractValue(Call, 1);
725 LValue LV = CGF.MakeNaturalAlignAddrLValue(Src1, IntPtrTy);
726 CGF.EmitStoreOfScalar(Exp, LV);
727
728 return CGF.Builder.CreateExtractValue(Call, 0);
729}
730
731static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E,
732 Intrinsic::ID IntrinsicID) {
733 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0));
734 llvm::Value *Dest0 = CGF.EmitScalarExpr(E->getArg(1));
735 llvm::Value *Dest1 = CGF.EmitScalarExpr(E->getArg(2));
736
737 llvm::Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {Val->getType()});
738 llvm::Value *Call = CGF.Builder.CreateCall(F, Val);
739
740 llvm::Value *SinResult = CGF.Builder.CreateExtractValue(Call, 0);
741 llvm::Value *CosResult = CGF.Builder.CreateExtractValue(Call, 1);
742
743 QualType DestPtrType = E->getArg(1)->getType()->getPointeeType();
744 LValue SinLV = CGF.MakeNaturalAlignAddrLValue(Dest0, DestPtrType);
745 LValue CosLV = CGF.MakeNaturalAlignAddrLValue(Dest1, DestPtrType);
746
747 llvm::StoreInst *StoreSin =
748 CGF.Builder.CreateStore(SinResult, SinLV.getAddress());
749 llvm::StoreInst *StoreCos =
750 CGF.Builder.CreateStore(CosResult, CosLV.getAddress());
751
752 // Mark the two stores as non-aliasing with each other. The order of stores
753 // emitted by this builtin is arbitrary, enforcing a particular order will
754 // prevent optimizations later on.
755 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
756 MDNode *Domain = MDHelper.createAnonymousAliasScopeDomain();
757 MDNode *AliasScope = MDHelper.createAnonymousAliasScope(Domain);
758 MDNode *AliasScopeList = MDNode::get(Call->getContext(), AliasScope);
759 StoreSin->setMetadata(LLVMContext::MD_alias_scope, AliasScopeList);
760 StoreCos->setMetadata(LLVMContext::MD_noalias, AliasScopeList);
761}
762
763static llvm::Value *emitModfBuiltin(CodeGenFunction &CGF, const CallExpr *E,
764 Intrinsic::ID IntrinsicID) {
765 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0));
766 llvm::Value *IntPartDest = CGF.EmitScalarExpr(E->getArg(1));
767
768 llvm::Value *Call =
769 CGF.Builder.CreateIntrinsic(IntrinsicID, {Val->getType()}, Val);
770
771 llvm::Value *FractionalResult = CGF.Builder.CreateExtractValue(Call, 0);
772 llvm::Value *IntegralResult = CGF.Builder.CreateExtractValue(Call, 1);
773
774 QualType DestPtrType = E->getArg(1)->getType()->getPointeeType();
775 LValue IntegralLV = CGF.MakeNaturalAlignAddrLValue(IntPartDest, DestPtrType);
776 CGF.EmitStoreOfScalar(IntegralResult, IntegralLV);
777
778 return FractionalResult;
779}
780
781/// EmitFAbs - Emit a call to @llvm.fabs().
783 llvm::Value *Call = CGF.Builder.CreateFAbs(V);
784 if (auto *CallI = dyn_cast<llvm::CallInst>(Call))
785 CallI->setDoesNotAccessMemory();
786 return Call;
787}
788
789/// Emit the computation of the sign bit for a floating point value. Returns
790/// the i1 sign bit value.
792 LLVMContext &C = CGF.CGM.getLLVMContext();
793
794 llvm::Type *Ty = V->getType();
795 int Width = Ty->getPrimitiveSizeInBits();
796 llvm::Type *IntTy = llvm::IntegerType::get(C, Width);
797 V = CGF.Builder.CreateBitCast(V, IntTy);
798 if (Ty->isPPC_FP128Ty()) {
799 // We want the sign bit of the higher-order double. The bitcast we just
800 // did works as if the double-double was stored to memory and then
801 // read as an i128. The "store" will put the higher-order double in the
802 // lower address in both little- and big-Endian modes, but the "load"
803 // will treat those bits as a different part of the i128: the low bits in
804 // little-Endian, the high bits in big-Endian. Therefore, on big-Endian
805 // we need to shift the high bits down to the low before truncating.
806 Width >>= 1;
807 if (CGF.getTarget().isBigEndian()) {
808 Value *ShiftCst = llvm::ConstantInt::get(IntTy, Width);
809 V = CGF.Builder.CreateLShr(V, ShiftCst);
810 }
811 // We are truncating value in order to extract the higher-order
812 // double, which we will be using to extract the sign from.
813 IntTy = llvm::IntegerType::get(C, Width);
814 V = CGF.Builder.CreateTrunc(V, IntTy);
815 }
816 Value *Zero = llvm::Constant::getNullValue(IntTy);
817 return CGF.Builder.CreateICmpSLT(V, Zero);
818}
819
821 const CallExpr *E, llvm::Constant *calleeValue) {
822 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
823 CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
824 llvm::CallBase *callOrInvoke = nullptr;
825 CGFunctionInfo const *FnInfo = nullptr;
826 return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot(),
827 /*Chain=*/nullptr, &callOrInvoke, &FnInfo);
828}
829
830/// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
831/// depending on IntrinsicID.
832///
833/// \arg CGF The current codegen function.
834/// \arg IntrinsicID The ID for the Intrinsic we wish to generate.
835/// \arg X The first argument to the llvm.*.with.overflow.*.
836/// \arg Y The second argument to the llvm.*.with.overflow.*.
837/// \arg Carry The carry returned by the llvm.*.with.overflow.*.
838/// \returns The result (i.e. sum/product) returned by the intrinsic.
840 const Intrinsic::ID IntrinsicID,
841 llvm::Value *X, llvm::Value *Y,
842 llvm::Value *&Carry) {
843 // Make sure we have integers of the same width.
844 assert(X->getType() == Y->getType() &&
845 "Arguments must be the same type. (Did you forget to make sure both "
846 "arguments have the same integer width?)");
847
848 Function *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType());
849 llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, {X, Y});
850 Carry = CGF.Builder.CreateExtractValue(Tmp, 1);
851 return CGF.Builder.CreateExtractValue(Tmp, 0);
852}
853
854namespace {
855 struct WidthAndSignedness {
856 unsigned Width;
857 bool Signed;
858 };
859}
860
861static WidthAndSignedness
863 const clang::QualType Type) {
864 assert(Type->isIntegerType() && "Given type is not an integer.");
865 unsigned Width = context.getIntWidth(Type);
867 return {Width, Signed};
868}
869
870// Given one or more integer types, this function produces an integer type that
871// encompasses them: any value in one of the given types could be expressed in
872// the encompassing type.
873static struct WidthAndSignedness
874EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) {
875 assert(Types.size() > 0 && "Empty list of types.");
876
877 // If any of the given types is signed, we must return a signed type.
878 bool Signed = false;
879 for (const auto &Type : Types) {
880 Signed |= Type.Signed;
881 }
882
883 // The encompassing type must have a width greater than or equal to the width
884 // of the specified types. Additionally, if the encompassing type is signed,
885 // its width must be strictly greater than the width of any unsigned types
886 // given.
887 unsigned Width = 0;
888 for (const auto &Type : Types) {
889 unsigned MinWidth = Type.Width + (Signed && !Type.Signed);
890 if (Width < MinWidth) {
891 Width = MinWidth;
892 }
893 }
894
895 return {Width, Signed};
896}
897
898Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) {
899 Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend;
900 return Builder.CreateCall(CGM.getIntrinsic(inst, {ArgValue->getType()}),
901 ArgValue);
902}
903
904/// Checks if using the result of __builtin_object_size(p, @p From) in place of
905/// __builtin_object_size(p, @p To) is correct
906static bool areBOSTypesCompatible(int From, int To) {
907 // Note: Our __builtin_object_size implementation currently treats Type=0 and
908 // Type=2 identically. Encoding this implementation detail here may make
909 // improving __builtin_object_size difficult in the future, so it's omitted.
910 return From == To || (From == 0 && To == 1) || (From == 3 && To == 2);
911}
912
913static llvm::Value *
914getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) {
915 return ConstantInt::get(ResType, (Type & 2) ? 0 : -1, /*isSigned=*/true);
916}
917
918llvm::Value *
919CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
920 llvm::IntegerType *ResType,
921 llvm::Value *EmittedE,
922 bool IsDynamic) {
923 if (std::optional<uint64_t> ObjectSize =
925 return ConstantInt::get(ResType, *ObjectSize, /*isSigned=*/true);
926 return emitBuiltinObjectSize(E, Type, ResType, EmittedE, IsDynamic);
927}
928
929/// Find a struct's flexible array member. It may be embedded inside multiple
930/// sub-structs, but must still be the last field.
932 ASTContext &Ctx,
933 const RecordDecl *RD) {
934 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
935 CGF.getLangOpts().getStrictFlexArraysLevel();
936
937 if (RD->isImplicit())
938 return nullptr;
939
940 for (const FieldDecl *FD : RD->fields()) {
942 Ctx, FD, FD->getType(), StrictFlexArraysLevel,
943 /*IgnoreTemplateOrMacroSubstitution=*/true))
944 return FD;
945
946 if (const auto *RD = FD->getType()->getAsRecordDecl())
947 if (const FieldDecl *FD = FindFlexibleArrayMemberField(CGF, Ctx, RD))
948 return FD;
949 }
950
951 return nullptr;
952}
953
954/// Calculate the offset of a struct field. It may be embedded inside multiple
955/// sub-structs.
956static bool GetFieldOffset(ASTContext &Ctx, const RecordDecl *RD,
957 const FieldDecl *FD, int64_t &Offset) {
958 if (RD->isImplicit())
959 return false;
960
961 // Keep track of the field number ourselves, because the other methods
962 // (CGRecordLayout::getLLVMFieldNo) aren't always equivalent to how the AST
963 // is laid out.
964 uint32_t FieldNo = 0;
965 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
966
967 for (const FieldDecl *Field : RD->fields()) {
968 if (Field == FD) {
969 Offset += Layout.getFieldOffset(FieldNo);
970 return true;
971 }
972
973 if (const auto *RD = Field->getType()->getAsRecordDecl()) {
974 if (GetFieldOffset(Ctx, RD, FD, Offset)) {
975 Offset += Layout.getFieldOffset(FieldNo);
976 return true;
977 }
978 }
979
980 if (!RD->isUnion())
981 ++FieldNo;
982 }
983
984 return false;
985}
986
987static std::optional<int64_t>
988GetFieldOffset(ASTContext &Ctx, const RecordDecl *RD, const FieldDecl *FD) {
989 int64_t Offset = 0;
990
991 if (GetFieldOffset(Ctx, RD, FD, Offset))
992 return std::optional<int64_t>(Offset);
993
994 return std::nullopt;
995}
996
997llvm::Value *CodeGenFunction::emitCountedBySize(const Expr *E,
998 llvm::Value *EmittedE,
999 unsigned Type,
1000 llvm::IntegerType *ResType) {
1001 // Note: If the whole struct is specificed in the __bdos (i.e. Visitor
1002 // returns a DeclRefExpr). The calculation of the whole size of the structure
1003 // with a flexible array member can be done in two ways:
1004 //
1005 // 1) sizeof(struct S) + count * sizeof(typeof(fam))
1006 // 2) offsetof(struct S, fam) + count * sizeof(typeof(fam))
1007 //
1008 // The first will add additional padding after the end of the array
1009 // allocation while the second method is more precise, but not quite expected
1010 // from programmers. See
1011 // https://lore.kernel.org/lkml/ZvV6X5FPBBW7CO1f@archlinux/ for a discussion
1012 // of the topic.
1013 //
1014 // GCC isn't (currently) able to calculate __bdos on a pointer to the whole
1015 // structure. Therefore, because of the above issue, we choose to match what
1016 // GCC does for consistency's sake.
1017
1018 const Expr *Idx = nullptr;
1019 // FIXME: `ArrayElementTy` is misleadingly named. `findStructFieldAccess()`
1020 // sets it to the type of the array-subscript base, i.e. the (possibly cast)
1021 // *pointer* being indexed (not an element type) or a null QualType when there
1022 // is no subscript.
1023 QualType ArrayElementTy;
1024 E = findStructFieldAccess(E, &Idx, &ArrayElementTy);
1025 if (!E)
1026 return nullptr;
1027
1028 if (Idx) {
1029 if (Idx->HasSideEffects(getContext()))
1030 // We can't have side-effects.
1031 return getDefaultBuiltinObjectSizeResult(Type, ResType);
1032
1033 if (const auto *IL = dyn_cast<IntegerLiteral>(Idx)) {
1034 int64_t Val = IL->getValue().getSExtValue();
1035 if (Val < 0)
1036 return getDefaultBuiltinObjectSizeResult(Type, ResType);
1037
1038 // The index is 0, so we don't need to take it into account.
1039 if (Val == 0)
1040 Idx = nullptr;
1041 }
1042 }
1043
1044 // __counted_by on either a flexible array member or a pointer into a struct
1045 // with a flexible array member.
1046 if (const auto *ME = dyn_cast<MemberExpr>(E))
1047 return emitCountedByMemberSize(ME, Idx, EmittedE, ArrayElementTy, Type,
1048 ResType);
1049
1050 // __counted_by on a pointer in a struct.
1051 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
1052 ICE && ICE->getCastKind() == CK_LValueToRValue)
1053 return emitCountedByPointerSize(ICE, Idx, EmittedE, ArrayElementTy, Type,
1054 ResType);
1055
1056 return nullptr;
1057}
1058
1060 llvm::Value *Res,
1061 llvm::Value *Index,
1062 llvm::IntegerType *ResType,
1063 bool IsSigned) {
1064 // cmp = (array_size >= 0)
1065 Value *Cmp = CGF.Builder.CreateIsNotNeg(Res);
1066 if (Index)
1067 // cmp = (cmp && index >= 0)
1068 Cmp = CGF.Builder.CreateAnd(CGF.Builder.CreateIsNotNeg(Index), Cmp);
1069
1070 // return cmp ? result : 0
1071 return CGF.Builder.CreateSelect(Cmp, Res,
1072 ConstantInt::get(ResType, 0, IsSigned));
1073}
1074
1075static std::pair<llvm::Value *, llvm::Value *>
1077 const FieldDecl *ArrayFD, const FieldDecl *CountFD,
1078 const Expr *Idx, llvm::IntegerType *ResType,
1079 bool IsSigned) {
1080 // count = ptr->count;
1081 Value *Count = CGF.EmitLoadOfCountedByField(ME, ArrayFD, CountFD);
1082 if (!Count)
1083 return std::make_pair<Value *>(nullptr, nullptr);
1084 Count = CGF.Builder.CreateIntCast(Count, ResType, IsSigned, "count");
1085
1086 // index = idx;
1087 Value *Index = nullptr;
1088 if (Idx) {
1089 bool IdxSigned = Idx->getType()->isSignedIntegerType();
1090 Index = CGF.EmitScalarExpr(Idx);
1091 Index = CGF.Builder.CreateIntCast(Index, ResType, IdxSigned, "index");
1092 }
1093
1094 return std::make_pair(Count, Index);
1095}
1096
1097llvm::Value *CodeGenFunction::emitCountedByPointerSize(
1098 const ImplicitCastExpr *E, const Expr *Idx, llvm::Value *EmittedE,
1099 QualType CastedArrayElementTy, unsigned Type, llvm::IntegerType *ResType) {
1100 assert(E->getCastKind() == CK_LValueToRValue &&
1101 "must be an LValue to RValue cast");
1102 assert(EmittedE && "emitted must not be null");
1103
1104 const MemberExpr *ME =
1105 dyn_cast<MemberExpr>(E->getSubExpr()->IgnoreParenNoopCasts(getContext()));
1106 if (!ME)
1107 return nullptr;
1108
1109 const auto *ArrayBaseFD = dyn_cast<FieldDecl>(ME->getMemberDecl());
1110 if (!ArrayBaseFD || !ArrayBaseFD->getType()->isPointerType() ||
1111 !ArrayBaseFD->getType()->isCountAttributedType())
1112 return nullptr;
1113
1114 // Get the 'count' FieldDecl.
1115 const FieldDecl *CountFD = ArrayBaseFD->findCountedByField();
1116 if (!CountFD)
1117 // Can't find the field referenced by the "counted_by" attribute.
1118 return nullptr;
1119
1120 // Calculate the array's object size using these formulae. (Note: if the
1121 // calculation is negative, we return 0.):
1122 //
1123 // struct p;
1124 // struct s {
1125 // /* ... */
1126 // struct p **array __attribute__((ATTR(count)));
1127 // int count;
1128 // };
1129 //
1130 // 1) 'ptr->array':
1131 //
1132 // #if ATTR is counted_by_or_null || ATTR is sized_by_or_null
1133 // count = ptr->array ? ptr->count : 0;
1134 // #else
1135 // count = ptr->count;
1136 // #endif
1137 //
1138 // #if ATTR is counted_by || ATTR is counted_by_or_null
1139 // array_element_size = sizeof (*ptr->array);
1140 // array_size = count * array_element_size;
1141 // #else
1142 // array_size = count;
1143 // #endif
1144 //
1145 // result = array_size;
1146 //
1147 // cmp = (result >= 0)
1148 // return cmp ? result : 0;
1149 //
1150 // 2) '&((cast) ptr->array)[idx]':
1151 //
1152 // #if ATTR is counted_by_or_null || ATTR is sized_by_or_null
1153 // count = ptr->array ? ptr->count : 0;
1154 // #else
1155 // count = ptr->count;
1156 // #endif
1157 // index = idx;
1158 //
1159 // #if ATTR is counted_by || ATTR is counted_by_or_null
1160 // array_element_size = sizeof (*ptr->array);
1161 // array_size = count * array_element_size;
1162 // #else
1163 // array_size = count;
1164 // #endif
1165 //
1166 // casted_array_element_size = sizeof (*((cast) ptr->array));
1167 //
1168 // index_size = index * casted_array_element_size;
1169 // result = array_size - index_size;
1170 //
1171 // cmp = (result >= 0)
1172 // if (index)
1173 // cmp = (cmp && index > 0)
1174 // return cmp ? result : 0;
1175
1176 auto GetPointeeSize = [&](QualType PtrTy) -> CharUnits {
1177 assert(!PtrTy.isNull());
1178 QualType PointeeTy = PtrTy->getPointeeType();
1179 assert(!PointeeTy.isNull() &&
1180 (PointeeTy->isVoidType() || !PointeeTy->isIncompleteType()) &&
1181 "pointee type must have a computable size");
1182
1183 CharUnits PointeeSize = getContext().getTypeSizeInChars(PointeeTy);
1184 if (PointeeSize.isZero()) {
1185 // Support GNU extension of treating `void` having size 1.
1186 PointeeSize = CharUnits::One();
1187 }
1188
1189 return PointeeSize;
1190 };
1191
1192 bool IsSigned = CountFD->getType()->isSignedIntegerType();
1193 const auto *CountAttributedTy =
1194 ArrayBaseFD->getType()->getAs<CountAttributedType>();
1195 assert(CountAttributedTy && "the field's type is not a CountAttributedType");
1196
1197 // count = ptr->count;
1198 // index = idx;
1199 Value *Count, *Index;
1200 std::tie(Count, Index) = GetCountFieldAndIndex(
1201 *this, ME, ArrayBaseFD, CountFD, Idx, ResType, IsSigned);
1202 if (!Count)
1203 return nullptr;
1204
1205 // For the _or_null variants, a null pointer describes no accessible memory:
1206 // count = ptr->array ? count : 0;
1207 if (CountAttributedTy->isOrNull()) {
1208 Value *Ptr = nullptr;
1209 if (!Idx) {
1210 // 1) 'ptr->array'
1211 // Reuse the already-emitted pointer value rather than re-loading `ME`.
1212 // Re-loading would produce a second, observable access for a volatile
1213 // pointer field
1214 Ptr = EmittedE;
1215 } else {
1216 // 2) '&((cast) ptr->array)[idx]'
1217 // FIXME: `EmittedE` is the element address, not `ptr->array`, so we fall
1218 // back to re-emitting `ME` and the pointer field is loaded twice. This is
1219 // normally harmless except when the pointer is `volatile`. Avoiding that
1220 // would require restructuring how the base pointer is emitted (it is
1221 // handled elsewhere in the callstack), so it is left as-is for now.
1222 Ptr = EmitScalarExpr(ME);
1223 }
1224 Value *IsNull = Builder.CreateIsNull(Ptr);
1225 Count = Builder.CreateSelect(IsNull, ConstantInt::get(ResType, 0, IsSigned),
1226 Count, "count.or.null");
1227 }
1228
1229 // #if ATTR is counted_by || ATTR is counted_by_or_null
1230 // array_element_size = sizeof (*ptr->array);
1231 // array_size = count * array_element_size;
1232 // #else
1233 // array_size = count;
1234 // #endif
1235 Value *ArraySize;
1236 if (!CountAttributedTy->isCountInBytes()) {
1237 // `__counted_by`/`__counted_by_or_null` require a complete pointee at use
1238 // sites (enforced by Sema) so the element size is computable.
1239 CharUnits ArrayElementBaseSize = GetPointeeSize(ArrayBaseFD->getType());
1240
1241 // array_element_size = sizeof (*ptr->array)
1242 auto *ArrayElementSize = llvm::ConstantInt::get(
1243 ResType, ArrayElementBaseSize.getQuantity(), IsSigned);
1244
1245 // array_size = count * array_element_size;
1246 ArraySize = Builder.CreateMul(Count, ArrayElementSize, "array_size",
1247 !IsSigned, IsSigned);
1248 } else {
1249 // array_size = count;
1250 ArraySize = Count;
1251 }
1252
1253 // Option (1) 'ptr->array'
1254 // result = array_size
1255 Value *Result = ArraySize;
1256
1257 if (Idx) { // Option (2) '&((cast) ptr->array)[idx]'
1258 // FIXME: CastedArrayElementTy is confusingly named. It's actually the base
1259 // expression of the ArraySubscriptExpr, not the element (pointee) type.
1260 CharUnits CastedArrayElementSizeInChars =
1261 GetPointeeSize(CastedArrayElementTy);
1262
1263 // casted_array_element_size = sizeof (*((cast) ptr->array));
1264 auto *CastedArrayElementSize = llvm::ConstantInt::get(
1265 ResType, CastedArrayElementSizeInChars.getQuantity(), IsSigned);
1266
1267 // index_size = index * casted_array_element_size;
1268 Value *IndexSize = Builder.CreateMul(Index, CastedArrayElementSize,
1269 "index_size", !IsSigned, IsSigned);
1270
1271 // result = result - index_size;
1272 Result =
1273 Builder.CreateSub(Result, IndexSize, "result", !IsSigned, IsSigned);
1274 }
1275
1276 return EmitPositiveResultOrZero(*this, Result, Index, ResType, IsSigned);
1277}
1278
1279llvm::Value *CodeGenFunction::emitCountedByMemberSize(
1280 const MemberExpr *ME, const Expr *Idx, llvm::Value *EmittedE,
1281 QualType CastedArrayElementTy, unsigned Type, llvm::IntegerType *ResType) {
1282 const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
1283 if (!FD)
1284 return nullptr;
1285
1286 // Find the flexible array member and check that it has the __counted_by
1287 // attribute.
1288 ASTContext &Ctx = getContext();
1289 const RecordDecl *RD = FD->getDeclContext()->getOuterLexicalRecordContext();
1290 const FieldDecl *FlexibleArrayMemberFD = nullptr;
1291
1293 Ctx, FD, FD->getType(), getLangOpts().getStrictFlexArraysLevel(),
1294 /*IgnoreTemplateOrMacroSubstitution=*/true))
1295 FlexibleArrayMemberFD = FD;
1296 else
1297 FlexibleArrayMemberFD = FindFlexibleArrayMemberField(*this, Ctx, RD);
1298
1299 if (!FlexibleArrayMemberFD ||
1300 !FlexibleArrayMemberFD->getType()->isCountAttributedType())
1301 return nullptr;
1302
1303 // Get the 'count' FieldDecl.
1304 const FieldDecl *CountFD = FlexibleArrayMemberFD->findCountedByField();
1305 if (!CountFD)
1306 // Can't find the field referenced by the "counted_by" attribute.
1307 return nullptr;
1308
1309 // Calculate the flexible array member's object size using these formulae.
1310 // (Note: if the calculation is negative, we return 0.):
1311 //
1312 // struct p;
1313 // struct s {
1314 // /* ... */
1315 // int count;
1316 // struct p *array[] __attribute__((counted_by(count)));
1317 // };
1318 //
1319 // 1) 'ptr->array':
1320 //
1321 // count = ptr->count;
1322 //
1323 // flexible_array_member_element_size = sizeof (*ptr->array);
1324 // flexible_array_member_size =
1325 // count * flexible_array_member_element_size;
1326 //
1327 // result = flexible_array_member_size;
1328 //
1329 // cmp = (result >= 0)
1330 // return cmp ? result : 0;
1331 //
1332 // 2) '&((cast) ptr->array)[idx]':
1333 //
1334 // count = ptr->count;
1335 // index = idx;
1336 //
1337 // flexible_array_member_element_size = sizeof (*ptr->array);
1338 // flexible_array_member_size =
1339 // count * flexible_array_member_element_size;
1340 //
1341 // casted_flexible_array_member_element_size =
1342 // sizeof (*((cast) ptr->array));
1343 // index_size = index * casted_flexible_array_member_element_size;
1344 //
1345 // result = flexible_array_member_size - index_size;
1346 //
1347 // cmp = (result >= 0)
1348 // if (index != 0)
1349 // cmp = (cmp && index >= 0)
1350 // return cmp ? result : 0;
1351 //
1352 // 3) '&ptr->field':
1353 //
1354 // count = ptr->count;
1355 // sizeof_struct = sizeof (struct s);
1356 //
1357 // flexible_array_member_element_size = sizeof (*ptr->array);
1358 // flexible_array_member_size =
1359 // count * flexible_array_member_element_size;
1360 //
1361 // field_offset = offsetof (struct s, field);
1362 // offset_diff = sizeof_struct - field_offset;
1363 //
1364 // result = offset_diff + flexible_array_member_size;
1365 //
1366 // cmp = (result >= 0)
1367 // return cmp ? result : 0;
1368 //
1369 // 4) '&((cast) ptr->field_array)[idx]':
1370 //
1371 // count = ptr->count;
1372 // index = idx;
1373 // sizeof_struct = sizeof (struct s);
1374 //
1375 // flexible_array_member_element_size = sizeof (*ptr->array);
1376 // flexible_array_member_size =
1377 // count * flexible_array_member_element_size;
1378 //
1379 // casted_field_element_size = sizeof (*((cast) ptr->field_array));
1380 // field_offset = offsetof (struct s, field)
1381 // field_offset += index * casted_field_element_size;
1382 //
1383 // offset_diff = sizeof_struct - field_offset;
1384 //
1385 // result = offset_diff + flexible_array_member_size;
1386 //
1387 // cmp = (result >= 0)
1388 // if (index != 0)
1389 // cmp = (cmp && index >= 0)
1390 // return cmp ? result : 0;
1391
1392 bool IsSigned = CountFD->getType()->isSignedIntegerType();
1393
1394 QualType FlexibleArrayMemberTy = FlexibleArrayMemberFD->getType();
1395
1396 // Explicit cast because otherwise the CharWidth will promote an i32's into
1397 // u64's leading to overflows.
1398 int64_t CharWidth = static_cast<int64_t>(CGM.getContext().getCharWidth());
1399
1400 // field_offset = offsetof (struct s, field);
1401 Value *FieldOffset = nullptr;
1402 if (FlexibleArrayMemberFD != FD) {
1403 std::optional<int64_t> Offset = GetFieldOffset(Ctx, RD, FD);
1404 if (!Offset)
1405 return nullptr;
1406 FieldOffset =
1407 llvm::ConstantInt::get(ResType, *Offset / CharWidth, IsSigned);
1408 }
1409
1410 // count = ptr->count;
1411 // index = ptr->index;
1412 Value *Count, *Index;
1413 std::tie(Count, Index) = GetCountFieldAndIndex(
1414 *this, ME, FlexibleArrayMemberFD, CountFD, Idx, ResType, IsSigned);
1415 if (!Count)
1416 return nullptr;
1417
1418 // flexible_array_member_element_size = sizeof (*ptr->array);
1419 const ArrayType *ArrayTy = Ctx.getAsArrayType(FlexibleArrayMemberTy);
1420 CharUnits BaseSize = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
1421 auto *FlexibleArrayMemberElementSize =
1422 llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
1423
1424 // flexible_array_member_size = count * flexible_array_member_element_size;
1425 Value *FlexibleArrayMemberSize =
1426 Builder.CreateMul(Count, FlexibleArrayMemberElementSize,
1427 "flexible_array_member_size", !IsSigned, IsSigned);
1428
1429 Value *Result = nullptr;
1430 if (FlexibleArrayMemberFD == FD) {
1431 if (Idx) { // Option (2) '&((cast) ptr->array)[idx]'
1432 // casted_flexible_array_member_element_size =
1433 // sizeof (*((cast) ptr->array));
1434 llvm::ConstantInt *CastedFlexibleArrayMemberElementSize =
1435 FlexibleArrayMemberElementSize;
1436 if (!CastedArrayElementTy.isNull() &&
1437 CastedArrayElementTy->isPointerType()) {
1438 CharUnits BaseSize =
1439 Ctx.getTypeSizeInChars(CastedArrayElementTy->getPointeeType());
1440 CastedFlexibleArrayMemberElementSize =
1441 llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
1442 }
1443
1444 // index_size = index * casted_flexible_array_member_element_size;
1445 Value *IndexSize =
1446 Builder.CreateMul(Index, CastedFlexibleArrayMemberElementSize,
1447 "index_size", !IsSigned, IsSigned);
1448
1449 // result = flexible_array_member_size - index_size;
1450 Result = Builder.CreateSub(FlexibleArrayMemberSize, IndexSize, "result",
1451 !IsSigned, IsSigned);
1452 } else { // Option (1) 'ptr->array'
1453 // result = flexible_array_member_size;
1454 Result = FlexibleArrayMemberSize;
1455 }
1456 } else {
1457 // sizeof_struct = sizeof (struct s);
1458 llvm::StructType *StructTy = getTypes().getCGRecordLayout(RD).getLLVMType();
1459 const llvm::DataLayout &Layout = CGM.getDataLayout();
1460 TypeSize Size = Layout.getTypeSizeInBits(StructTy);
1461 Value *SizeofStruct =
1462 llvm::ConstantInt::get(ResType, Size.getKnownMinValue() / CharWidth);
1463
1464 if (Idx) { // Option (4) '&((cast) ptr->field_array)[idx]'
1465 // casted_field_element_size = sizeof (*((cast) ptr->field_array));
1466 CharUnits BaseSize;
1467 if (!CastedArrayElementTy.isNull() &&
1468 CastedArrayElementTy->isPointerType()) {
1469 BaseSize =
1470 Ctx.getTypeSizeInChars(CastedArrayElementTy->getPointeeType());
1471 } else {
1472 const ArrayType *ArrayTy = Ctx.getAsArrayType(FD->getType());
1473 BaseSize = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
1474 }
1475
1476 llvm::ConstantInt *CastedFieldElementSize =
1477 llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
1478
1479 // field_offset += index * casted_field_element_size;
1480 Value *Mul = Builder.CreateMul(Index, CastedFieldElementSize,
1481 "field_offset", !IsSigned, IsSigned);
1482 FieldOffset = Builder.CreateAdd(FieldOffset, Mul);
1483 }
1484 // Option (3) '&ptr->field', and Option (4) continuation.
1485 // offset_diff = flexible_array_member_offset - field_offset;
1486 Value *OffsetDiff = Builder.CreateSub(SizeofStruct, FieldOffset,
1487 "offset_diff", !IsSigned, IsSigned);
1488
1489 // result = offset_diff + flexible_array_member_size;
1490 Result = Builder.CreateAdd(FlexibleArrayMemberSize, OffsetDiff, "result");
1491 }
1492
1493 return EmitPositiveResultOrZero(*this, Result, Index, ResType, IsSigned);
1494}
1495
1496/// Returns a Value corresponding to the size of the given expression.
1497/// This Value may be either of the following:
1498/// - A llvm::Argument (if E is a param with the pass_object_size attribute on
1499/// it)
1500/// - A call to the @llvm.objectsize intrinsic
1501///
1502/// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
1503/// and we wouldn't otherwise try to reference a pass_object_size parameter,
1504/// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
1505llvm::Value *
1506CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
1507 llvm::IntegerType *ResType,
1508 llvm::Value *EmittedE, bool IsDynamic) {
1509 // We need to reference an argument if the pointer is a parameter with the
1510 // pass_object_size attribute.
1511 if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
1512 auto *Param = dyn_cast<ParmVarDecl>(D->getDecl());
1513 auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>();
1514 if (Param != nullptr && PS != nullptr &&
1515 areBOSTypesCompatible(PS->getType(), Type)) {
1516 auto Iter = SizeArguments.find(Param);
1517 assert(Iter != SizeArguments.end());
1518
1519 const ImplicitParamDecl *D = Iter->second;
1520 auto DIter = LocalDeclMap.find(D);
1521 assert(DIter != LocalDeclMap.end());
1522
1523 return EmitLoadOfScalar(DIter->second, /*Volatile=*/false,
1524 getContext().getSizeType(), E->getBeginLoc());
1525 }
1526 }
1527
1528 // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't
1529 // evaluate E for side-effects. In either case, we shouldn't lower to
1530 // @llvm.objectsize.
1531 if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext())))
1532 return getDefaultBuiltinObjectSizeResult(Type, ResType);
1533
1534 Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
1535 assert(Ptr->getType()->isPointerTy() &&
1536 "Non-pointer passed to __builtin_object_size?");
1537
1538 if (IsDynamic)
1539 // Emit special code for a flexible array member with the "counted_by"
1540 // attribute.
1541 if (Value *V = emitCountedBySize(E, Ptr, Type, ResType))
1542 return V;
1543
1544 Function *F =
1545 CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()});
1546
1547 // LLVM only supports 0 and 2, make sure that we pass along that as a boolean.
1548 Value *Min = Builder.getInt1((Type & 2) != 0);
1549 // For GCC compatibility, __builtin_object_size treat NULL as unknown size.
1550 Value *NullIsUnknown = Builder.getTrue();
1551 Value *Dynamic = Builder.getInt1(IsDynamic);
1552 return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic});
1553}
1554
1555namespace {
1556/// A struct to generically describe a bit test intrinsic.
1557struct BitTest {
1558 enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set };
1559 enum InterlockingKind : uint8_t {
1560 Unlocked,
1561 Sequential,
1562 Acquire,
1563 Release,
1564 NoFence
1565 };
1566
1567 ActionKind Action;
1568 InterlockingKind Interlocking;
1569 bool Is64Bit;
1570
1571 static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
1572};
1573
1574} // namespace
1575
1576BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
1577 switch (BuiltinID) {
1578 // Main portable variants.
1579 case Builtin::BI_bittest:
1580 return {TestOnly, Unlocked, false};
1581 case Builtin::BI_bittestandcomplement:
1582 return {Complement, Unlocked, false};
1583 case Builtin::BI_bittestandreset:
1584 return {Reset, Unlocked, false};
1585 case Builtin::BI_bittestandset:
1586 return {Set, Unlocked, false};
1587 case Builtin::BI_interlockedbittestandreset:
1588 return {Reset, Sequential, false};
1589 case Builtin::BI_interlockedbittestandset:
1590 return {Set, Sequential, false};
1591
1592 // 64-bit variants.
1593 case Builtin::BI_bittest64:
1594 return {TestOnly, Unlocked, true};
1595 case Builtin::BI_bittestandcomplement64:
1596 return {Complement, Unlocked, true};
1597 case Builtin::BI_bittestandreset64:
1598 return {Reset, Unlocked, true};
1599 case Builtin::BI_bittestandset64:
1600 return {Set, Unlocked, true};
1601 case Builtin::BI_interlockedbittestandreset64:
1602 return {Reset, Sequential, true};
1603 case Builtin::BI_interlockedbittestandset64:
1604 return {Set, Sequential, true};
1605
1606 // ARM/AArch64-specific ordering variants.
1607 case Builtin::BI_interlockedbittestandset_acq:
1608 return {Set, Acquire, false};
1609 case Builtin::BI_interlockedbittestandset_rel:
1610 return {Set, Release, false};
1611 case Builtin::BI_interlockedbittestandset_nf:
1612 return {Set, NoFence, false};
1613 case Builtin::BI_interlockedbittestandreset_acq:
1614 return {Reset, Acquire, false};
1615 case Builtin::BI_interlockedbittestandreset_rel:
1616 return {Reset, Release, false};
1617 case Builtin::BI_interlockedbittestandreset_nf:
1618 return {Reset, NoFence, false};
1619 case Builtin::BI_interlockedbittestandreset64_acq:
1620 return {Reset, Acquire, false};
1621 case Builtin::BI_interlockedbittestandreset64_rel:
1622 return {Reset, Release, false};
1623 case Builtin::BI_interlockedbittestandreset64_nf:
1624 return {Reset, NoFence, false};
1625 case Builtin::BI_interlockedbittestandset64_acq:
1626 return {Set, Acquire, false};
1627 case Builtin::BI_interlockedbittestandset64_rel:
1628 return {Set, Release, false};
1629 case Builtin::BI_interlockedbittestandset64_nf:
1630 return {Set, NoFence, false};
1631 }
1632 llvm_unreachable("expected only bittest intrinsics");
1633}
1634
1635static char bitActionToX86BTCode(BitTest::ActionKind A) {
1636 switch (A) {
1637 case BitTest::TestOnly: return '\0';
1638 case BitTest::Complement: return 'c';
1639 case BitTest::Reset: return 'r';
1640 case BitTest::Set: return 's';
1641 }
1642 llvm_unreachable("invalid action");
1643}
1644
1646 BitTest BT,
1647 const CallExpr *E, Value *BitBase,
1648 Value *BitPos) {
1649 char Action = bitActionToX86BTCode(BT.Action);
1650 char SizeSuffix = BT.Is64Bit ? 'q' : 'l';
1651
1652 // Build the assembly.
1654 raw_svector_ostream AsmOS(Asm);
1655 if (BT.Interlocking != BitTest::Unlocked)
1656 AsmOS << "lock ";
1657 AsmOS << "bt";
1658 if (Action)
1659 AsmOS << Action;
1660 AsmOS << SizeSuffix << " $2, ($1)";
1661
1662 // Build the constraints. FIXME: We should support immediates when possible.
1663 std::string Constraints = "={@ccc},r,r,~{cc},~{memory}";
1664 std::string_view MachineClobbers = CGF.getTarget().getClobbers();
1665 if (!MachineClobbers.empty()) {
1666 Constraints += ',';
1667 Constraints += MachineClobbers;
1668 }
1669 llvm::IntegerType *IntType = llvm::IntegerType::get(
1670 CGF.getLLVMContext(),
1671 CGF.getContext().getTypeSize(E->getArg(1)->getType()));
1672 llvm::FunctionType *FTy =
1673 llvm::FunctionType::get(CGF.Int8Ty, {CGF.DefaultPtrTy, IntType}, false);
1674
1675 llvm::InlineAsm *IA =
1676 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1677 return CGF.Builder.CreateCall(IA, {BitBase, BitPos});
1678}
1679
1680static llvm::AtomicOrdering
1681getBitTestAtomicOrdering(BitTest::InterlockingKind I) {
1682 switch (I) {
1683 case BitTest::Unlocked: return llvm::AtomicOrdering::NotAtomic;
1684 case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent;
1685 case BitTest::Acquire: return llvm::AtomicOrdering::Acquire;
1686 case BitTest::Release: return llvm::AtomicOrdering::Release;
1687 case BitTest::NoFence: return llvm::AtomicOrdering::Monotonic;
1688 }
1689 llvm_unreachable("invalid interlocking");
1690}
1691
1692static llvm::Value *EmitBitCountExpr(CodeGenFunction &CGF, const Expr *E) {
1693 llvm::Value *ArgValue = CGF.EmitScalarExpr(E);
1694 llvm::Type *ArgType = ArgValue->getType();
1695
1696 // Boolean vectors can be casted directly to its bitfield representation. We
1697 // intentionally do not round up to the next power of two size and let LLVM
1698 // handle the trailing bits.
1699 //
1700 // In big endian mode, the bitfield representation has a reversed bit order,
1701 // hence the need to add an operation to reverse it back to the expected
1702 // order.
1703 if (auto *VT = dyn_cast<llvm::FixedVectorType>(ArgType);
1704 VT && VT->getElementType()->isIntegerTy(1)) {
1705 llvm::Type *StorageType =
1706 llvm::Type::getIntNTy(CGF.getLLVMContext(), VT->getNumElements());
1707 ArgValue = CGF.Builder.CreateBitCast(ArgValue, StorageType);
1708
1709 if (CGF.getTarget().isBigEndian())
1710 ArgValue = CGF.Builder.CreateIntrinsic(Intrinsic::bitreverse,
1711 {StorageType}, ArgValue);
1712 }
1713
1714 return ArgValue;
1715}
1716
1717/// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of
1718/// bits and a bit position and read and optionally modify the bit at that
1719/// position. The position index can be arbitrarily large, i.e. it can be larger
1720/// than 31 or 63, so we need an indexed load in the general case.
1721static llvm::Value *EmitBitTestIntrinsic(CodeGenFunction &CGF,
1722 unsigned BuiltinID,
1723 const CallExpr *E) {
1724 Value *BitBase = CGF.EmitScalarExpr(E->getArg(0));
1725 Value *BitPos = CGF.EmitScalarExpr(E->getArg(1));
1726
1727 BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID);
1728
1729 // X86 has special BT, BTC, BTR, and BTS instructions that handle the array
1730 // indexing operation internally. Use them if possible.
1731 if (CGF.getTarget().getTriple().isX86())
1732 return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos);
1733
1734 // Otherwise, use generic code to load one byte and test the bit. Use all but
1735 // the bottom three bits as the array index, and the bottom three bits to form
1736 // a mask.
1737 // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0;
1738 Value *ByteIndex = CGF.Builder.CreateAShr(
1739 BitPos, llvm::ConstantInt::get(BitPos->getType(), 3), "bittest.byteidx");
1740 Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBase, ByteIndex,
1741 "bittest.byteaddr"),
1742 CGF.Int8Ty, CharUnits::One());
1743 Value *PosLow =
1744 CGF.Builder.CreateAnd(CGF.Builder.CreateTrunc(BitPos, CGF.Int8Ty),
1745 llvm::ConstantInt::get(CGF.Int8Ty, 0x7));
1746
1747 // The updating instructions will need a mask.
1748 Value *Mask = nullptr;
1749 if (BT.Action != BitTest::TestOnly) {
1750 Mask = CGF.Builder.CreateShl(llvm::ConstantInt::get(CGF.Int8Ty, 1), PosLow,
1751 "bittest.mask");
1752 }
1753
1754 // Check the action and ordering of the interlocked intrinsics.
1755 llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(BT.Interlocking);
1756
1757 Value *OldByte = nullptr;
1758 if (Ordering != llvm::AtomicOrdering::NotAtomic) {
1759 // Emit a combined atomicrmw load/store operation for the interlocked
1760 // intrinsics.
1761 llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or;
1762 if (BT.Action == BitTest::Reset) {
1763 Mask = CGF.Builder.CreateNot(Mask);
1764 RMWOp = llvm::AtomicRMWInst::And;
1765 }
1766 OldByte = CGF.Builder.CreateAtomicRMW(RMWOp, ByteAddr, Mask, Ordering);
1767 } else {
1768 // Emit a plain load for the non-interlocked intrinsics.
1769 OldByte = CGF.Builder.CreateLoad(ByteAddr, "bittest.byte");
1770 Value *NewByte = nullptr;
1771 switch (BT.Action) {
1772 case BitTest::TestOnly:
1773 // Don't store anything.
1774 break;
1775 case BitTest::Complement:
1776 NewByte = CGF.Builder.CreateXor(OldByte, Mask);
1777 break;
1778 case BitTest::Reset:
1779 NewByte = CGF.Builder.CreateAnd(OldByte, CGF.Builder.CreateNot(Mask));
1780 break;
1781 case BitTest::Set:
1782 NewByte = CGF.Builder.CreateOr(OldByte, Mask);
1783 break;
1784 }
1785 if (NewByte)
1786 CGF.Builder.CreateStore(NewByte, ByteAddr);
1787 }
1788
1789 // However we loaded the old byte, either by plain load or atomicrmw, shift
1790 // the bit into the low position and mask it to 0 or 1.
1791 Value *ShiftedByte = CGF.Builder.CreateLShr(OldByte, PosLow, "bittest.shr");
1792 return CGF.Builder.CreateAnd(
1793 ShiftedByte, llvm::ConstantInt::get(CGF.Int8Ty, 1), "bittest.res");
1794}
1795
1796namespace {
1797enum class MSVCSetJmpKind {
1798 _setjmpex,
1799 _setjmp3,
1800 _setjmp
1801};
1802}
1803
1804/// MSVC handles setjmp a bit differently on different platforms. On every
1805/// architecture except 32-bit x86, the frame address is passed. On x86, extra
1806/// parameters can be passed as variadic arguments, but we always pass none.
1807static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind,
1808 const CallExpr *E) {
1809 llvm::Value *Arg1 = nullptr;
1810 llvm::Type *Arg1Ty = nullptr;
1811 StringRef Name;
1812 bool IsVarArg = false;
1813 if (SJKind == MSVCSetJmpKind::_setjmp3) {
1814 Name = "_setjmp3";
1815 Arg1Ty = CGF.Int32Ty;
1816 Arg1 = llvm::ConstantInt::get(CGF.IntTy, 0);
1817 IsVarArg = true;
1818 } else {
1819 Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex";
1820 Arg1Ty = CGF.Int8PtrTy;
1821 if (CGF.getTarget().getTriple().getArch() == llvm::Triple::aarch64) {
1822 Arg1 = CGF.Builder.CreateCall(
1823 CGF.CGM.getIntrinsic(Intrinsic::sponentry, CGF.AllocaInt8PtrTy));
1824 } else
1825 Arg1 = CGF.Builder.CreateCall(
1826 CGF.CGM.getIntrinsic(Intrinsic::frameaddress, CGF.AllocaInt8PtrTy),
1827 llvm::ConstantInt::get(CGF.Int32Ty, 0));
1828 }
1829
1830 // Mark the call site and declaration with ReturnsTwice.
1831 llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty};
1832 llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get(
1833 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex,
1834 llvm::Attribute::ReturnsTwice);
1835 llvm::FunctionCallee SetJmpFn = CGF.CGM.CreateRuntimeFunction(
1836 llvm::FunctionType::get(CGF.IntTy, ArgTypes, IsVarArg), Name,
1837 ReturnsTwiceAttr, /*Local=*/true);
1838
1839 llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast(
1840 CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy);
1841 llvm::Value *Args[] = {Buf, Arg1};
1842 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args);
1843 CB->setAttributes(ReturnsTwiceAttr);
1844 return RValue::get(CB);
1845}
1846
1847// Emit an MSVC intrinsic. Assumes that arguments have *not* been evaluated.
1849 const CallExpr *E) {
1850 switch (BuiltinID) {
1853 Address IndexAddress(EmitPointerWithAlignment(E->getArg(0)));
1854 Value *ArgValue = EmitScalarExpr(E->getArg(1));
1855
1856 llvm::Type *ArgType = ArgValue->getType();
1857 llvm::Type *IndexType = IndexAddress.getElementType();
1858 llvm::Type *ResultType = ConvertType(E->getType());
1859
1860 Value *ArgZero = llvm::Constant::getNullValue(ArgType);
1861 Value *ResZero = llvm::Constant::getNullValue(ResultType);
1862 Value *ResOne = llvm::ConstantInt::get(ResultType, 1);
1863
1864 BasicBlock *Begin = Builder.GetInsertBlock();
1865 BasicBlock *End = createBasicBlock("bitscan_end", this->CurFn);
1866 Builder.SetInsertPoint(End);
1867 PHINode *Result = Builder.CreatePHI(ResultType, 2, "bitscan_result");
1868
1869 Builder.SetInsertPoint(Begin);
1870 Value *IsZero = Builder.CreateICmpEQ(ArgValue, ArgZero);
1871 BasicBlock *NotZero = createBasicBlock("bitscan_not_zero", this->CurFn);
1872 Builder.CreateCondBr(IsZero, End, NotZero);
1873 Result->addIncoming(ResZero, Begin);
1874
1875 Builder.SetInsertPoint(NotZero);
1876
1877 if (BuiltinID == MSVCIntrin::_BitScanForward) {
1878 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1879 Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1880 ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1881 Builder.CreateStore(ZeroCount, IndexAddress, false);
1882 } else {
1883 unsigned ArgWidth = cast<llvm::IntegerType>(ArgType)->getBitWidth();
1884 Value *ArgTypeLastIndex = llvm::ConstantInt::get(IndexType, ArgWidth - 1);
1885
1886 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1887 Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1888 ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1889 Value *Index = Builder.CreateNSWSub(ArgTypeLastIndex, ZeroCount);
1890 Builder.CreateStore(Index, IndexAddress, false);
1891 }
1892 Builder.CreateBr(End);
1893 Result->addIncoming(ResOne, NotZero);
1894
1895 Builder.SetInsertPoint(End);
1896 return Result;
1897 }
1899 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E);
1901 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E);
1903 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E);
1905 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E);
1907 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E);
1909 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E);
1911 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1912 AtomicOrdering::Acquire);
1914 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1915 AtomicOrdering::Release);
1917 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1918 AtomicOrdering::Monotonic);
1920 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1921 AtomicOrdering::Acquire);
1923 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1924 AtomicOrdering::Release);
1926 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1927 AtomicOrdering::Monotonic);
1929 return EmitAtomicCmpXchgForMSIntrin(*this, E);
1931 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire);
1933 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release);
1935 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1938 *this, E, AtomicOrdering::SequentiallyConsistent);
1940 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Acquire);
1942 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Release);
1944 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1946 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1947 AtomicOrdering::Acquire);
1949 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1950 AtomicOrdering::Release);
1952 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1953 AtomicOrdering::Monotonic);
1955 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1956 AtomicOrdering::Acquire);
1958 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1959 AtomicOrdering::Release);
1961 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1962 AtomicOrdering::Monotonic);
1964 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1965 AtomicOrdering::Acquire);
1967 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1968 AtomicOrdering::Release);
1970 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1971 AtomicOrdering::Monotonic);
1973 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire);
1975 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release);
1977 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic);
1979 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire);
1981 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release);
1983 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic);
1984
1986 return EmitAtomicDecrementValue(*this, E);
1988 return EmitAtomicIncrementValue(*this, E);
1989
1991 // Request immediate process termination from the kernel. The instruction
1992 // sequences to do this are documented on MSDN:
1993 // https://msdn.microsoft.com/en-us/library/dn774154.aspx
1994 llvm::Triple::ArchType ISA = getTarget().getTriple().getArch();
1995 StringRef Asm, Constraints;
1996 switch (ISA) {
1997 default:
1998 ErrorUnsupported(E, "__fastfail call for this architecture");
1999 break;
2000 case llvm::Triple::x86:
2001 case llvm::Triple::x86_64:
2002 Asm = "int $$0x29";
2003 Constraints = "{cx}";
2004 break;
2005 case llvm::Triple::thumb:
2006 Asm = "udf #251";
2007 Constraints = "{r0}";
2008 break;
2009 case llvm::Triple::aarch64:
2010 Asm = "brk #0xF003";
2011 Constraints = "{w0}";
2012 }
2013 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, {Int32Ty}, false);
2014 llvm::InlineAsm *IA =
2015 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
2016 llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
2017 getLLVMContext(), llvm::AttributeList::FunctionIndex,
2018 llvm::Attribute::NoReturn);
2019 llvm::CallInst *CI = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0)));
2020 CI->setAttributes(NoReturnAttr);
2021 return CI;
2022 }
2023 }
2024 llvm_unreachable("Incorrect MSVC intrinsic!");
2025}
2026
2027namespace {
2028// ARC cleanup for __builtin_os_log_format
2029struct CallObjCArcUse final : EHScopeStack::Cleanup {
2030 CallObjCArcUse(llvm::Value *object) : object(object) {}
2031 llvm::Value *object;
2032
2033 void Emit(CodeGenFunction &CGF, Flags flags) override {
2034 CGF.EmitARCIntrinsicUse(object);
2035 }
2036};
2037}
2038
2040 BuiltinCheckKind Kind) {
2041 assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero) &&
2042 "Unsupported builtin check kind");
2043
2044 Value *ArgValue = EmitBitCountExpr(*this, E);
2045 if (!SanOpts.has(SanitizerKind::Builtin))
2046 return ArgValue;
2047
2048 auto CheckOrdinal = SanitizerKind::SO_Builtin;
2049 auto CheckHandler = SanitizerHandler::InvalidBuiltin;
2050 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2051 Value *Cond = Builder.CreateICmpNE(
2052 ArgValue, llvm::Constant::getNullValue(ArgValue->getType()));
2053 EmitCheck(std::make_pair(Cond, CheckOrdinal), CheckHandler,
2055 llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)},
2056 {});
2057 return ArgValue;
2058}
2059
2061 Value *ArgValue = EvaluateExprAsBool(E);
2062 if (!SanOpts.has(SanitizerKind::Builtin))
2063 return ArgValue;
2064
2065 auto CheckOrdinal = SanitizerKind::SO_Builtin;
2066 auto CheckHandler = SanitizerHandler::InvalidBuiltin;
2067 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2068 EmitCheck(
2069 std::make_pair(ArgValue, CheckOrdinal), CheckHandler,
2071 llvm::ConstantInt::get(Builder.getInt8Ty(), BCK_AssumePassedFalse)},
2072 {});
2073 return ArgValue;
2074}
2075
2076static Value *EmitAbs(CodeGenFunction &CGF, Value *ArgValue, bool HasNSW) {
2077 return CGF.Builder.CreateBinaryIntrinsic(
2078 Intrinsic::abs, ArgValue,
2079 ConstantInt::get(CGF.Builder.getInt1Ty(), HasNSW));
2080}
2081
2083 bool SanitizeOverflow) {
2084 Value *ArgValue = CGF.EmitScalarExpr(E->getArg(0));
2085
2086 // Try to eliminate overflow check.
2087 if (const auto *VCI = dyn_cast<llvm::ConstantInt>(ArgValue)) {
2088 if (!VCI->isMinSignedValue())
2089 return EmitAbs(CGF, ArgValue, true);
2090 }
2091
2093 SanitizerHandler CheckHandler;
2094 if (SanitizeOverflow) {
2095 Ordinals.push_back(SanitizerKind::SO_SignedIntegerOverflow);
2096 CheckHandler = SanitizerHandler::NegateOverflow;
2097 } else
2098 CheckHandler = SanitizerHandler::SubOverflow;
2099
2100 SanitizerDebugLocation SanScope(&CGF, Ordinals, CheckHandler);
2101
2102 Constant *Zero = Constant::getNullValue(ArgValue->getType());
2103 Value *ResultAndOverflow = CGF.Builder.CreateBinaryIntrinsic(
2104 Intrinsic::ssub_with_overflow, Zero, ArgValue);
2105 Value *Result = CGF.Builder.CreateExtractValue(ResultAndOverflow, 0);
2106 Value *NotOverflow = CGF.Builder.CreateNot(
2107 CGF.Builder.CreateExtractValue(ResultAndOverflow, 1));
2108
2109 // TODO: support -ftrapv-handler.
2110 if (SanitizeOverflow) {
2111 CGF.EmitCheck({{NotOverflow, SanitizerKind::SO_SignedIntegerOverflow}},
2112 CheckHandler,
2115 {ArgValue});
2116 } else
2117 CGF.EmitTrapCheck(NotOverflow, CheckHandler);
2118
2119 Value *CmpResult = CGF.Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
2120 return CGF.Builder.CreateSelect(CmpResult, Result, ArgValue, "abs");
2121}
2122
2123/// Get the argument type for arguments to os_log_helper.
2125 QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false);
2126 return C.getCanonicalType(UnsignedTy);
2127}
2128
2131 CharUnits BufferAlignment) {
2132 ASTContext &Ctx = getContext();
2133
2135 {
2136 raw_svector_ostream OS(Name);
2137 OS << "__os_log_helper";
2138 OS << "_" << BufferAlignment.getQuantity();
2139 OS << "_" << int(Layout.getSummaryByte());
2140 OS << "_" << int(Layout.getNumArgsByte());
2141 for (const auto &Item : Layout.Items)
2142 OS << "_" << int(Item.getSizeByte()) << "_"
2143 << int(Item.getDescriptorByte());
2144 }
2145
2146 if (llvm::Function *F = CGM.getModule().getFunction(Name))
2147 return F;
2148
2150 FunctionArgList Args;
2151 Args.push_back(ImplicitParamDecl::Create(
2152 Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer"), Ctx.VoidPtrTy,
2154 ArgTys.emplace_back(Ctx.VoidPtrTy);
2155
2156 for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) {
2157 char Size = Layout.Items[I].getSizeByte();
2158 if (!Size)
2159 continue;
2160
2161 QualType ArgTy = getOSLogArgType(Ctx, Size);
2162 Args.push_back(ImplicitParamDecl::Create(
2163 Ctx, nullptr, SourceLocation(),
2164 &Ctx.Idents.get(std::string("arg") + llvm::to_string(I)), ArgTy,
2166 ArgTys.emplace_back(ArgTy);
2167 }
2168
2169 QualType ReturnTy = Ctx.VoidTy;
2170
2171 // The helper function has linkonce_odr linkage to enable the linker to merge
2172 // identical functions. To ensure the merging always happens, 'noinline' is
2173 // attached to the function when compiling with -Oz.
2174 const CGFunctionInfo &FI =
2175 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args);
2176 llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(FI);
2177 llvm::Function *Fn = llvm::Function::Create(
2178 FuncTy, llvm::GlobalValue::LinkOnceODRLinkage, Name, &CGM.getModule());
2179 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2180 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
2181 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
2182 Fn->setDoesNotThrow();
2183
2184 // Attach 'noinline' at -Oz.
2185 if (CGM.getCodeGenOpts().OptimizeSize == 2)
2186 Fn->addFnAttr(llvm::Attribute::NoInline);
2187
2188 auto NL = ApplyDebugLocation::CreateEmpty(*this);
2189 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, Args);
2190
2191 // Create a scope with an artificial location for the body of this function.
2192 auto AL = ApplyDebugLocation::CreateArtificial(*this);
2193
2194 CharUnits Offset;
2196 Builder.CreateLoad(GetAddrOfLocalVar(Args[0]), "buf"), Ctx.VoidTy,
2197 BufferAlignment);
2198 Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()),
2199 Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
2200 Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()),
2201 Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
2202
2203 unsigned I = 1;
2204 for (const auto &Item : Layout.Items) {
2205 Builder.CreateStore(
2206 Builder.getInt8(Item.getDescriptorByte()),
2207 Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
2208 Builder.CreateStore(
2209 Builder.getInt8(Item.getSizeByte()),
2210 Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
2211
2212 CharUnits Size = Item.size();
2213 if (!Size.getQuantity())
2214 continue;
2215
2216 Address Arg = GetAddrOfLocalVar(Args[I]);
2217 Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData");
2218 Addr = Addr.withElementType(Arg.getElementType());
2219 Builder.CreateStore(Builder.CreateLoad(Arg), Addr);
2220 Offset += Size;
2221 ++I;
2222 }
2223
2225
2226 return Fn;
2227}
2228
2230 assert(E.getNumArgs() >= 2 &&
2231 "__builtin_os_log_format takes at least 2 arguments");
2232 ASTContext &Ctx = getContext();
2235 Address BufAddr = EmitPointerWithAlignment(E.getArg(0));
2236
2237 // Ignore argument 1, the format string. It is not currently used.
2238 CallArgList Args;
2239 Args.add(RValue::get(BufAddr.emitRawPointer(*this)), Ctx.VoidPtrTy);
2240
2241 for (const auto &Item : Layout.Items) {
2242 int Size = Item.getSizeByte();
2243 if (!Size)
2244 continue;
2245
2246 llvm::Value *ArgVal;
2247
2248 if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) {
2249 uint64_t Val = 0;
2250 for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I)
2251 Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8;
2252 ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val));
2253 } else if (const Expr *TheExpr = Item.getExpr()) {
2254 ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false);
2255
2256 // If a temporary object that requires destruction after the full
2257 // expression is passed, push a lifetime-extended cleanup to extend its
2258 // lifetime to the end of the enclosing block scope.
2259 auto LifetimeExtendObject = [&](const Expr *E) {
2260 E = E->IgnoreParenCasts();
2261 // Extend lifetimes of objects returned by function calls and message
2262 // sends.
2263
2264 // FIXME: We should do this in other cases in which temporaries are
2265 // created including arguments of non-ARC types (e.g., C++
2266 // temporaries).
2268 return true;
2269 return false;
2270 };
2271
2272 if (TheExpr->getType()->isObjCRetainableType() &&
2273 getLangOpts().ObjCAutoRefCount && LifetimeExtendObject(TheExpr)) {
2274 assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&
2275 "Only scalar can be a ObjC retainable type");
2276 if (!isa<Constant>(ArgVal)) {
2277 CleanupKind Cleanup = getARCCleanupKind();
2278 QualType Ty = TheExpr->getType();
2279 RawAddress Alloca = CreateMemTempWithoutCast(Ty, "os.log.arg");
2280 ArgVal = EmitARCRetain(Ty, ArgVal);
2281 Builder.CreateStore(ArgVal, Alloca);
2282 pushLifetimeExtendedDestroy(Cleanup, Alloca, Ty,
2284 Cleanup & EHCleanup);
2285
2286 // Push a clang.arc.use call to ensure ARC optimizer knows that the
2287 // argument has to be alive.
2288 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
2290 }
2291 }
2292 } else {
2293 ArgVal = Builder.getInt32(Item.getConstValue().getQuantity());
2294 }
2295
2296 unsigned ArgValSize =
2297 CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType());
2298 llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(),
2299 ArgValSize);
2300 ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy);
2301 CanQualType ArgTy = getOSLogArgType(Ctx, Size);
2302 // If ArgVal has type x86_fp80, zero-extend ArgVal.
2303 ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy));
2304 Args.add(RValue::get(ArgVal), ArgTy);
2305 }
2306
2307 const CGFunctionInfo &FI =
2308 CGM.getTypes().arrangeBuiltinFunctionCall(Ctx.VoidTy, Args);
2309 llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction(
2310 Layout, BufAddr.getAlignment());
2312 return RValue::get(BufAddr, *this);
2313}
2314
2316 unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info,
2317 WidthAndSignedness ResultInfo) {
2318 return BuiltinID == Builtin::BI__builtin_mul_overflow &&
2319 Op1Info.Width == Op2Info.Width && Op2Info.Width == ResultInfo.Width &&
2320 !Op1Info.Signed && !Op2Info.Signed && ResultInfo.Signed;
2321}
2322
2324 CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info,
2325 const clang::Expr *Op2, WidthAndSignedness Op2Info,
2326 const clang::Expr *ResultArg, QualType ResultQTy,
2327 WidthAndSignedness ResultInfo) {
2329 Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
2330 "Cannot specialize this multiply");
2331
2332 llvm::Value *V1 = CGF.EmitScalarExpr(Op1);
2333 llvm::Value *V2 = CGF.EmitScalarExpr(Op2);
2334
2335 llvm::Value *HasOverflow;
2336 llvm::Value *Result = EmitOverflowIntrinsic(
2337 CGF, Intrinsic::umul_with_overflow, V1, V2, HasOverflow);
2338
2339 // The intrinsic call will detect overflow when the value is > UINT_MAX,
2340 // however, since the original builtin had a signed result, we need to report
2341 // an overflow when the result is greater than INT_MAX.
2342 auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width);
2343 llvm::Value *IntMaxValue = llvm::ConstantInt::get(Result->getType(), IntMax);
2344
2345 llvm::Value *IntMaxOverflow = CGF.Builder.CreateICmpUGT(Result, IntMaxValue);
2346 HasOverflow = CGF.Builder.CreateOr(HasOverflow, IntMaxOverflow);
2347
2348 bool isVolatile =
2349 ResultArg->getType()->getPointeeType().isVolatileQualified();
2350 Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
2351 CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2352 isVolatile);
2353 return RValue::get(HasOverflow);
2354}
2355
2356/// Determine if a binop is a checked mixed-sign multiply we can specialize.
2357static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
2358 WidthAndSignedness Op1Info,
2359 WidthAndSignedness Op2Info,
2360 WidthAndSignedness ResultInfo) {
2361 return BuiltinID == Builtin::BI__builtin_mul_overflow &&
2362 std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width &&
2363 Op1Info.Signed != Op2Info.Signed;
2364}
2365
2366/// Emit a checked mixed-sign multiply. This is a cheaper specialization of
2367/// the generic checked-binop irgen.
2368static RValue
2370 WidthAndSignedness Op1Info, const clang::Expr *Op2,
2371 WidthAndSignedness Op2Info,
2372 const clang::Expr *ResultArg, QualType ResultQTy,
2373 WidthAndSignedness ResultInfo) {
2374 assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,
2375 Op2Info, ResultInfo) &&
2376 "Not a mixed-sign multipliction we can specialize");
2377
2378 // Emit the signed and unsigned operands.
2379 const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
2380 const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
2381 llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
2382 llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
2383 unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width;
2384 unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width;
2385
2386 // One of the operands may be smaller than the other. If so, [s|z]ext it.
2387 if (SignedOpWidth < UnsignedOpWidth)
2388 Signed = CGF.Builder.CreateSExt(Signed, Unsigned->getType(), "op.sext");
2389 if (UnsignedOpWidth < SignedOpWidth)
2390 Unsigned = CGF.Builder.CreateZExt(Unsigned, Signed->getType(), "op.zext");
2391
2392 llvm::Type *OpTy = Signed->getType();
2393 llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
2394 Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
2395 llvm::Type *ResTy = CGF.getTypes().ConvertType(ResultQTy);
2396 unsigned OpWidth = std::max(Op1Info.Width, Op2Info.Width);
2397
2398 // Take the absolute value of the signed operand.
2399 llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
2400 llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
2401 llvm::Value *AbsSigned =
2402 CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
2403
2404 // Perform a checked unsigned multiplication.
2405 llvm::Value *UnsignedOverflow;
2406 llvm::Value *UnsignedResult =
2407 EmitOverflowIntrinsic(CGF, Intrinsic::umul_with_overflow, AbsSigned,
2408 Unsigned, UnsignedOverflow);
2409
2410 llvm::Value *Overflow, *Result;
2411 if (ResultInfo.Signed) {
2412 // Signed overflow occurs if the result is greater than INT_MAX or lesser
2413 // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
2414 auto IntMax =
2415 llvm::APInt::getSignedMaxValue(ResultInfo.Width).zext(OpWidth);
2416 llvm::Value *MaxResult =
2417 CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
2418 CGF.Builder.CreateZExt(IsNegative, OpTy));
2419 llvm::Value *SignedOverflow =
2420 CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
2421 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
2422
2423 // Prepare the signed result (possibly by negating it).
2424 llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
2425 llvm::Value *SignedResult =
2426 CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
2427 Result = CGF.Builder.CreateTrunc(SignedResult, ResTy);
2428 } else {
2429 // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX.
2430 llvm::Value *Underflow = CGF.Builder.CreateAnd(
2431 IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
2432 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
2433 if (ResultInfo.Width < OpWidth) {
2434 auto IntMax =
2435 llvm::APInt::getMaxValue(ResultInfo.Width).zext(OpWidth);
2436 llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
2437 UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
2438 Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
2439 }
2440
2441 // Negate the product if it would be negative in infinite precision.
2442 Result = CGF.Builder.CreateSelect(
2443 IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
2444
2445 Result = CGF.Builder.CreateTrunc(Result, ResTy);
2446 }
2447 assert(Overflow && Result && "Missing overflow or result");
2448
2449 bool isVolatile =
2450 ResultArg->getType()->getPointeeType().isVolatileQualified();
2451 CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2452 isVolatile);
2453 return RValue::get(Overflow);
2454}
2455
2456/// Determine if the specified type requires laundering by checking if it is a
2457/// dynamic class type or contains a subobject which is a dynamic class type.
2459 if (!CGM.getCodeGenOpts().StrictVTablePointers)
2460 return false;
2461 return Ty.requiresBuiltinLaunder(CGM.getContext());
2462}
2463
2464RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) {
2465 llvm::Value *Src = EmitScalarExpr(E->getArg(0));
2466 llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1));
2467
2468 // The builtin's shift arg may have a different type than the source arg and
2469 // result, but the LLVM intrinsic uses the same type for all values.
2470 llvm::Type *Ty = Src->getType();
2471 llvm::Type *ShiftTy = ShiftAmt->getType();
2472
2473 unsigned BitWidth = Ty->getIntegerBitWidth();
2474
2475 // Normalize shift amount to [0, BitWidth) range to match runtime behavior.
2476 // This matches the algorithm in ExprConstant.cpp for constant evaluation.
2477 if (BitWidth == 1) {
2478 // Rotating a 1-bit value is always a no-op
2479 ShiftAmt = ConstantInt::get(ShiftTy, 0);
2480 } else if (BitWidth == 2) {
2481 // For 2-bit values: rotation amount is 0 or 1 based on
2482 // whether the amount is even or odd. We can't use srem here because
2483 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
2484 llvm::Value *One = ConstantInt::get(ShiftTy, 1);
2485 ShiftAmt = Builder.CreateAnd(ShiftAmt, One);
2486 } else {
2487 unsigned ShiftAmtBitWidth = ShiftTy->getIntegerBitWidth();
2488 bool ShiftAmtIsSigned = E->getArg(1)->getType()->isSignedIntegerType();
2489
2490 // Choose the wider type for the divisor to avoid truncation
2491 llvm::Type *DivisorTy = ShiftAmtBitWidth > BitWidth ? ShiftTy : Ty;
2492 llvm::Value *Divisor = ConstantInt::get(DivisorTy, BitWidth);
2493
2494 // Extend ShiftAmt to match Divisor width if needed
2495 if (ShiftAmtBitWidth < DivisorTy->getIntegerBitWidth()) {
2496 ShiftAmt = Builder.CreateIntCast(ShiftAmt, DivisorTy, ShiftAmtIsSigned);
2497 }
2498
2499 // Normalize to [0, BitWidth)
2500 llvm::Value *RemResult;
2501 if (ShiftAmtIsSigned) {
2502 RemResult = Builder.CreateSRem(ShiftAmt, Divisor);
2503 // Signed remainder can be negative, convert to positive equivalent
2504 llvm::Value *Zero = ConstantInt::get(DivisorTy, 0);
2505 llvm::Value *IsNegative = Builder.CreateICmpSLT(RemResult, Zero);
2506 llvm::Value *PositiveShift = Builder.CreateAdd(RemResult, Divisor);
2507 ShiftAmt = Builder.CreateSelect(IsNegative, PositiveShift, RemResult);
2508 } else {
2509 ShiftAmt = Builder.CreateURem(ShiftAmt, Divisor);
2510 }
2511 }
2512
2513 // Convert to the source type if needed
2514 if (ShiftAmt->getType() != Ty) {
2515 ShiftAmt = Builder.CreateIntCast(ShiftAmt, Ty, false);
2516 }
2517
2518 // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same.
2519 unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
2520 Function *F = CGM.getIntrinsic(IID, Ty);
2521 return RValue::get(Builder.CreateCall(F, {Src, Src, ShiftAmt}));
2522}
2523
2524// Map math builtins for long-double to f128 version.
2525static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID) {
2526 switch (BuiltinID) {
2527#define MUTATE_LDBL(func) \
2528 case Builtin::BI__builtin_##func##l: \
2529 return Builtin::BI__builtin_##func##f128;
2560 MUTATE_LDBL(nans)
2561 MUTATE_LDBL(inf)
2580 MUTATE_LDBL(huge_val)
2590#undef MUTATE_LDBL
2591 default:
2592 return BuiltinID;
2593 }
2594}
2595
2596static Value *tryUseTestFPKind(CodeGenFunction &CGF, unsigned BuiltinID,
2597 Value *V) {
2598 if (CGF.Builder.getIsFPConstrained() &&
2599 CGF.Builder.getDefaultConstrainedExcept() != fp::ebIgnore) {
2600 if (Value *Result =
2601 CGF.getTargetHooks().testFPKind(V, BuiltinID, CGF.Builder, CGF.CGM))
2602 return Result;
2603 }
2604 return nullptr;
2605}
2606
2608 const FunctionDecl *FD) {
2609 auto Name = FD->getNameAsString() + "__hipstdpar_unsupported";
2610 auto FnTy = CGF->CGM.getTypes().GetFunctionType(FD);
2611 auto UBF = CGF->CGM.getModule().getOrInsertFunction(Name, FnTy);
2612
2614 for (auto &&FormalTy : FnTy->params())
2615 Args.push_back(llvm::PoisonValue::get(FormalTy));
2616
2617 return RValue::get(CGF->Builder.CreateCall(UBF, Args));
2618}
2619
2620// stdc_{leading,trailing}_{zeros,ones} and stdc_count_ones: counts bits using
2621// ctlz, cttz, or ctpop (IsPop). InvertArg flips the input to count the
2622// opposite bit value.
2624 Intrinsic::ID IntID,
2625 bool InvertArg, bool IsPop) {
2626 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2627 llvm::Type *ArgType = ArgValue->getType();
2628 llvm::Type *ResultType = ConvertType(E->getType());
2629 Value *ActualArg = InvertArg ? Builder.CreateNot(ArgValue) : ArgValue;
2630 Function *F = CGM.getIntrinsic(IntID, ArgType);
2631 Value *Result = IsPop
2632 ? Builder.CreateCall(F, ActualArg)
2633 : Builder.CreateCall(F, {ActualArg, Builder.getFalse()});
2634 if (Result->getType() != ResultType)
2635 Result = Builder.CreateIntCast(Result, ResultType, false);
2636 return RValue::get(Result);
2637}
2638
2639// stdc_count_zeros (BitWidth - ctpop) and stdc_bit_width (BitWidth - ctlz).
2640// IsPop selects ctpop; otherwise ctlz is used.
2642 Intrinsic::ID IntID, bool IsPop) {
2643 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2644 llvm::Type *ArgType = ArgValue->getType();
2645 llvm::Type *ResultType = ConvertType(E->getType());
2646 unsigned BitWidth = ArgType->getIntegerBitWidth();
2647 Function *F = CGM.getIntrinsic(IntID, ArgType);
2648 Value *Cnt = IsPop ? Builder.CreateCall(F, ArgValue)
2649 : Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
2650 Value *Result = Builder.CreateSub(ConstantInt::get(ArgType, BitWidth), Cnt);
2651 if (Result->getType() != ResultType)
2652 Result = Builder.CreateIntCast(Result, ResultType, false);
2653 return RValue::get(Result);
2654}
2655
2656// stdc_first_{leading,trailing}_{zero,one}: returns the 1-based position of
2657// the first matching bit, or 0 if no such bit exists. InvertArg flips the
2658// input to search for zeros instead of ones.
2660 bool InvertArg) {
2661 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2662 llvm::Type *ArgType = ArgValue->getType();
2663 llvm::Type *ResultType = ConvertType(E->getType());
2664 Value *Zero = ConstantInt::get(ArgType, 0);
2665 Value *One = ConstantInt::get(ArgType, 1);
2666 Value *ActualArg = InvertArg ? Builder.CreateNot(ArgValue) : ArgValue;
2667 Function *F = CGM.getIntrinsic(IntID, ArgType);
2668 Value *Cnt = Builder.CreateCall(F, {ActualArg, Builder.getFalse()});
2669 Value *Tmp = Builder.CreateAdd(Cnt, One);
2670 Value *IsZero = Builder.CreateICmpEQ(ActualArg, Zero);
2671 Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp);
2672 if (Result->getType() != ResultType)
2673 Result = Builder.CreateIntCast(Result, ResultType, false);
2674 return RValue::get(Result);
2675}
2676
2678 const ASTContext::BitInterval &PaddingInterval) {
2679 uint64_t CharWidth = CGF.getContext().getCharWidth();
2680
2681 auto *I8Ptr = CGF.Builder.CreateBitCast(Src.getBasePointer(), CGF.Int8PtrTy);
2682 auto *Zero = ConstantInt::get(CGF.Int8Ty, 0);
2683
2684 // Calculate byte indices and bit positions
2685 auto StartByte = PaddingInterval.First / CharWidth;
2686 auto StartBit = PaddingInterval.First % CharWidth;
2687 auto EndByte = PaddingInterval.Last / CharWidth;
2688 auto EndBit = PaddingInterval.Last % CharWidth;
2689
2690 if (StartByte == EndByte) {
2691 // Interval is within a single byte
2692 auto *Index = ConstantInt::get(CGF.IntTy, StartByte);
2693 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2694 Address ElementAddr(Element, CGF.Int8Ty,
2696 CharUnits::fromQuantity(StartByte)));
2697
2698 auto *Value = CGF.Builder.CreateLoad(ElementAddr);
2699
2700 // Create mask to clear bits within the byte
2701 // We want to clear bits from StartBit to EndBit-1
2702 uint8_t bitsToClear = ((1 << EndBit) - 1) & ~((1 << StartBit) - 1);
2703 uint8_t bitsToKeep = ~bitsToClear;
2704 auto *MaskValue = ConstantInt::get(CGF.Int8Ty, bitsToKeep);
2705 auto *NewValue = CGF.Builder.CreateAnd(Value, MaskValue);
2706
2707 CGF.Builder.CreateStore(NewValue, ElementAddr);
2708 } else {
2709 // Handle the start byte
2710 if (StartBit != 0) {
2711 auto *Index = ConstantInt::get(CGF.IntTy, StartByte);
2712 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2713 Address ElementAddr(Element, CGF.Int8Ty,
2715 CharUnits::fromQuantity(StartByte)));
2716
2717 auto *Value = CGF.Builder.CreateLoad(ElementAddr);
2718
2719 uint8_t bitsToClear = ((1 << (CharWidth - StartBit)) - 1) << StartBit;
2720 uint8_t bitsToKeep = ~bitsToClear;
2721 auto *MaskValue = ConstantInt::get(CGF.Int8Ty, bitsToKeep);
2722 auto *NewValue = CGF.Builder.CreateAnd(Value, MaskValue);
2723
2724 CGF.Builder.CreateStore(NewValue, ElementAddr);
2725 ++StartByte;
2726 }
2727
2728 // Handle full bytes in the middle
2729 for (auto Offset = StartByte; Offset < EndByte; ++Offset) {
2730 auto *Index = ConstantInt::get(CGF.IntTy, Offset);
2731 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2732 Address ElementAddr(Element, CGF.Int8Ty,
2734 CharUnits::fromQuantity(Offset)));
2735
2736 CGF.Builder.CreateStore(Zero, ElementAddr);
2737 }
2738
2739 // Handle the end byte
2740 if (EndBit != 0) {
2741 auto *Index = ConstantInt::get(CGF.IntTy, EndByte);
2742 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2743 Address ElementAddr(Element, CGF.Int8Ty,
2745 CharUnits::fromQuantity(EndByte)));
2746
2747 auto *Value = CGF.Builder.CreateLoad(ElementAddr);
2748
2749 uint8_t bitsToClear = (1 << EndBit) - 1;
2750 uint8_t bitsToKeep = ~bitsToClear;
2751 auto *MaskValue = ConstantInt::get(CGF.Int8Ty, bitsToKeep);
2752 auto *NewValue = CGF.Builder.CreateAnd(Value, MaskValue);
2753
2754 CGF.Builder.CreateStore(NewValue, ElementAddr);
2755 }
2756 }
2757}
2758
2760 const CallExpr *E,
2762 assert(!getContext().BuiltinInfo.isImmediate(BuiltinID) &&
2763 "Should not codegen for consteval builtins");
2764
2765 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
2766 // See if we can constant fold this builtin. If so, don't emit it at all.
2767 // TODO: Extend this handling to all builtin calls that we can constant-fold.
2769 if (E->isPRValue() && E->EvaluateAsRValue(Result, CGM.getContext()) &&
2770 !Result.hasSideEffects()) {
2771 if (Result.Val.isInt())
2772 return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
2773 Result.Val.getInt()));
2774 if (Result.Val.isFloat())
2775 return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
2776 Result.Val.getFloat()));
2777 }
2778
2779 // If current long-double semantics is IEEE 128-bit, replace math builtins
2780 // of long-double with f128 equivalent.
2781 // TODO: This mutation should also be applied to other targets other than PPC,
2782 // after backend supports IEEE 128-bit style libcalls.
2783 if (getTarget().getTriple().isPPC64() &&
2784 &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
2785 BuiltinID = mutateLongDoubleBuiltin(BuiltinID);
2786
2787 // If the builtin has been declared explicitly with an assembler label,
2788 // disable the specialized emitting below. Ideally we should communicate the
2789 // rename in IR, or at least avoid generating the intrinsic calls that are
2790 // likely to get lowered to the renamed library functions.
2791 const unsigned BuiltinIDIfNoAsmLabel =
2792 FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID;
2793
2794 std::optional<bool> ErrnoOverriden;
2795 // ErrnoOverriden is true if math-errno is overriden via the
2796 // '#pragma float_control(precise, on)'. This pragma disables fast-math,
2797 // which implies math-errno.
2798 if (E->hasStoredFPFeatures()) {
2800 if (OP.hasMathErrnoOverride())
2801 ErrnoOverriden = OP.getMathErrnoOverride();
2802 }
2803 // True if 'attribute__((optnone))' is used. This attribute overrides
2804 // fast-math which implies math-errno.
2805 bool OptNone = CurFuncDecl && CurFuncDecl->hasAttr<OptimizeNoneAttr>();
2806
2807 bool IsOptimizationEnabled = CGM.getCodeGenOpts().OptimizationLevel != 0;
2808
2809 bool GenerateFPMathIntrinsics =
2811 BuiltinID, CGM.getTriple(), ErrnoOverriden, getLangOpts().MathErrno,
2812 OptNone, IsOptimizationEnabled);
2813
2814 if (GenerateFPMathIntrinsics) {
2815 switch (BuiltinIDIfNoAsmLabel) {
2816 case Builtin::BIacos:
2817 case Builtin::BIacosf:
2818 case Builtin::BIacosl:
2819 case Builtin::BI__builtin_acos:
2820 case Builtin::BI__builtin_acosf:
2821 case Builtin::BI__builtin_acosf16:
2822 case Builtin::BI__builtin_acosl:
2823 case Builtin::BI__builtin_acosf128:
2824 case Builtin::BI__builtin_elementwise_acos:
2826 *this, E, Intrinsic::acos, Intrinsic::experimental_constrained_acos));
2827
2828 case Builtin::BIasin:
2829 case Builtin::BIasinf:
2830 case Builtin::BIasinl:
2831 case Builtin::BI__builtin_asin:
2832 case Builtin::BI__builtin_asinf:
2833 case Builtin::BI__builtin_asinf16:
2834 case Builtin::BI__builtin_asinl:
2835 case Builtin::BI__builtin_asinf128:
2836 case Builtin::BI__builtin_elementwise_asin:
2838 *this, E, Intrinsic::asin, Intrinsic::experimental_constrained_asin));
2839
2840 case Builtin::BIatan:
2841 case Builtin::BIatanf:
2842 case Builtin::BIatanl:
2843 case Builtin::BI__builtin_atan:
2844 case Builtin::BI__builtin_atanf:
2845 case Builtin::BI__builtin_atanf16:
2846 case Builtin::BI__builtin_atanl:
2847 case Builtin::BI__builtin_atanf128:
2848 case Builtin::BI__builtin_elementwise_atan:
2850 *this, E, Intrinsic::atan, Intrinsic::experimental_constrained_atan));
2851
2852 case Builtin::BIatan2:
2853 case Builtin::BIatan2f:
2854 case Builtin::BIatan2l:
2855 case Builtin::BI__builtin_atan2:
2856 case Builtin::BI__builtin_atan2f:
2857 case Builtin::BI__builtin_atan2f16:
2858 case Builtin::BI__builtin_atan2l:
2859 case Builtin::BI__builtin_atan2f128:
2860 case Builtin::BI__builtin_elementwise_atan2:
2862 *this, E, Intrinsic::atan2,
2863 Intrinsic::experimental_constrained_atan2));
2864
2865 case Builtin::BIceil:
2866 case Builtin::BIceilf:
2867 case Builtin::BIceill:
2868 case Builtin::BI__builtin_ceil:
2869 case Builtin::BI__builtin_ceilf:
2870 case Builtin::BI__builtin_ceilf16:
2871 case Builtin::BI__builtin_ceill:
2872 case Builtin::BI__builtin_ceilf128:
2873 case Builtin::BI__builtin_elementwise_ceil:
2875 Intrinsic::ceil,
2876 Intrinsic::experimental_constrained_ceil));
2877
2878 case Builtin::BIcopysign:
2879 case Builtin::BIcopysignf:
2880 case Builtin::BIcopysignl:
2881 case Builtin::BI__builtin_copysign:
2882 case Builtin::BI__builtin_copysignf:
2883 case Builtin::BI__builtin_copysignf16:
2884 case Builtin::BI__builtin_copysignl:
2885 case Builtin::BI__builtin_copysignf128:
2886 return RValue::get(
2887 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::copysign));
2888
2889 case Builtin::BIcos:
2890 case Builtin::BIcosf:
2891 case Builtin::BIcosl:
2892 case Builtin::BI__builtin_cos:
2893 case Builtin::BI__builtin_cosf:
2894 case Builtin::BI__builtin_cosf16:
2895 case Builtin::BI__builtin_cosl:
2896 case Builtin::BI__builtin_cosf128:
2897 case Builtin::BI__builtin_elementwise_cos:
2899 Intrinsic::cos,
2900 Intrinsic::experimental_constrained_cos));
2901
2902 case Builtin::BIcosh:
2903 case Builtin::BIcoshf:
2904 case Builtin::BIcoshl:
2905 case Builtin::BI__builtin_cosh:
2906 case Builtin::BI__builtin_coshf:
2907 case Builtin::BI__builtin_coshf16:
2908 case Builtin::BI__builtin_coshl:
2909 case Builtin::BI__builtin_coshf128:
2910 case Builtin::BI__builtin_elementwise_cosh:
2912 *this, E, Intrinsic::cosh, Intrinsic::experimental_constrained_cosh));
2913
2914 case Builtin::BIexp:
2915 case Builtin::BIexpf:
2916 case Builtin::BIexpl:
2917 case Builtin::BI__builtin_exp:
2918 case Builtin::BI__builtin_expf:
2919 case Builtin::BI__builtin_expf16:
2920 case Builtin::BI__builtin_expl:
2921 case Builtin::BI__builtin_expf128:
2922 case Builtin::BI__builtin_elementwise_exp:
2924 Intrinsic::exp,
2925 Intrinsic::experimental_constrained_exp));
2926
2927 case Builtin::BIexp2:
2928 case Builtin::BIexp2f:
2929 case Builtin::BIexp2l:
2930 case Builtin::BI__builtin_exp2:
2931 case Builtin::BI__builtin_exp2f:
2932 case Builtin::BI__builtin_exp2f16:
2933 case Builtin::BI__builtin_exp2l:
2934 case Builtin::BI__builtin_exp2f128:
2935 case Builtin::BI__builtin_elementwise_exp2:
2937 Intrinsic::exp2,
2938 Intrinsic::experimental_constrained_exp2));
2939 case Builtin::BI__builtin_exp10:
2940 case Builtin::BI__builtin_exp10f:
2941 case Builtin::BI__builtin_exp10f16:
2942 case Builtin::BI__builtin_exp10l:
2943 case Builtin::BI__builtin_exp10f128:
2944 case Builtin::BI__builtin_elementwise_exp10: {
2945 // TODO: strictfp support
2946 if (Builder.getIsFPConstrained())
2947 break;
2948 return RValue::get(
2949 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::exp10));
2950 }
2951 case Builtin::BIfabs:
2952 case Builtin::BIfabsf:
2953 case Builtin::BIfabsl:
2954 case Builtin::BI__builtin_fabs:
2955 case Builtin::BI__builtin_fabsf:
2956 case Builtin::BI__builtin_fabsf16:
2957 case Builtin::BI__builtin_fabsl:
2958 case Builtin::BI__builtin_fabsf128:
2959 return RValue::get(
2960 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::fabs));
2961
2962 case Builtin::BIfloor:
2963 case Builtin::BIfloorf:
2964 case Builtin::BIfloorl:
2965 case Builtin::BI__builtin_floor:
2966 case Builtin::BI__builtin_floorf:
2967 case Builtin::BI__builtin_floorf16:
2968 case Builtin::BI__builtin_floorl:
2969 case Builtin::BI__builtin_floorf128:
2970 case Builtin::BI__builtin_elementwise_floor:
2972 Intrinsic::floor,
2973 Intrinsic::experimental_constrained_floor));
2974
2975 case Builtin::BIfma:
2976 case Builtin::BIfmaf:
2977 case Builtin::BIfmal:
2978 case Builtin::BI__builtin_fma:
2979 case Builtin::BI__builtin_fmaf:
2980 case Builtin::BI__builtin_fmaf16:
2981 case Builtin::BI__builtin_fmal:
2982 case Builtin::BI__builtin_fmaf128:
2983 case Builtin::BI__builtin_elementwise_fma:
2985 Intrinsic::fma,
2986 Intrinsic::experimental_constrained_fma));
2987
2988 case Builtin::BIfmax:
2989 case Builtin::BIfmaxf:
2990 case Builtin::BIfmaxl:
2991 case Builtin::BI__builtin_fmax:
2992 case Builtin::BI__builtin_fmaxf:
2993 case Builtin::BI__builtin_fmaxf16:
2994 case Builtin::BI__builtin_fmaxl:
2995 case Builtin::BI__builtin_fmaxf128: {
2996 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
2997 Builder.getFastMathFlags().setNoSignedZeros();
2999 *this, E, Intrinsic::maxnum,
3000 Intrinsic::experimental_constrained_maxnum));
3001 }
3002
3003 case Builtin::BIfmin:
3004 case Builtin::BIfminf:
3005 case Builtin::BIfminl:
3006 case Builtin::BI__builtin_fmin:
3007 case Builtin::BI__builtin_fminf:
3008 case Builtin::BI__builtin_fminf16:
3009 case Builtin::BI__builtin_fminl:
3010 case Builtin::BI__builtin_fminf128: {
3011 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
3012 Builder.getFastMathFlags().setNoSignedZeros();
3014 *this, E, Intrinsic::minnum,
3015 Intrinsic::experimental_constrained_minnum));
3016 }
3017
3018 case Builtin::BIfmaximum_num:
3019 case Builtin::BIfmaximum_numf:
3020 case Builtin::BIfmaximum_numl:
3021 case Builtin::BI__builtin_fmaximum_num:
3022 case Builtin::BI__builtin_fmaximum_numf:
3023 case Builtin::BI__builtin_fmaximum_numf16:
3024 case Builtin::BI__builtin_fmaximum_numl:
3025 case Builtin::BI__builtin_fmaximum_numf128:
3026 return RValue::get(
3027 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::maximumnum));
3028
3029 case Builtin::BIfminimum_num:
3030 case Builtin::BIfminimum_numf:
3031 case Builtin::BIfminimum_numl:
3032 case Builtin::BI__builtin_fminimum_num:
3033 case Builtin::BI__builtin_fminimum_numf:
3034 case Builtin::BI__builtin_fminimum_numf16:
3035 case Builtin::BI__builtin_fminimum_numl:
3036 case Builtin::BI__builtin_fminimum_numf128:
3037 return RValue::get(
3038 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::minimumnum));
3039
3040 // fmod() is a special-case. It maps to the frem instruction rather than an
3041 // LLVM intrinsic.
3042 case Builtin::BIfmod:
3043 case Builtin::BIfmodf:
3044 case Builtin::BIfmodl:
3045 case Builtin::BI__builtin_fmod:
3046 case Builtin::BI__builtin_fmodf:
3047 case Builtin::BI__builtin_fmodf16:
3048 case Builtin::BI__builtin_fmodl:
3049 case Builtin::BI__builtin_fmodf128:
3050 case Builtin::BI__builtin_elementwise_fmod: {
3051 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3052 Value *Arg1 = EmitScalarExpr(E->getArg(0));
3053 Value *Arg2 = EmitScalarExpr(E->getArg(1));
3054 if (Builder.getIsFPConstrained()) {
3055 Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_frem,
3056 Arg1->getType());
3057 return RValue::get(Builder.CreateConstrainedFPCall(F, {Arg1, Arg2}));
3058 } else {
3059 return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
3060 }
3061 }
3062
3063 case Builtin::BIlog:
3064 case Builtin::BIlogf:
3065 case Builtin::BIlogl:
3066 case Builtin::BI__builtin_log:
3067 case Builtin::BI__builtin_logf:
3068 case Builtin::BI__builtin_logf16:
3069 case Builtin::BI__builtin_logl:
3070 case Builtin::BI__builtin_logf128:
3071 case Builtin::BI__builtin_elementwise_log:
3073 Intrinsic::log,
3074 Intrinsic::experimental_constrained_log));
3075
3076 case Builtin::BIlog10:
3077 case Builtin::BIlog10f:
3078 case Builtin::BIlog10l:
3079 case Builtin::BI__builtin_log10:
3080 case Builtin::BI__builtin_log10f:
3081 case Builtin::BI__builtin_log10f16:
3082 case Builtin::BI__builtin_log10l:
3083 case Builtin::BI__builtin_log10f128:
3084 case Builtin::BI__builtin_elementwise_log10:
3086 Intrinsic::log10,
3087 Intrinsic::experimental_constrained_log10));
3088
3089 case Builtin::BIlog2:
3090 case Builtin::BIlog2f:
3091 case Builtin::BIlog2l:
3092 case Builtin::BI__builtin_log2:
3093 case Builtin::BI__builtin_log2f:
3094 case Builtin::BI__builtin_log2f16:
3095 case Builtin::BI__builtin_log2l:
3096 case Builtin::BI__builtin_log2f128:
3097 case Builtin::BI__builtin_elementwise_log2:
3099 Intrinsic::log2,
3100 Intrinsic::experimental_constrained_log2));
3101
3102 case Builtin::BInearbyint:
3103 case Builtin::BInearbyintf:
3104 case Builtin::BInearbyintl:
3105 case Builtin::BI__builtin_nearbyint:
3106 case Builtin::BI__builtin_nearbyintf:
3107 case Builtin::BI__builtin_nearbyintl:
3108 case Builtin::BI__builtin_nearbyintf128:
3109 case Builtin::BI__builtin_elementwise_nearbyint:
3111 Intrinsic::nearbyint,
3112 Intrinsic::experimental_constrained_nearbyint));
3113
3114 case Builtin::BIpow:
3115 case Builtin::BIpowf:
3116 case Builtin::BIpowl:
3117 case Builtin::BI__builtin_pow:
3118 case Builtin::BI__builtin_powf:
3119 case Builtin::BI__builtin_powf16:
3120 case Builtin::BI__builtin_powl:
3121 case Builtin::BI__builtin_powf128:
3122 case Builtin::BI__builtin_elementwise_pow:
3124 Intrinsic::pow,
3125 Intrinsic::experimental_constrained_pow));
3126
3127 case Builtin::BIrint:
3128 case Builtin::BIrintf:
3129 case Builtin::BIrintl:
3130 case Builtin::BI__builtin_rint:
3131 case Builtin::BI__builtin_rintf:
3132 case Builtin::BI__builtin_rintf16:
3133 case Builtin::BI__builtin_rintl:
3134 case Builtin::BI__builtin_rintf128:
3135 case Builtin::BI__builtin_elementwise_rint:
3137 Intrinsic::rint,
3138 Intrinsic::experimental_constrained_rint));
3139
3140 case Builtin::BIround:
3141 case Builtin::BIroundf:
3142 case Builtin::BIroundl:
3143 case Builtin::BI__builtin_round:
3144 case Builtin::BI__builtin_roundf:
3145 case Builtin::BI__builtin_roundf16:
3146 case Builtin::BI__builtin_roundl:
3147 case Builtin::BI__builtin_roundf128:
3148 case Builtin::BI__builtin_elementwise_round:
3150 Intrinsic::round,
3151 Intrinsic::experimental_constrained_round));
3152
3153 case Builtin::BIroundeven:
3154 case Builtin::BIroundevenf:
3155 case Builtin::BIroundevenl:
3156 case Builtin::BI__builtin_roundeven:
3157 case Builtin::BI__builtin_roundevenf:
3158 case Builtin::BI__builtin_roundevenf16:
3159 case Builtin::BI__builtin_roundevenl:
3160 case Builtin::BI__builtin_roundevenf128:
3161 case Builtin::BI__builtin_elementwise_roundeven:
3163 Intrinsic::roundeven,
3164 Intrinsic::experimental_constrained_roundeven));
3165
3166 case Builtin::BIsin:
3167 case Builtin::BIsinf:
3168 case Builtin::BIsinl:
3169 case Builtin::BI__builtin_sin:
3170 case Builtin::BI__builtin_sinf:
3171 case Builtin::BI__builtin_sinf16:
3172 case Builtin::BI__builtin_sinl:
3173 case Builtin::BI__builtin_sinf128:
3174 case Builtin::BI__builtin_elementwise_sin:
3176 Intrinsic::sin,
3177 Intrinsic::experimental_constrained_sin));
3178
3179 case Builtin::BIsinh:
3180 case Builtin::BIsinhf:
3181 case Builtin::BIsinhl:
3182 case Builtin::BI__builtin_sinh:
3183 case Builtin::BI__builtin_sinhf:
3184 case Builtin::BI__builtin_sinhf16:
3185 case Builtin::BI__builtin_sinhl:
3186 case Builtin::BI__builtin_sinhf128:
3187 case Builtin::BI__builtin_elementwise_sinh:
3189 *this, E, Intrinsic::sinh, Intrinsic::experimental_constrained_sinh));
3190
3191 case Builtin::BI__builtin_sincospi:
3192 case Builtin::BI__builtin_sincospif:
3193 case Builtin::BI__builtin_sincospil:
3194 if (Builder.getIsFPConstrained())
3195 break; // TODO: Emit constrained sincospi intrinsic once one exists.
3196 emitSincosBuiltin(*this, E, Intrinsic::sincospi);
3197 return RValue::get(nullptr);
3198
3199 case Builtin::BIsincos:
3200 case Builtin::BIsincosf:
3201 case Builtin::BIsincosl:
3202 case Builtin::BI__builtin_sincos:
3203 case Builtin::BI__builtin_sincosf:
3204 case Builtin::BI__builtin_sincosf16:
3205 case Builtin::BI__builtin_sincosl:
3206 case Builtin::BI__builtin_sincosf128:
3207 if (Builder.getIsFPConstrained())
3208 break; // TODO: Emit constrained sincos intrinsic once one exists.
3209 emitSincosBuiltin(*this, E, Intrinsic::sincos);
3210 return RValue::get(nullptr);
3211
3212 case Builtin::BIsqrt:
3213 case Builtin::BIsqrtf:
3214 case Builtin::BIsqrtl:
3215 case Builtin::BI__builtin_sqrt:
3216 case Builtin::BI__builtin_sqrtf:
3217 case Builtin::BI__builtin_sqrtf16:
3218 case Builtin::BI__builtin_sqrtl:
3219 case Builtin::BI__builtin_sqrtf128:
3220 case Builtin::BI__builtin_elementwise_sqrt: {
3222 *this, E, Intrinsic::sqrt, Intrinsic::experimental_constrained_sqrt);
3224 return RValue::get(Call);
3225 }
3226
3227 case Builtin::BItan:
3228 case Builtin::BItanf:
3229 case Builtin::BItanl:
3230 case Builtin::BI__builtin_tan:
3231 case Builtin::BI__builtin_tanf:
3232 case Builtin::BI__builtin_tanf16:
3233 case Builtin::BI__builtin_tanl:
3234 case Builtin::BI__builtin_tanf128:
3235 case Builtin::BI__builtin_elementwise_tan:
3237 *this, E, Intrinsic::tan, Intrinsic::experimental_constrained_tan));
3238
3239 case Builtin::BItanh:
3240 case Builtin::BItanhf:
3241 case Builtin::BItanhl:
3242 case Builtin::BI__builtin_tanh:
3243 case Builtin::BI__builtin_tanhf:
3244 case Builtin::BI__builtin_tanhf16:
3245 case Builtin::BI__builtin_tanhl:
3246 case Builtin::BI__builtin_tanhf128:
3247 case Builtin::BI__builtin_elementwise_tanh:
3249 *this, E, Intrinsic::tanh, Intrinsic::experimental_constrained_tanh));
3250
3251 case Builtin::BItrunc:
3252 case Builtin::BItruncf:
3253 case Builtin::BItruncl:
3254 case Builtin::BI__builtin_trunc:
3255 case Builtin::BI__builtin_truncf:
3256 case Builtin::BI__builtin_truncf16:
3257 case Builtin::BI__builtin_truncl:
3258 case Builtin::BI__builtin_truncf128:
3259 case Builtin::BI__builtin_elementwise_trunc:
3261 Intrinsic::trunc,
3262 Intrinsic::experimental_constrained_trunc));
3263
3264 case Builtin::BIlround:
3265 case Builtin::BIlroundf:
3266 case Builtin::BIlroundl:
3267 case Builtin::BI__builtin_lround:
3268 case Builtin::BI__builtin_lroundf:
3269 case Builtin::BI__builtin_lroundl:
3270 case Builtin::BI__builtin_lroundf128:
3272 *this, E, Intrinsic::lround,
3273 Intrinsic::experimental_constrained_lround));
3274
3275 case Builtin::BIllround:
3276 case Builtin::BIllroundf:
3277 case Builtin::BIllroundl:
3278 case Builtin::BI__builtin_llround:
3279 case Builtin::BI__builtin_llroundf:
3280 case Builtin::BI__builtin_llroundl:
3281 case Builtin::BI__builtin_llroundf128:
3283 *this, E, Intrinsic::llround,
3284 Intrinsic::experimental_constrained_llround));
3285
3286 case Builtin::BIlrint:
3287 case Builtin::BIlrintf:
3288 case Builtin::BIlrintl:
3289 case Builtin::BI__builtin_lrint:
3290 case Builtin::BI__builtin_lrintf:
3291 case Builtin::BI__builtin_lrintl:
3292 case Builtin::BI__builtin_lrintf128:
3294 *this, E, Intrinsic::lrint,
3295 Intrinsic::experimental_constrained_lrint));
3296
3297 case Builtin::BIllrint:
3298 case Builtin::BIllrintf:
3299 case Builtin::BIllrintl:
3300 case Builtin::BI__builtin_llrint:
3301 case Builtin::BI__builtin_llrintf:
3302 case Builtin::BI__builtin_llrintl:
3303 case Builtin::BI__builtin_llrintf128:
3305 *this, E, Intrinsic::llrint,
3306 Intrinsic::experimental_constrained_llrint));
3307 case Builtin::BI__builtin_ldexp:
3308 case Builtin::BI__builtin_ldexpf:
3309 case Builtin::BI__builtin_ldexpl:
3310 case Builtin::BI__builtin_ldexpf16:
3311 case Builtin::BI__builtin_ldexpf128:
3312 case Builtin::BI__builtin_elementwise_ldexp:
3314 *this, E, Intrinsic::ldexp,
3315 Intrinsic::experimental_constrained_ldexp));
3316 default:
3317 break;
3318 }
3319 }
3320
3321 // Check NonnullAttribute/NullabilityArg and Alignment.
3322 auto EmitArgCheck = [&](TypeCheckKind Kind, Address A, const Expr *Arg,
3323 unsigned ParmNum) {
3324 Value *Val = A.emitRawPointer(*this);
3325 EmitNonNullArgCheck(RValue::get(Val), Arg->getType(), Arg->getExprLoc(), FD,
3326 ParmNum);
3327
3328 if (SanOpts.has(SanitizerKind::Alignment)) {
3329 SanitizerSet SkippedChecks;
3330 SkippedChecks.set(SanitizerKind::All);
3331 SkippedChecks.clear(SanitizerKind::Alignment);
3332 SourceLocation Loc = Arg->getExprLoc();
3333 // Strip an implicit cast.
3334 if (auto *CE = dyn_cast<ImplicitCastExpr>(Arg))
3335 if (CE->getCastKind() == CK_BitCast)
3336 Arg = CE->getSubExpr();
3337 EmitTypeCheck(Kind, Loc, Val, Arg->getType(), A.getAlignment(),
3338 SkippedChecks);
3339 }
3340 };
3341
3342 switch (BuiltinIDIfNoAsmLabel) {
3343 default: break;
3344 case Builtin::BI__builtin___CFStringMakeConstantString:
3345 case Builtin::BI__builtin___NSStringMakeConstantString:
3346 return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
3347 case Builtin::BI__builtin_stdarg_start:
3348 case Builtin::BI__builtin_va_start:
3349 case Builtin::BI__va_start:
3350 case Builtin::BI__builtin_c23_va_start:
3351 case Builtin::BI__builtin_va_end:
3352 EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
3353 ? EmitScalarExpr(E->getArg(0))
3354 : EmitVAListRef(E->getArg(0)).emitRawPointer(*this),
3355 BuiltinID != Builtin::BI__builtin_va_end);
3356 return RValue::get(nullptr);
3357 case Builtin::BI__builtin_va_copy: {
3358 Value *DstPtr = EmitVAListRef(E->getArg(0)).emitRawPointer(*this);
3359 Value *SrcPtr = EmitVAListRef(E->getArg(1)).emitRawPointer(*this);
3360 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy, {DstPtr->getType()}),
3361 {DstPtr, SrcPtr});
3362 return RValue::get(nullptr);
3363 }
3364 case Builtin::BIabs:
3365 case Builtin::BIlabs:
3366 case Builtin::BIllabs:
3367 case Builtin::BI__builtin_abs:
3368 case Builtin::BI__builtin_labs:
3369 case Builtin::BI__builtin_llabs: {
3370 bool SanitizeOverflow = SanOpts.has(SanitizerKind::SignedIntegerOverflow);
3371
3372 Value *Result;
3373 switch (getLangOpts().getSignedOverflowBehavior()) {
3375 Result = EmitAbs(*this, EmitScalarExpr(E->getArg(0)), false);
3376 break;
3378 if (!SanitizeOverflow) {
3379 Result = EmitAbs(*this, EmitScalarExpr(E->getArg(0)), true);
3380 break;
3381 }
3382 [[fallthrough]];
3384 // TODO: Somehow handle the corner case when the address of abs is taken.
3385 Result = EmitOverflowCheckedAbs(*this, E, SanitizeOverflow);
3386 break;
3387 }
3388 return RValue::get(Result);
3389 }
3390 case Builtin::BI__builtin_complex: {
3391 Value *Real = EmitScalarExpr(E->getArg(0));
3392 Value *Imag = EmitScalarExpr(E->getArg(1));
3393 return RValue::getComplex({Real, Imag});
3394 }
3395 case Builtin::BI__builtin_conj:
3396 case Builtin::BI__builtin_conjf:
3397 case Builtin::BI__builtin_conjl:
3398 case Builtin::BIconj:
3399 case Builtin::BIconjf:
3400 case Builtin::BIconjl: {
3401 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3402 Value *Real = ComplexVal.first;
3403 Value *Imag = ComplexVal.second;
3404 Imag = Builder.CreateFNeg(Imag, "neg");
3405 return RValue::getComplex(std::make_pair(Real, Imag));
3406 }
3407 case Builtin::BI__builtin_creal:
3408 case Builtin::BI__builtin_crealf:
3409 case Builtin::BI__builtin_creall:
3410 case Builtin::BIcreal:
3411 case Builtin::BIcrealf:
3412 case Builtin::BIcreall: {
3413 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3414 return RValue::get(ComplexVal.first);
3415 }
3416
3417 case Builtin::BI__builtin_preserve_access_index: {
3418 // Only enabled preserved access index region when debuginfo
3419 // is available as debuginfo is needed to preserve user-level
3420 // access pattern.
3421 if (!getDebugInfo()) {
3422 CGM.Error(E->getExprLoc(), "using builtin_preserve_access_index() without -g");
3423 return RValue::get(EmitScalarExpr(E->getArg(0)));
3424 }
3425
3426 // Nested builtin_preserve_access_index() not supported
3428 CGM.Error(E->getExprLoc(), "nested builtin_preserve_access_index() not supported");
3429 return RValue::get(EmitScalarExpr(E->getArg(0)));
3430 }
3431
3432 IsInPreservedAIRegion = true;
3433 Value *Res = EmitScalarExpr(E->getArg(0));
3434 IsInPreservedAIRegion = false;
3435 return RValue::get(Res);
3436 }
3437
3438 case Builtin::BI__builtin_cimag:
3439 case Builtin::BI__builtin_cimagf:
3440 case Builtin::BI__builtin_cimagl:
3441 case Builtin::BIcimag:
3442 case Builtin::BIcimagf:
3443 case Builtin::BIcimagl: {
3444 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3445 return RValue::get(ComplexVal.second);
3446 }
3447
3448 case Builtin::BI__builtin_clrsb:
3449 case Builtin::BI__builtin_clrsbl:
3450 case Builtin::BI__builtin_clrsbll: {
3451 // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or
3452 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3453
3454 llvm::Type *ArgType = ArgValue->getType();
3455 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3456
3457 llvm::Type *ResultType = ConvertType(E->getType());
3458 Value *Zero = llvm::Constant::getNullValue(ArgType);
3459 Value *IsNeg = Builder.CreateICmpSLT(ArgValue, Zero, "isneg");
3460 Value *Inverse = Builder.CreateNot(ArgValue, "not");
3461 Value *Tmp = Builder.CreateSelect(IsNeg, Inverse, ArgValue);
3462 Value *Ctlz = Builder.CreateCall(F, {Tmp, Builder.getFalse()});
3463 Value *Result =
3464 Builder.CreateNUWSub(Ctlz, llvm::ConstantInt::get(ArgType, 1));
3465 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3466 "cast");
3467 return RValue::get(Result);
3468 }
3469 case Builtin::BI__builtin_ctzs:
3470 case Builtin::BI__builtin_ctz:
3471 case Builtin::BI__builtin_ctzl:
3472 case Builtin::BI__builtin_ctzll:
3473 case Builtin::BI__builtin_ctzg:
3474 case Builtin::BI__builtin_elementwise_ctzg: {
3475 bool HasFallback =
3476 (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_ctzg ||
3477 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_ctzg) &&
3478 E->getNumArgs() > 1;
3479
3480 Value *ArgValue =
3481 HasFallback ? EmitBitCountExpr(*this, E->getArg(0))
3483
3484 llvm::Type *ArgType = ArgValue->getType();
3485 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
3486
3487 llvm::Type *ResultType = ConvertType(E->getType());
3488 // The elementwise builtins always exhibit zero-is-undef behaviour
3489 Value *ZeroUndef = Builder.getInt1(
3490 HasFallback || getTarget().isCLZForZeroUndef() ||
3491 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_ctzg);
3492 Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
3493 if (Result->getType() != ResultType)
3494 Result =
3495 Builder.CreateIntCast(Result, ResultType, /*isSigned*/ false, "cast");
3496 if (!HasFallback)
3497 return RValue::get(Result);
3498
3499 Value *Zero = Constant::getNullValue(ArgType);
3500 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
3501 Value *FallbackValue = EmitScalarExpr(E->getArg(1));
3502 Value *ResultOrFallback =
3503 Builder.CreateSelect(IsZero, FallbackValue, Result, "ctzg");
3504 return RValue::get(ResultOrFallback);
3505 }
3506 case Builtin::BI__builtin_clzs:
3507 case Builtin::BI__builtin_clz:
3508 case Builtin::BI__builtin_clzl:
3509 case Builtin::BI__builtin_clzll:
3510 case Builtin::BI__builtin_clzg:
3511 case Builtin::BI__builtin_elementwise_clzg: {
3512 bool HasFallback =
3513 (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_clzg ||
3514 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_clzg) &&
3515 E->getNumArgs() > 1;
3516
3517 Value *ArgValue =
3518 HasFallback ? EmitBitCountExpr(*this, E->getArg(0))
3520
3521 llvm::Type *ArgType = ArgValue->getType();
3522 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3523
3524 llvm::Type *ResultType = ConvertType(E->getType());
3525 // The elementwise builtins always exhibit zero-is-undef behaviour
3526 Value *ZeroUndef = Builder.getInt1(
3527 HasFallback || getTarget().isCLZForZeroUndef() ||
3528 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_clzg);
3529 Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
3530 if (Result->getType() != ResultType)
3531 Result =
3532 Builder.CreateIntCast(Result, ResultType, /*isSigned*/ false, "cast");
3533 if (!HasFallback)
3534 return RValue::get(Result);
3535
3536 Value *Zero = Constant::getNullValue(ArgType);
3537 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
3538 Value *FallbackValue = EmitScalarExpr(E->getArg(1));
3539 Value *ResultOrFallback =
3540 Builder.CreateSelect(IsZero, FallbackValue, Result, "clzg");
3541 return RValue::get(ResultOrFallback);
3542 }
3543 case Builtin::BI__builtin_ffs:
3544 case Builtin::BI__builtin_ffsl:
3545 case Builtin::BI__builtin_ffsll: {
3546 // ffs(x) -> x ? cttz(x) + 1 : 0
3547 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3548
3549 llvm::Type *ArgType = ArgValue->getType();
3550 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
3551
3552 llvm::Type *ResultType = ConvertType(E->getType());
3553 Value *Tmp =
3554 Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
3555 llvm::ConstantInt::get(ArgType, 1));
3556 Value *Zero = llvm::Constant::getNullValue(ArgType);
3557 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
3558 Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
3559 if (Result->getType() != ResultType)
3560 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3561 "cast");
3562 return RValue::get(Result);
3563 }
3564 case Builtin::BI__builtin_parity:
3565 case Builtin::BI__builtin_parityl:
3566 case Builtin::BI__builtin_parityll: {
3567 // parity(x) -> ctpop(x) & 1
3568 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3569
3570 llvm::Type *ArgType = ArgValue->getType();
3571 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
3572
3573 llvm::Type *ResultType = ConvertType(E->getType());
3574 Value *Tmp = Builder.CreateCall(F, ArgValue);
3575 Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
3576 if (Result->getType() != ResultType)
3577 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3578 "cast");
3579 return RValue::get(Result);
3580 }
3581 case Builtin::BI__lzcnt16:
3582 case Builtin::BI__lzcnt:
3583 case Builtin::BI__lzcnt64: {
3584 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3585
3586 llvm::Type *ArgType = ArgValue->getType();
3587 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3588
3589 llvm::Type *ResultType = ConvertType(E->getType());
3590 Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
3591 if (Result->getType() != ResultType)
3592 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3593 "cast");
3594 return RValue::get(Result);
3595 }
3596 case Builtin::BI__popcnt16:
3597 case Builtin::BI__popcnt:
3598 case Builtin::BI__popcnt64:
3599 case Builtin::BI__builtin_popcount:
3600 case Builtin::BI__builtin_popcountl:
3601 case Builtin::BI__builtin_popcountll:
3602 case Builtin::BI__builtin_popcountg: {
3603 Value *ArgValue = EmitBitCountExpr(*this, E->getArg(0));
3604
3605 llvm::Type *ArgType = ArgValue->getType();
3606 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
3607
3608 llvm::Type *ResultType = ConvertType(E->getType());
3609 Value *Result = Builder.CreateCall(F, ArgValue);
3610 if (Result->getType() != ResultType)
3611 Result =
3612 Builder.CreateIntCast(Result, ResultType, /*isSigned*/ false, "cast");
3613 return RValue::get(Result);
3614 }
3615 case Builtin::BI__builtin_unpredictable: {
3616 // Always return the argument of __builtin_unpredictable. LLVM does not
3617 // handle this builtin. Metadata for this builtin should be added directly
3618 // to instructions such as branches or switches that use it.
3619 return RValue::get(EmitScalarExpr(E->getArg(0)));
3620 }
3621 case Builtin::BI__builtin_expect: {
3622 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3623 llvm::Type *ArgType = ArgValue->getType();
3624
3625 Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
3626 // Don't generate llvm.expect on -O0 as the backend won't use it for
3627 // anything.
3628 // Note, we still IRGen ExpectedValue because it could have side-effects.
3629 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3630 return RValue::get(ArgValue);
3631
3632 Function *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
3633 Value *Result =
3634 Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
3635 return RValue::get(Result);
3636 }
3637 case Builtin::BI__builtin_expect_with_probability: {
3638 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3639 llvm::Type *ArgType = ArgValue->getType();
3640
3641 Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
3642 llvm::APFloat Probability(0.0);
3643 const Expr *ProbArg = E->getArg(2);
3644 bool EvalSucceed = ProbArg->EvaluateAsFloat(Probability, CGM.getContext());
3645 assert(EvalSucceed && "probability should be able to evaluate as float");
3646 (void)EvalSucceed;
3647 bool LoseInfo = false;
3648 Probability.convert(llvm::APFloat::IEEEdouble(),
3649 llvm::RoundingMode::Dynamic, &LoseInfo);
3650 llvm::Type *Ty = ConvertType(ProbArg->getType());
3651 Constant *Confidence = ConstantFP::get(Ty, Probability);
3652 // Don't generate llvm.expect.with.probability on -O0 as the backend
3653 // won't use it for anything.
3654 // Note, we still IRGen ExpectedValue because it could have side-effects.
3655 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3656 return RValue::get(ArgValue);
3657
3658 Function *FnExpect =
3659 CGM.getIntrinsic(Intrinsic::expect_with_probability, ArgType);
3660 Value *Result = Builder.CreateCall(
3661 FnExpect, {ArgValue, ExpectedValue, Confidence}, "expval");
3662 return RValue::get(Result);
3663 }
3664 case Builtin::BI__builtin_assume_aligned: {
3665 const Expr *Ptr = E->getArg(0);
3666 Value *PtrValue = EmitScalarExpr(Ptr);
3667 Value *OffsetValue =
3668 (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
3669
3670 Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
3671 ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
3672 if (AlignmentCI->getValue().ugt(llvm::Value::MaximumAlignment))
3673 AlignmentCI = ConstantInt::get(AlignmentCI->getIntegerType(),
3674 llvm::Value::MaximumAlignment);
3675
3676 emitAlignmentAssumption(PtrValue, Ptr,
3677 /*The expr loc is sufficient.*/ SourceLocation(),
3678 AlignmentCI, OffsetValue);
3679 return RValue::get(PtrValue);
3680 }
3681 case Builtin::BI__builtin_assume_dereferenceable: {
3682 const Expr *Ptr = E->getArg(0);
3683 const Expr *Size = E->getArg(1);
3684 Value *PtrValue = EmitScalarExpr(Ptr);
3685 Value *SizeValue = EmitScalarExpr(Size);
3686 if (SizeValue->getType() != IntPtrTy)
3687 SizeValue =
3688 Builder.CreateIntCast(SizeValue, IntPtrTy, false, "casted.size");
3689 Builder.CreateDereferenceableAssumption(PtrValue, SizeValue);
3690 return RValue::get(nullptr);
3691 }
3692 case Builtin::BI__assume:
3693 case Builtin::BI__builtin_assume: {
3694 if (E->getArg(0)->HasSideEffects(getContext()))
3695 return RValue::get(nullptr);
3696
3697 Value *ArgValue = EmitCheckedArgForAssume(E->getArg(0));
3698 Function *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
3699 Builder.CreateCall(FnAssume, ArgValue);
3700 return RValue::get(nullptr);
3701 }
3702 case Builtin::BI__builtin_assume_separate_storage: {
3703 const Expr *Arg0 = E->getArg(0);
3704 const Expr *Arg1 = E->getArg(1);
3705
3706 Value *Value0 = EmitScalarExpr(Arg0);
3707 Value *Value1 = EmitScalarExpr(Arg1);
3708
3709 Value *Values[] = {Value0, Value1};
3710 OperandBundleDefT<Value *> OBD("separate_storage", Values);
3711 Builder.CreateAssumption({OBD});
3712 return RValue::get(nullptr);
3713 }
3714 case Builtin::BI__builtin_allow_runtime_check: {
3715 StringRef Kind =
3716 cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())->getString();
3717 LLVMContext &Ctx = CGM.getLLVMContext();
3718 llvm::Value *Allow = Builder.CreateCall(
3719 CGM.getIntrinsic(Intrinsic::allow_runtime_check),
3720 llvm::MetadataAsValue::get(Ctx, llvm::MDString::get(Ctx, Kind)));
3721 return RValue::get(Allow);
3722 }
3723 case Builtin::BI__builtin_allow_sanitize_check: {
3724 Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
3725 StringRef Name =
3726 cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())->getString();
3727
3728 // We deliberately allow the use of kernel- and non-kernel names
3729 // interchangably, even when one or the other is enabled. This is consistent
3730 // with the no_sanitize-attribute, which allows either kernel- or non-kernel
3731 // name to disable instrumentation (see CodeGenFunction::StartFunction).
3732 if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
3733 SanitizerKind::KernelAddress) &&
3734 (Name == "address" || Name == "kernel-address")) {
3735 IntrID = Intrinsic::allow_sanitize_address;
3736 } else if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
3737 Name == "thread") {
3738 IntrID = Intrinsic::allow_sanitize_thread;
3739 } else if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Memory |
3740 SanitizerKind::KernelMemory) &&
3741 (Name == "memory" || Name == "kernel-memory")) {
3742 IntrID = Intrinsic::allow_sanitize_memory;
3743 } else if (getLangOpts().Sanitize.hasOneOf(
3744 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress) &&
3745 (Name == "hwaddress" || Name == "kernel-hwaddress")) {
3746 IntrID = Intrinsic::allow_sanitize_hwaddress;
3747 }
3748
3749 if (IntrID != Intrinsic::not_intrinsic) {
3750 llvm::Value *Allow = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3751 return RValue::get(Allow);
3752 }
3753 // If the checked sanitizer is not enabled, we can safely lower to false
3754 // right away. This is also more efficient, since the LowerAllowCheckPass
3755 // must not always be enabled if none of the above sanitizers are enabled.
3756 return RValue::get(Builder.getFalse());
3757 }
3758 case Builtin::BI__arithmetic_fence: {
3759 // Create the builtin call if FastMath is selected, and the target
3760 // supports the builtin, otherwise just return the argument.
3761 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3762 llvm::FastMathFlags FMF = Builder.getFastMathFlags();
3763 bool isArithmeticFenceEnabled =
3764 FMF.allowReassoc() &&
3766 QualType ArgType = E->getArg(0)->getType();
3767 if (ArgType->isComplexType()) {
3768 if (isArithmeticFenceEnabled) {
3769 QualType ElementType = ArgType->castAs<ComplexType>()->getElementType();
3770 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3771 Value *Real = Builder.CreateArithmeticFence(ComplexVal.first,
3772 ConvertType(ElementType));
3773 Value *Imag = Builder.CreateArithmeticFence(ComplexVal.second,
3774 ConvertType(ElementType));
3775 return RValue::getComplex(std::make_pair(Real, Imag));
3776 }
3777 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3778 Value *Real = ComplexVal.first;
3779 Value *Imag = ComplexVal.second;
3780 return RValue::getComplex(std::make_pair(Real, Imag));
3781 }
3782 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3783 if (isArithmeticFenceEnabled)
3784 return RValue::get(
3785 Builder.CreateArithmeticFence(ArgValue, ConvertType(ArgType)));
3786 return RValue::get(ArgValue);
3787 }
3788 case Builtin::BI__builtin_bswapg: {
3789 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3790 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(ArgValue->getType());
3791 assert(IntTy && "LLVM's __builtin_bswapg only supports integer variants");
3792 if (IntTy->getBitWidth() == 1 || IntTy->getBitWidth() == 8)
3793 return RValue::get(ArgValue);
3794 assert(((IntTy->getBitWidth() % 16 == 0 && IntTy->getBitWidth() != 0)) &&
3795 "LLVM's __builtin_bswapg only supports integer variants that has a "
3796 "multiple of 16 bits as well as a single byte");
3797 return RValue::get(
3798 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
3799 }
3800 case Builtin::BI__builtin_bswap16:
3801 case Builtin::BI__builtin_bswap32:
3802 case Builtin::BI__builtin_bswap64:
3803 case Builtin::BI_byteswap_ushort:
3804 case Builtin::BI_byteswap_ulong:
3805 case Builtin::BI_byteswap_uint64: {
3806 return RValue::get(
3807 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
3808 }
3809 case Builtin::BI__builtin_bitreverseg: {
3810 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3811 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(ArgValue->getType());
3812 assert(IntTy &&
3813 "LLVM's __builtin_bitreverseg only support integer variants");
3814 if (IntTy->getBitWidth() == 1)
3815 return RValue::get(ArgValue);
3816 return RValue::get(
3817 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bitreverse));
3818 }
3819 case Builtin::BI__builtin_bitreverse8:
3820 case Builtin::BI__builtin_bitreverse16:
3821 case Builtin::BI__builtin_bitreverse32:
3822 case Builtin::BI__builtin_bitreverse64: {
3823 return RValue::get(
3824 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bitreverse));
3825 }
3826 case Builtin::BI__builtin_rotateleft8:
3827 case Builtin::BI__builtin_rotateleft16:
3828 case Builtin::BI__builtin_rotateleft32:
3829 case Builtin::BI__builtin_rotateleft64:
3830 case Builtin::BI__builtin_stdc_rotate_left:
3831 case Builtin::BIstdc_rotate_left_uc:
3832 case Builtin::BIstdc_rotate_left_us:
3833 case Builtin::BIstdc_rotate_left_ui:
3834 case Builtin::BIstdc_rotate_left_ul:
3835 case Builtin::BIstdc_rotate_left_ull:
3836 case Builtin::BI_rotl8: // Microsoft variants of rotate left
3837 case Builtin::BI_rotl16:
3838 case Builtin::BI_rotl:
3839 case Builtin::BI_lrotl:
3840 case Builtin::BI_rotl64:
3841 return emitRotate(E, false);
3842
3843 case Builtin::BI__builtin_rotateright8:
3844 case Builtin::BI__builtin_rotateright16:
3845 case Builtin::BI__builtin_rotateright32:
3846 case Builtin::BI__builtin_rotateright64:
3847 case Builtin::BI__builtin_stdc_rotate_right:
3848 case Builtin::BIstdc_rotate_right_uc:
3849 case Builtin::BIstdc_rotate_right_us:
3850 case Builtin::BIstdc_rotate_right_ui:
3851 case Builtin::BIstdc_rotate_right_ul:
3852 case Builtin::BIstdc_rotate_right_ull:
3853 case Builtin::BI_rotr8: // Microsoft variants of rotate right
3854 case Builtin::BI_rotr16:
3855 case Builtin::BI_rotr:
3856 case Builtin::BI_lrotr:
3857 case Builtin::BI_rotr64:
3858 return emitRotate(E, true);
3859
3860 case Builtin::BIstdc_leading_zeros_uc:
3861 case Builtin::BIstdc_leading_zeros_us:
3862 case Builtin::BIstdc_leading_zeros_ui:
3863 case Builtin::BIstdc_leading_zeros_ul:
3864 case Builtin::BIstdc_leading_zeros_ull:
3865 case Builtin::BI__builtin_stdc_leading_zeros:
3866 return emitStdcCountIntrinsic(E, Intrinsic::ctlz, /*InvertArg=*/false);
3867 case Builtin::BIstdc_leading_ones_uc:
3868 case Builtin::BIstdc_leading_ones_us:
3869 case Builtin::BIstdc_leading_ones_ui:
3870 case Builtin::BIstdc_leading_ones_ul:
3871 case Builtin::BIstdc_leading_ones_ull:
3872 case Builtin::BI__builtin_stdc_leading_ones:
3873 return emitStdcCountIntrinsic(E, Intrinsic::ctlz, /*InvertArg=*/true);
3874 case Builtin::BIstdc_trailing_zeros_uc:
3875 case Builtin::BIstdc_trailing_zeros_us:
3876 case Builtin::BIstdc_trailing_zeros_ui:
3877 case Builtin::BIstdc_trailing_zeros_ul:
3878 case Builtin::BIstdc_trailing_zeros_ull:
3879 case Builtin::BI__builtin_stdc_trailing_zeros:
3880 return emitStdcCountIntrinsic(E, Intrinsic::cttz, /*InvertArg=*/false);
3881 case Builtin::BIstdc_trailing_ones_uc:
3882 case Builtin::BIstdc_trailing_ones_us:
3883 case Builtin::BIstdc_trailing_ones_ui:
3884 case Builtin::BIstdc_trailing_ones_ul:
3885 case Builtin::BIstdc_trailing_ones_ull:
3886 case Builtin::BI__builtin_stdc_trailing_ones:
3887 return emitStdcCountIntrinsic(E, Intrinsic::cttz, /*InvertArg=*/true);
3888 case Builtin::BIstdc_first_leading_zero_uc:
3889 case Builtin::BIstdc_first_leading_zero_us:
3890 case Builtin::BIstdc_first_leading_zero_ui:
3891 case Builtin::BIstdc_first_leading_zero_ul:
3892 case Builtin::BIstdc_first_leading_zero_ull:
3893 case Builtin::BI__builtin_stdc_first_leading_zero:
3894 return emitStdcFirstBit(E, Intrinsic::ctlz, /*InvertArg=*/true);
3895 case Builtin::BIstdc_first_leading_one_uc:
3896 case Builtin::BIstdc_first_leading_one_us:
3897 case Builtin::BIstdc_first_leading_one_ui:
3898 case Builtin::BIstdc_first_leading_one_ul:
3899 case Builtin::BIstdc_first_leading_one_ull:
3900 case Builtin::BI__builtin_stdc_first_leading_one:
3901 return emitStdcFirstBit(E, Intrinsic::ctlz, /*InvertArg=*/false);
3902 case Builtin::BIstdc_first_trailing_zero_uc:
3903 case Builtin::BIstdc_first_trailing_zero_us:
3904 case Builtin::BIstdc_first_trailing_zero_ui:
3905 case Builtin::BIstdc_first_trailing_zero_ul:
3906 case Builtin::BIstdc_first_trailing_zero_ull:
3907 case Builtin::BI__builtin_stdc_first_trailing_zero:
3908 return emitStdcFirstBit(E, Intrinsic::cttz, /*InvertArg=*/true);
3909 case Builtin::BIstdc_first_trailing_one_uc:
3910 case Builtin::BIstdc_first_trailing_one_us:
3911 case Builtin::BIstdc_first_trailing_one_ui:
3912 case Builtin::BIstdc_first_trailing_one_ul:
3913 case Builtin::BIstdc_first_trailing_one_ull:
3914 case Builtin::BI__builtin_stdc_first_trailing_one:
3915 return emitStdcFirstBit(E, Intrinsic::cttz, /*InvertArg=*/false);
3916 case Builtin::BIstdc_count_zeros_uc:
3917 case Builtin::BIstdc_count_zeros_us:
3918 case Builtin::BIstdc_count_zeros_ui:
3919 case Builtin::BIstdc_count_zeros_ul:
3920 case Builtin::BIstdc_count_zeros_ull:
3921 case Builtin::BI__builtin_stdc_count_zeros:
3922 return emitStdcBitWidthMinus(E, Intrinsic::ctpop, /*IsPop=*/true);
3923 case Builtin::BIstdc_count_ones_uc:
3924 case Builtin::BIstdc_count_ones_us:
3925 case Builtin::BIstdc_count_ones_ui:
3926 case Builtin::BIstdc_count_ones_ul:
3927 case Builtin::BIstdc_count_ones_ull:
3928 case Builtin::BI__builtin_stdc_count_ones:
3929 return emitStdcCountIntrinsic(E, Intrinsic::ctpop, /*InvertArg=*/false,
3930 /*IsPop=*/true);
3931 case Builtin::BIstdc_has_single_bit_uc:
3932 case Builtin::BIstdc_has_single_bit_us:
3933 case Builtin::BIstdc_has_single_bit_ui:
3934 case Builtin::BIstdc_has_single_bit_ul:
3935 case Builtin::BIstdc_has_single_bit_ull:
3936 case Builtin::BI__builtin_stdc_has_single_bit: {
3937 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3938 llvm::Type *ArgType = ArgValue->getType();
3939 Value *One = ConstantInt::get(ArgType, 1);
3940 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
3941 Value *PopCnt = Builder.CreateCall(F, ArgValue);
3942 return RValue::get(Builder.CreateICmpEQ(PopCnt, One));
3943 }
3944 case Builtin::BIstdc_bit_width_uc:
3945 case Builtin::BIstdc_bit_width_us:
3946 case Builtin::BIstdc_bit_width_ui:
3947 case Builtin::BIstdc_bit_width_ul:
3948 case Builtin::BIstdc_bit_width_ull:
3949 case Builtin::BI__builtin_stdc_bit_width:
3950 return emitStdcBitWidthMinus(E, Intrinsic::ctlz, /*IsPop=*/false);
3951 case Builtin::BIstdc_bit_floor_uc:
3952 case Builtin::BIstdc_bit_floor_us:
3953 case Builtin::BIstdc_bit_floor_ui:
3954 case Builtin::BIstdc_bit_floor_ul:
3955 case Builtin::BIstdc_bit_floor_ull:
3956 case Builtin::BI__builtin_stdc_bit_floor: {
3957 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3958 llvm::Type *ArgType = ArgValue->getType();
3959 unsigned BitWidth = ArgType->getIntegerBitWidth();
3960 Value *Zero = ConstantInt::get(ArgType, 0);
3961 Value *One = ConstantInt::get(ArgType, 1);
3962 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3963 Value *LZ = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
3964 Value *ShiftAmt =
3965 Builder.CreateSub(ConstantInt::get(ArgType, BitWidth - 1), LZ);
3966 Value *Shifted = Builder.CreateShl(One, ShiftAmt);
3967 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero);
3968 Value *Result = Builder.CreateSelect(IsZero, Zero, Shifted);
3969 return RValue::get(Result);
3970 }
3971 case Builtin::BIstdc_bit_ceil_uc:
3972 case Builtin::BIstdc_bit_ceil_us:
3973 case Builtin::BIstdc_bit_ceil_ui:
3974 case Builtin::BIstdc_bit_ceil_ul:
3975 case Builtin::BIstdc_bit_ceil_ull:
3976 case Builtin::BI__builtin_stdc_bit_ceil: {
3977 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3978 llvm::Type *ArgType = ArgValue->getType();
3979 Value *One = ConstantInt::get(ArgType, 1);
3980 Value *IsLEOne = Builder.CreateICmpULE(ArgValue, One, "isleone");
3981
3982 BasicBlock *EntryBB = Builder.GetInsertBlock();
3983 BasicBlock *CalcBB = createBasicBlock("bitceil.calc", CurFn);
3984 BasicBlock *MergeBB = createBasicBlock("bitceil.merge", CurFn);
3985
3986 Builder.CreateCondBr(IsLEOne, MergeBB, CalcBB);
3987
3988 Builder.SetInsertPoint(CalcBB);
3989 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3990 Value *ArgMinusOne = Builder.CreateSub(ArgValue, One);
3991 Value *LZ = Builder.CreateCall(F, {ArgMinusOne, Builder.getFalse()});
3992 // 2<<(BitWidth-1-LZ) to get the next power of two. The shift
3993 // amount is always in [0, BitWidth-1], so when LZ==0 (argument has its MSB
3994 // set), the result wraps to 0
3995 unsigned BitWidth = ArgType->getIntegerBitWidth();
3996 Value *ShiftAmt =
3997 Builder.CreateSub(ConstantInt::get(ArgType, BitWidth - 1), LZ);
3998 Value *Two = Builder.CreateShl(One, One);
3999 Value *Tmp = Builder.CreateShl(Two, ShiftAmt);
4000 Builder.CreateBr(MergeBB);
4001
4002 Builder.SetInsertPoint(MergeBB);
4003 PHINode *Phi = Builder.CreatePHI(ArgType, 2);
4004 Phi->addIncoming(One, EntryBB);
4005 Phi->addIncoming(Tmp, CalcBB);
4006 return RValue::get(Phi);
4007 }
4008
4009 // stdc_memreverse8u8 is a no-op (single byte, nothing to swap).
4010 case Builtin::BIstdc_memreverse8u8:
4011 return RValue::get(EmitScalarExpr(E->getArg(0)));
4012
4013 case Builtin::BIstdc_memreverse8u16:
4014 case Builtin::BIstdc_memreverse8u32:
4015 case Builtin::BIstdc_memreverse8u64:
4016 return RValue::get(
4017 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
4018
4019 case Builtin::BIstdc_memreverse8:
4020 case Builtin::BI__builtin_stdc_memreverse8: {
4022 if (E->getArg(0)->EvaluateAsInt(R, getContext())) {
4023 uint64_t Size = R.Val.getInt().getZExtValue();
4024 if (Size <= 1) {
4025 EmitIgnoredExpr(E->getArg(1));
4026 return RValue::get(nullptr);
4027 }
4028 if (Size == 2 || Size == 4 || Size == 8) {
4029 llvm::Type *IntTy = Builder.getIntNTy(Size * 8);
4030 Address PtrAddr = EmitPointerWithAlignment(E->getArg(1));
4031 Address Addr = PtrAddr.withElementType(IntTy);
4032 Value *Val = Builder.CreateLoad(Addr);
4033 Function *F = CGM.getIntrinsic(Intrinsic::bswap, IntTy);
4034 Value *Swapped = Builder.CreateCall(F, Val);
4035 Builder.CreateStore(Swapped, Addr);
4036 return RValue::get(nullptr);
4037 }
4038 }
4039
4040 // General case: fall back to the library function stdc_memreverse8.
4041 break;
4042 }
4043
4044 case Builtin::BI__builtin_constant_p: {
4045 llvm::Type *ResultType = ConvertType(E->getType());
4046
4047 const Expr *Arg = E->getArg(0);
4048 QualType ArgType = Arg->getType();
4049 // FIXME: The allowance for Obj-C pointers and block pointers is historical
4050 // and likely a mistake.
4051 if (!ArgType->isIntegralOrEnumerationType() && !ArgType->isFloatingType() &&
4052 !ArgType->isObjCObjectPointerType() && !ArgType->isBlockPointerType())
4053 // Per the GCC documentation, only numeric constants are recognized after
4054 // inlining.
4055 return RValue::get(ConstantInt::get(ResultType, 0));
4056
4057 if (Arg->HasSideEffects(getContext()))
4058 // The argument is unevaluated, so be conservative if it might have
4059 // side-effects.
4060 return RValue::get(ConstantInt::get(ResultType, 0));
4061
4062 Value *ArgValue = EmitScalarExpr(Arg);
4063 if (ArgType->isObjCObjectPointerType()) {
4064 // Convert Objective-C objects to id because we cannot distinguish between
4065 // LLVM types for Obj-C classes as they are opaque.
4066 ArgType = CGM.getContext().getObjCIdType();
4067 ArgValue = Builder.CreateBitCast(ArgValue, ConvertType(ArgType));
4068 }
4069 Function *F =
4070 CGM.getIntrinsic(Intrinsic::is_constant, ConvertType(ArgType));
4071 Value *Result = Builder.CreateCall(F, ArgValue);
4072 if (Result->getType() != ResultType)
4073 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/false);
4074 return RValue::get(Result);
4075 }
4076 case Builtin::BI__builtin_dynamic_object_size:
4077 case Builtin::BI__builtin_object_size: {
4078 unsigned Type =
4079 E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
4080 auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
4081
4082 // We pass this builtin onto the optimizer so that it can figure out the
4083 // object size in more complex cases.
4084 bool IsDynamic = BuiltinID == Builtin::BI__builtin_dynamic_object_size;
4085 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
4086 /*EmittedE=*/nullptr, IsDynamic));
4087 }
4088 case Builtin::BI__builtin_counted_by_ref: {
4089 // Default to returning '(void *) 0'.
4090 llvm::Value *Result = llvm::ConstantPointerNull::get(
4091 llvm::PointerType::getUnqual(getLLVMContext()));
4092
4093 const Expr *Arg = E->getArg(0)->IgnoreParenImpCasts();
4094
4095 if (auto *UO = dyn_cast<UnaryOperator>(Arg);
4096 UO && UO->getOpcode() == UO_AddrOf) {
4097 Arg = UO->getSubExpr()->IgnoreParenImpCasts();
4098
4099 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Arg))
4100 Arg = ASE->getBase()->IgnoreParenImpCasts();
4101 }
4102
4103 if (const MemberExpr *ME = dyn_cast_if_present<MemberExpr>(Arg)) {
4104 if (auto *CATy =
4106 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
4107 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
4108 if (const FieldDecl *CountFD = MemberDecl->findCountedByField())
4109 Result = GetCountedByFieldExprGEP(Arg, MemberDecl, CountFD);
4110 else
4111 llvm::report_fatal_error("Cannot find the counted_by 'count' field");
4112 }
4113 }
4114
4115 return RValue::get(Result);
4116 }
4117 case Builtin::BI__builtin_prefetch: {
4118 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
4119 unsigned ICEArguments = (1 << 1) | (1 << 2);
4120 // FIXME: Technically these constants should of type 'int', yes?
4121 RW = (E->getNumArgs() > 1) ? EmitScalarOrConstFoldImmArg(ICEArguments, 1, E)
4122 : llvm::ConstantInt::get(Int32Ty, 0);
4123 Locality = (E->getNumArgs() > 2)
4124 ? EmitScalarOrConstFoldImmArg(ICEArguments, 2, E)
4125 : llvm::ConstantInt::get(Int32Ty, 3);
4126 Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
4127 Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
4128 Builder.CreateCall(F, {Address, RW, Locality, Data});
4129 return RValue::get(nullptr);
4130 }
4131 case Builtin::BI__builtin_readcyclecounter: {
4132 Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
4133 return RValue::get(Builder.CreateCall(F));
4134 }
4135 case Builtin::BI__builtin_readsteadycounter: {
4136 Function *F = CGM.getIntrinsic(Intrinsic::readsteadycounter);
4137 return RValue::get(Builder.CreateCall(F));
4138 }
4139 case Builtin::BI__builtin___clear_cache: {
4140 Value *Begin = EmitScalarExpr(E->getArg(0));
4141 Value *End = EmitScalarExpr(E->getArg(1));
4142 Function *F = CGM.getIntrinsic(Intrinsic::clear_cache, {CGM.DefaultPtrTy});
4143 return RValue::get(Builder.CreateCall(F, {Begin, End}));
4144 }
4145 case Builtin::BI__builtin_trap:
4146 EmitTrapCall(Intrinsic::trap);
4147 return RValue::get(nullptr);
4148 case Builtin::BI__builtin_verbose_trap: {
4149 llvm::DebugLoc CallLocation = Builder.getCurrentDebugLocation();
4150 llvm::DILocation *TrapLocation = CallLocation;
4151 if (getDebugInfo()) {
4152 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4153 TrapLocation, *E->getArg(0)->tryEvaluateString(getContext()),
4155 // Keep the trap on the builtin's source line. A line-zero location would
4156 // leave the trap attributed to the preceding line in the line table.
4157 TrapLocation = llvm::DILocation::get(
4158 getLLVMContext(), CallLocation.getLine(), CallLocation.getCol(),
4159 TrapLocation->getScope(), TrapLocation->getInlinedAt());
4160 }
4161 ApplyDebugLocation ApplyTrapDI(*this, TrapLocation);
4162 // Currently no attempt is made to prevent traps from being merged.
4163 EmitTrapCall(Intrinsic::trap);
4164 return RValue::get(nullptr);
4165 }
4166 case Builtin::BI__debugbreak:
4167 EmitTrapCall(Intrinsic::debugtrap);
4168 return RValue::get(nullptr);
4169 case Builtin::BI__builtin_unreachable: {
4171
4172 // We do need to preserve an insertion point.
4173 EmitBlock(createBasicBlock("unreachable.cont"));
4174
4175 return RValue::get(nullptr);
4176 }
4177
4178 case Builtin::BI__builtin_powi:
4179 case Builtin::BI__builtin_powif:
4180 case Builtin::BI__builtin_powil: {
4181 llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
4182 llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
4183
4184 if (Builder.getIsFPConstrained()) {
4185 // FIXME: llvm.powi has 2 mangling types,
4186 // llvm.experimental.constrained.powi has one.
4187 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4188 Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_powi,
4189 Src0->getType());
4190 return RValue::get(Builder.CreateConstrainedFPCall(F, { Src0, Src1 }));
4191 }
4192
4193 Function *F = CGM.getIntrinsic(Intrinsic::powi,
4194 { Src0->getType(), Src1->getType() });
4195 return RValue::get(Builder.CreateCall(F, { Src0, Src1 }));
4196 }
4197 case Builtin::BI__builtin_frexpl: {
4198 // Linux PPC will not be adding additional PPCDoubleDouble support.
4199 // WIP to switch default to IEEE long double. Will emit libcall for
4200 // frexpl instead of legalizing this type in the BE.
4201 if (&getTarget().getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())
4202 break;
4203 [[fallthrough]];
4204 }
4205 case Builtin::BI__builtin_frexp:
4206 case Builtin::BI__builtin_frexpf:
4207 case Builtin::BI__builtin_frexpf128:
4208 case Builtin::BI__builtin_frexpf16:
4209 return RValue::get(emitFrexpBuiltin(*this, E, Intrinsic::frexp));
4210 case Builtin::BImodf:
4211 case Builtin::BImodff:
4212 case Builtin::BImodfl:
4213 case Builtin::BI__builtin_modf:
4214 case Builtin::BI__builtin_modff:
4215 case Builtin::BI__builtin_modfl:
4216 if (Builder.getIsFPConstrained())
4217 break; // TODO: Emit constrained modf intrinsic once one exists.
4218 return RValue::get(emitModfBuiltin(*this, E, Intrinsic::modf));
4219 case Builtin::BI__builtin_isgreater:
4220 case Builtin::BI__builtin_isgreaterequal:
4221 case Builtin::BI__builtin_isless:
4222 case Builtin::BI__builtin_islessequal:
4223 case Builtin::BI__builtin_islessgreater:
4224 case Builtin::BI__builtin_isunordered: {
4225 // Ordered comparisons: we know the arguments to these are matching scalar
4226 // floating point values.
4227 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4228 Value *LHS = EmitScalarExpr(E->getArg(0));
4229 Value *RHS = EmitScalarExpr(E->getArg(1));
4230
4231 switch (BuiltinID) {
4232 default: llvm_unreachable("Unknown ordered comparison");
4233 case Builtin::BI__builtin_isgreater:
4234 LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
4235 break;
4236 case Builtin::BI__builtin_isgreaterequal:
4237 LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
4238 break;
4239 case Builtin::BI__builtin_isless:
4240 LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
4241 break;
4242 case Builtin::BI__builtin_islessequal:
4243 LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
4244 break;
4245 case Builtin::BI__builtin_islessgreater:
4246 LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
4247 break;
4248 case Builtin::BI__builtin_isunordered:
4249 LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
4250 break;
4251 }
4252 // ZExt bool to int type.
4253 return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
4254 }
4255
4256 case Builtin::BI__builtin_isnan: {
4257 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4258 Value *V = EmitScalarExpr(E->getArg(0));
4259 if (Value *Result = tryUseTestFPKind(*this, BuiltinID, V))
4260 return RValue::get(Result);
4261 return RValue::get(
4262 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcNan),
4263 ConvertType(E->getType())));
4264 }
4265
4266 case Builtin::BI__builtin_issignaling: {
4267 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4268 Value *V = EmitScalarExpr(E->getArg(0));
4269 return RValue::get(
4270 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcSNan),
4271 ConvertType(E->getType())));
4272 }
4273
4274 case Builtin::BI__builtin_isinf: {
4275 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4276 Value *V = EmitScalarExpr(E->getArg(0));
4277 if (Value *Result = tryUseTestFPKind(*this, BuiltinID, V))
4278 return RValue::get(Result);
4279 return RValue::get(
4280 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcInf),
4281 ConvertType(E->getType())));
4282 }
4283
4284 case Builtin::BIfinite:
4285 case Builtin::BI__finite:
4286 case Builtin::BIfinitef:
4287 case Builtin::BI__finitef:
4288 case Builtin::BIfinitel:
4289 case Builtin::BI__finitel:
4290 case Builtin::BI__builtin_isfinite: {
4291 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4292 Value *V = EmitScalarExpr(E->getArg(0));
4293 if (Value *Result = tryUseTestFPKind(*this, BuiltinID, V))
4294 return RValue::get(Result);
4295 return RValue::get(
4296 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcFinite),
4297 ConvertType(E->getType())));
4298 }
4299
4300 case Builtin::BI__builtin_isnormal: {
4301 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4302 Value *V = EmitScalarExpr(E->getArg(0));
4303 return RValue::get(
4304 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcNormal),
4305 ConvertType(E->getType())));
4306 }
4307
4308 case Builtin::BI__builtin_issubnormal: {
4309 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4310 Value *V = EmitScalarExpr(E->getArg(0));
4311 return RValue::get(
4312 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcSubnormal),
4313 ConvertType(E->getType())));
4314 }
4315
4316 case Builtin::BI__builtin_iszero: {
4317 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4318 Value *V = EmitScalarExpr(E->getArg(0));
4319 return RValue::get(
4320 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcZero),
4321 ConvertType(E->getType())));
4322 }
4323
4324 case Builtin::BI__builtin_isfpclass: {
4326 if (!E->getArg(1)->EvaluateAsInt(Result, CGM.getContext()))
4327 break;
4328 uint64_t Test = Result.Val.getInt().getLimitedValue();
4329 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4330 Value *V = EmitScalarExpr(E->getArg(0));
4331 return RValue::get(Builder.CreateZExt(Builder.createIsFPClass(V, Test),
4332 ConvertType(E->getType())));
4333 }
4334
4335 case Builtin::BI__builtin_nondeterministic_value: {
4336 llvm::Type *Ty = ConvertType(E->getArg(0)->getType());
4337
4338 Value *Result = PoisonValue::get(Ty);
4339 Result = Builder.CreateFreeze(Result);
4340
4341 return RValue::get(Result);
4342 }
4343
4344 case Builtin::BI__builtin_elementwise_abs: {
4345 Value *Result;
4346 QualType QT = E->getArg(0)->getType();
4347
4348 if (auto *VecTy = QT->getAs<VectorType>())
4349 QT = VecTy->getElementType();
4350 if (QT->isIntegerType())
4351 Result = Builder.CreateBinaryIntrinsic(
4352 Intrinsic::abs, EmitScalarExpr(E->getArg(0)), Builder.getFalse(),
4353 nullptr, "elt.abs");
4354 else
4355 Result = emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::fabs,
4356 "elt.abs");
4357
4358 return RValue::get(Result);
4359 }
4360 case Builtin::BI__builtin_elementwise_bitreverse:
4362 *this, E, Intrinsic::bitreverse, "elt.bitreverse"));
4363 case Builtin::BI__builtin_elementwise_popcount:
4365 *this, E, Intrinsic::ctpop, "elt.ctpop"));
4366 case Builtin::BI__builtin_elementwise_canonicalize:
4368 *this, E, Intrinsic::canonicalize, "elt.canonicalize"));
4369 case Builtin::BI__builtin_elementwise_copysign:
4370 return RValue::get(
4371 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::copysign));
4372 case Builtin::BI__builtin_elementwise_fshl:
4373 return RValue::get(
4374 emitBuiltinWithOneOverloadedType<3>(*this, E, Intrinsic::fshl));
4375 case Builtin::BI__builtin_elementwise_fshr:
4376 return RValue::get(
4377 emitBuiltinWithOneOverloadedType<3>(*this, E, Intrinsic::fshr));
4378 case Builtin::BI__builtin_elementwise_clmul:
4379 return RValue::get(
4380 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::clmul));
4381 case Builtin::BI__builtin_elementwise_pext:
4382 return RValue::get(
4383 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::pext));
4384 case Builtin::BI__builtin_elementwise_pdep:
4385 return RValue::get(
4386 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::pdep));
4387
4388 case Builtin::BI__builtin_elementwise_add_sat:
4389 case Builtin::BI__builtin_elementwise_sub_sat: {
4390 Value *Op0 = EmitScalarExpr(E->getArg(0));
4391 Value *Op1 = EmitScalarExpr(E->getArg(1));
4392 Value *Result;
4393 assert(Op0->getType()->isIntOrIntVectorTy() && "integer type expected");
4394 QualType Ty = E->getArg(0)->getType();
4395 if (auto *VecTy = Ty->getAs<VectorType>())
4396 Ty = VecTy->getElementType();
4397 bool IsSigned = Ty->isSignedIntegerType();
4398 unsigned Opc;
4399 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_add_sat)
4400 Opc = IsSigned ? Intrinsic::sadd_sat : Intrinsic::uadd_sat;
4401 else
4402 Opc = IsSigned ? Intrinsic::ssub_sat : Intrinsic::usub_sat;
4403 Result = Builder.CreateBinaryIntrinsic(Opc, Op0, Op1, nullptr, "elt.sat");
4404 return RValue::get(Result);
4405 }
4406
4407 case Builtin::BI__builtin_elementwise_max: {
4408 Value *Op0 = EmitScalarExpr(E->getArg(0));
4409 Value *Op1 = EmitScalarExpr(E->getArg(1));
4410 Value *Result;
4411 if (Op0->getType()->isIntOrIntVectorTy()) {
4412 QualType Ty = E->getArg(0)->getType();
4413 Result = Builder.CreateBinaryIntrinsic(
4414 Ty->hasSignedIntegerRepresentation() ? Intrinsic::smax
4415 : Intrinsic::umax,
4416 Op0, Op1, nullptr, "elt.max");
4417 } else
4418 Result = Builder.CreateMaxNum(Op0, Op1, /*FMFSource=*/nullptr, "elt.max");
4419 return RValue::get(Result);
4420 }
4421 case Builtin::BI__builtin_elementwise_min: {
4422 Value *Op0 = EmitScalarExpr(E->getArg(0));
4423 Value *Op1 = EmitScalarExpr(E->getArg(1));
4424 Value *Result;
4425 if (Op0->getType()->isIntOrIntVectorTy()) {
4426 QualType Ty = E->getArg(0)->getType();
4427 Result = Builder.CreateBinaryIntrinsic(
4428 Ty->hasSignedIntegerRepresentation() ? Intrinsic::smin
4429 : Intrinsic::umin,
4430 Op0, Op1, nullptr, "elt.min");
4431 } else
4432 Result = Builder.CreateMinNum(Op0, Op1, /*FMFSource=*/nullptr, "elt.min");
4433 return RValue::get(Result);
4434 }
4435
4436 case Builtin::BI__builtin_elementwise_maxnum: {
4437 Value *Op0 = EmitScalarExpr(E->getArg(0));
4438 Value *Op1 = EmitScalarExpr(E->getArg(1));
4439 Value *Result = Builder.CreateBinaryIntrinsic(llvm::Intrinsic::maxnum, Op0,
4440 Op1, nullptr, "elt.maxnum");
4441 return RValue::get(Result);
4442 }
4443
4444 case Builtin::BI__builtin_elementwise_minnum: {
4445 Value *Op0 = EmitScalarExpr(E->getArg(0));
4446 Value *Op1 = EmitScalarExpr(E->getArg(1));
4447 Value *Result = Builder.CreateBinaryIntrinsic(llvm::Intrinsic::minnum, Op0,
4448 Op1, nullptr, "elt.minnum");
4449 return RValue::get(Result);
4450 }
4451
4452 case Builtin::BI__builtin_elementwise_maximum: {
4453 Value *Op0 = EmitScalarExpr(E->getArg(0));
4454 Value *Op1 = EmitScalarExpr(E->getArg(1));
4455 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::maximum, Op0, Op1,
4456 nullptr, "elt.maximum");
4457 return RValue::get(Result);
4458 }
4459
4460 case Builtin::BI__builtin_elementwise_minimum: {
4461 Value *Op0 = EmitScalarExpr(E->getArg(0));
4462 Value *Op1 = EmitScalarExpr(E->getArg(1));
4463 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::minimum, Op0, Op1,
4464 nullptr, "elt.minimum");
4465 return RValue::get(Result);
4466 }
4467
4468 case Builtin::BI__builtin_elementwise_maximumnum: {
4469 Value *Op0 = EmitScalarExpr(E->getArg(0));
4470 Value *Op1 = EmitScalarExpr(E->getArg(1));
4471 Value *Result = Builder.CreateBinaryIntrinsic(
4472 Intrinsic::maximumnum, Op0, Op1, nullptr, "elt.maximumnum");
4473 return RValue::get(Result);
4474 }
4475
4476 case Builtin::BI__builtin_elementwise_minimumnum: {
4477 Value *Op0 = EmitScalarExpr(E->getArg(0));
4478 Value *Op1 = EmitScalarExpr(E->getArg(1));
4479 Value *Result = Builder.CreateBinaryIntrinsic(
4480 Intrinsic::minimumnum, Op0, Op1, nullptr, "elt.minimumnum");
4481 return RValue::get(Result);
4482 }
4483
4484 case Builtin::BI__builtin_reduce_max: {
4485 auto GetIntrinsicID = [this](QualType QT) {
4486 if (auto *VecTy = QT->getAs<VectorType>())
4487 QT = VecTy->getElementType();
4488 else if (QT->isSizelessVectorType())
4489 QT = QT->getSizelessVectorEltType(CGM.getContext());
4490
4491 if (QT->isSignedIntegerType())
4492 return Intrinsic::vector_reduce_smax;
4493 if (QT->isUnsignedIntegerType())
4494 return Intrinsic::vector_reduce_umax;
4495 assert(QT->isFloatingType() && "must have a float here");
4496 return Intrinsic::vector_reduce_fmax;
4497 };
4499 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
4500 }
4501
4502 case Builtin::BI__builtin_reduce_min: {
4503 auto GetIntrinsicID = [this](QualType QT) {
4504 if (auto *VecTy = QT->getAs<VectorType>())
4505 QT = VecTy->getElementType();
4506 else if (QT->isSizelessVectorType())
4507 QT = QT->getSizelessVectorEltType(CGM.getContext());
4508
4509 if (QT->isSignedIntegerType())
4510 return Intrinsic::vector_reduce_smin;
4511 if (QT->isUnsignedIntegerType())
4512 return Intrinsic::vector_reduce_umin;
4513 assert(QT->isFloatingType() && "must have a float here");
4514 return Intrinsic::vector_reduce_fmin;
4515 };
4516
4518 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
4519 }
4520
4521 case Builtin::BI__builtin_reduce_add:
4523 *this, E, Intrinsic::vector_reduce_add, "rdx.add"));
4524 case Builtin::BI__builtin_reduce_mul:
4526 *this, E, Intrinsic::vector_reduce_mul, "rdx.mul"));
4527 case Builtin::BI__builtin_reduce_xor:
4529 *this, E, Intrinsic::vector_reduce_xor, "rdx.xor"));
4530 case Builtin::BI__builtin_reduce_or:
4532 *this, E, Intrinsic::vector_reduce_or, "rdx.or"));
4533 case Builtin::BI__builtin_reduce_and:
4535 *this, E, Intrinsic::vector_reduce_and, "rdx.and"));
4536 case Builtin::BI__builtin_reduce_maximum:
4538 *this, E, Intrinsic::vector_reduce_fmaximum, "rdx.maximum"));
4539 case Builtin::BI__builtin_reduce_minimum:
4541 *this, E, Intrinsic::vector_reduce_fminimum, "rdx.minimum"));
4542 case Builtin::BI__builtin_reduce_assoc_fadd:
4543 case Builtin::BI__builtin_reduce_in_order_fadd: {
4544 llvm::Value *Vector = EmitScalarExpr(E->getArg(0));
4545 llvm::Type *ScalarTy = Vector->getType()->getScalarType();
4546 llvm::Value *StartValue = nullptr;
4547 if (E->getNumArgs() == 2)
4548 StartValue = Builder.CreateFPCast(EmitScalarExpr(E->getArg(1)), ScalarTy);
4549 llvm::Value *Args[] = {/*start_value=*/StartValue
4550 ? StartValue
4551 : llvm::ConstantFP::get(ScalarTy, -0.0F),
4552 /*vector=*/Vector};
4553 llvm::Function *F =
4554 CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Vector->getType());
4555 llvm::CallBase *Reduce = Builder.CreateCall(F, Args, "rdx.addf");
4556 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_reduce_assoc_fadd) {
4557 // `__builtin_reduce_assoc_fadd` is an associative reduction which
4558 // requires the reassoc FMF flag.
4559 llvm::FastMathFlags FMF;
4560 FMF.setAllowReassoc();
4561 cast<llvm::CallBase>(Reduce)->setFastMathFlags(FMF);
4562 }
4563 return RValue::get(Reduce);
4564 }
4565
4566 case Builtin::BI__builtin_matrix_transpose: {
4567 auto *MatrixTy = E->getArg(0)->getType()->castAs<ConstantMatrixType>();
4568 Value *MatValue = EmitScalarExpr(E->getArg(0));
4569 MatrixBuilder MB(Builder);
4570 Value *Result = MB.CreateMatrixTranspose(MatValue, MatrixTy->getNumRows(),
4571 MatrixTy->getNumColumns());
4572 return RValue::get(Result);
4573 }
4574
4575 case Builtin::BI__builtin_matrix_column_major_load: {
4576 MatrixBuilder MB(Builder);
4577 // Emit everything that isn't dependent on the first parameter type
4578 Value *Stride = EmitScalarExpr(E->getArg(3));
4579 const auto *ResultTy = E->getType()->getAs<ConstantMatrixType>();
4580 auto *PtrTy = E->getArg(0)->getType()->getAs<PointerType>();
4581 assert(PtrTy && "arg0 must be of pointer type");
4582 bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
4583
4586 E->getArg(0)->getType(), E->getArg(0)->getExprLoc(), FD,
4587 0);
4588 Value *Result = MB.CreateColumnMajorLoad(
4589 Src.getElementType(), Src.emitRawPointer(*this),
4590 Align(Src.getAlignment().getQuantity()), Stride, IsVolatile,
4591 ResultTy->getNumRows(), ResultTy->getNumColumns(), "matrix");
4592 return RValue::get(Result);
4593 }
4594
4595 case Builtin::BI__builtin_matrix_column_major_store: {
4596 MatrixBuilder MB(Builder);
4597 Value *Matrix = EmitScalarExpr(E->getArg(0));
4599 Value *Stride = EmitScalarExpr(E->getArg(2));
4600
4601 const auto *MatrixTy = E->getArg(0)->getType()->getAs<ConstantMatrixType>();
4602 auto *PtrTy = E->getArg(1)->getType()->getAs<PointerType>();
4603 assert(PtrTy && "arg1 must be of pointer type");
4604 bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
4605
4607 E->getArg(1)->getType(), E->getArg(1)->getExprLoc(), FD,
4608 0);
4609 Value *Result = MB.CreateColumnMajorStore(
4610 Matrix, Dst.emitRawPointer(*this),
4611 Align(Dst.getAlignment().getQuantity()), Stride, IsVolatile,
4612 MatrixTy->getNumRows(), MatrixTy->getNumColumns());
4614 return RValue::get(Result);
4615 }
4616
4617 case Builtin::BI__builtin_masked_load:
4618 case Builtin::BI__builtin_masked_expand_load: {
4619 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4620 llvm::Value *Ptr = EmitScalarExpr(E->getArg(1));
4621
4622 llvm::Type *RetTy = CGM.getTypes().ConvertType(E->getType());
4623 llvm::Value *PassThru = llvm::PoisonValue::get(RetTy);
4624 if (E->getNumArgs() > 2)
4625 PassThru = EmitScalarExpr(E->getArg(2));
4626
4627 CharUnits Align = CGM.getNaturalTypeAlignment(
4628 E->getType()->getAs<VectorType>()->getElementType(), nullptr);
4629
4630 llvm::Value *Result;
4631 if (BuiltinID == Builtin::BI__builtin_masked_load)
4632 Result = Builder.CreateMaskedLoad(RetTy, Ptr, Align.getAsAlign(), Mask,
4633 PassThru, "masked_load");
4634 else
4635 Result = Builder.CreateMaskedExpandLoad(RetTy, Ptr, MaybeAlign(), Mask,
4636 PassThru, "masked_expand_load");
4637
4638 return RValue::get(Result);
4639 };
4640 case Builtin::BI__builtin_masked_gather: {
4641 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4642 llvm::Value *Idx = EmitScalarExpr(E->getArg(1));
4643 llvm::Value *Ptr = EmitScalarExpr(E->getArg(2));
4644
4645 llvm::Type *RetTy = CGM.getTypes().ConvertType(E->getType());
4646 CharUnits Align = CGM.getNaturalTypeAlignment(
4647 E->getType()->getAs<VectorType>()->getElementType(), nullptr);
4648
4649 llvm::Value *PassThru = llvm::PoisonValue::get(RetTy);
4650 if (E->getNumArgs() > 3)
4651 PassThru = EmitScalarExpr(E->getArg(3));
4652
4653 llvm::Type *ElemTy = CGM.getTypes().ConvertType(
4655 llvm::Value *PtrVec = Builder.CreateGEP(ElemTy, Ptr, Idx);
4656
4657 llvm::Value *Result = Builder.CreateMaskedGather(
4658 RetTy, PtrVec, Align.getAsAlign(), Mask, PassThru, "masked_gather");
4659 return RValue::get(Result);
4660 }
4661 case Builtin::BI__builtin_masked_store:
4662 case Builtin::BI__builtin_masked_compress_store: {
4663 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4664 llvm::Value *Val = EmitScalarExpr(E->getArg(1));
4665 llvm::Value *Ptr = EmitScalarExpr(E->getArg(2));
4666
4667 CharUnits Align = CGM.getNaturalTypeAlignment(
4669 nullptr);
4670
4671 if (BuiltinID == Builtin::BI__builtin_masked_store)
4672 Builder.CreateMaskedStore(Val, Ptr, Align.getAsAlign(), Mask);
4673 else
4674 Builder.CreateMaskedCompressStore(Val, Ptr, MaybeAlign(), Mask);
4675
4676 return RValue::get(nullptr);
4677 }
4678 case Builtin::BI__builtin_masked_scatter: {
4679 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4680 llvm::Value *Idx = EmitScalarExpr(E->getArg(1));
4681 llvm::Value *Val = EmitScalarExpr(E->getArg(2));
4682 llvm::Value *Ptr = EmitScalarExpr(E->getArg(3));
4683
4684 CharUnits Align = CGM.getNaturalTypeAlignment(
4686 nullptr);
4687
4688 llvm::Type *ElemTy = CGM.getTypes().ConvertType(
4689 E->getArg(1)->getType()->getAs<VectorType>()->getElementType());
4690 llvm::Value *PtrVec = Builder.CreateGEP(ElemTy, Ptr, Idx);
4691
4692 Builder.CreateMaskedScatter(Val, PtrVec, Align.getAsAlign(), Mask);
4693 return RValue();
4694 }
4695 case Builtin::BI__builtin_isinf_sign: {
4696 // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
4697 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4698 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
4699 Value *Arg = EmitScalarExpr(E->getArg(0));
4700 Value *AbsArg = EmitFAbs(*this, Arg);
4701 Value *IsInf = Builder.CreateFCmpOEQ(
4702 AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
4703 Value *IsNeg = EmitSignBit(*this, Arg);
4704
4705 llvm::Type *IntTy = ConvertType(E->getType());
4706 Value *Zero = Constant::getNullValue(IntTy);
4707 Value *One = ConstantInt::get(IntTy, 1);
4708 Value *NegativeOne = ConstantInt::getAllOnesValue(IntTy);
4709 Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
4710 Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
4711 return RValue::get(Result);
4712 }
4713
4714 case Builtin::BI__builtin_flt_rounds: {
4715 Function *F = CGM.getIntrinsic(Intrinsic::get_rounding);
4716
4717 llvm::Type *ResultType = ConvertType(E->getType());
4718 Value *Result = Builder.CreateCall(F);
4719 if (Result->getType() != ResultType)
4720 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
4721 "cast");
4722 return RValue::get(Result);
4723 }
4724
4725 case Builtin::BI__builtin_set_flt_rounds: {
4726 Function *F = CGM.getIntrinsic(Intrinsic::set_rounding);
4727
4728 Value *V = EmitScalarExpr(E->getArg(0));
4729 Builder.CreateCall(F, V);
4730 return RValue::get(nullptr);
4731 }
4732
4733 case Builtin::BI__builtin_fpclassify: {
4734 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4735 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
4736 Value *V = EmitScalarExpr(E->getArg(5));
4737 llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
4738
4739 // Create Result
4740 BasicBlock *Begin = Builder.GetInsertBlock();
4741 BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
4742 Builder.SetInsertPoint(End);
4743 PHINode *Result =
4744 Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
4745 "fpclassify_result");
4746
4747 // if (V==0) return FP_ZERO
4748 Builder.SetInsertPoint(Begin);
4749 Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
4750 "iszero");
4751 Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
4752 BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
4753 Builder.CreateCondBr(IsZero, End, NotZero);
4754 Result->addIncoming(ZeroLiteral, Begin);
4755
4756 // if (V != V) return FP_NAN
4757 Builder.SetInsertPoint(NotZero);
4758 Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
4759 Value *NanLiteral = EmitScalarExpr(E->getArg(0));
4760 BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
4761 Builder.CreateCondBr(IsNan, End, NotNan);
4762 Result->addIncoming(NanLiteral, NotZero);
4763
4764 // if (fabs(V) == infinity) return FP_INFINITY
4765 Builder.SetInsertPoint(NotNan);
4766 Value *VAbs = EmitFAbs(*this, V);
4767 Value *IsInf =
4768 Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
4769 "isinf");
4770 Value *InfLiteral = EmitScalarExpr(E->getArg(1));
4771 BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
4772 Builder.CreateCondBr(IsInf, End, NotInf);
4773 Result->addIncoming(InfLiteral, NotNan);
4774
4775 // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
4776 Builder.SetInsertPoint(NotInf);
4777 APFloat Smallest = APFloat::getSmallestNormalized(
4778 getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
4779 Value *IsNormal =
4780 Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
4781 "isnormal");
4782 Value *NormalResult =
4783 Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
4784 EmitScalarExpr(E->getArg(3)));
4785 Builder.CreateBr(End);
4786 Result->addIncoming(NormalResult, NotInf);
4787
4788 // return Result
4789 Builder.SetInsertPoint(End);
4790 return RValue::get(Result);
4791 }
4792
4793 // An alloca will always return a pointer to the alloca (stack) address
4794 // space. This address space need not be the same as the AST / Language
4795 // default (e.g. in C / C++ auto vars are in the generic address space). At
4796 // the AST level this is handled within CreateTempAlloca et al., but for the
4797 // builtin / dynamic alloca we have to handle it here. We use an explicit cast
4798 // instead of passing an AS to CreateAlloca so as to not inhibit optimisation.
4799 case Builtin::BIalloca:
4800 case Builtin::BI_alloca:
4801 case Builtin::BI__builtin_alloca_uninitialized:
4802 case Builtin::BI__builtin_alloca: {
4803 Value *Size = EmitScalarExpr(E->getArg(0));
4804 const TargetInfo &TI = getContext().getTargetInfo();
4805 // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
4806 const Align SuitableAlignmentInBytes =
4807 CGM.getContext()
4808 .toCharUnitsFromBits(TI.getSuitableAlign())
4809 .getAsAlign();
4810 AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
4811 AI->setAlignment(SuitableAlignmentInBytes);
4812 if (BuiltinID != Builtin::BI__builtin_alloca_uninitialized)
4813 initializeAlloca(*this, AI, Size, SuitableAlignmentInBytes);
4814 if (AI->getAddressSpace() !=
4815 CGM.getContext().getTargetAddressSpace(
4817 llvm::Type *Ty = CGM.getTypes().ConvertType(E->getType());
4818 return RValue::get(performAddrSpaceCast(AI, Ty));
4819 }
4820 return RValue::get(AI);
4821 }
4822
4823 case Builtin::BI__builtin_alloca_with_align_uninitialized:
4824 case Builtin::BI__builtin_alloca_with_align: {
4825 Value *Size = EmitScalarExpr(E->getArg(0));
4826 Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
4827 auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
4828 unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
4829 const Align AlignmentInBytes =
4830 CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getAsAlign();
4831 AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
4832 AI->setAlignment(AlignmentInBytes);
4833 if (BuiltinID != Builtin::BI__builtin_alloca_with_align_uninitialized)
4834 initializeAlloca(*this, AI, Size, AlignmentInBytes);
4835 if (AI->getAddressSpace() !=
4836 CGM.getContext().getTargetAddressSpace(
4838 llvm::Type *Ty = CGM.getTypes().ConvertType(E->getType());
4839 return RValue::get(performAddrSpaceCast(AI, Ty));
4840 }
4841 return RValue::get(AI);
4842 }
4843
4844 case Builtin::BI__builtin_infer_alloc_token: {
4845 llvm::MDNode *MDN = buildAllocToken(E);
4846 llvm::Value *MDV = MetadataAsValue::get(getLLVMContext(), MDN);
4847 llvm::Function *F =
4848 CGM.getIntrinsic(llvm::Intrinsic::alloc_token_id, {IntPtrTy});
4849 llvm::CallBase *TokenID = Builder.CreateCall(F, MDV);
4850 return RValue::get(TokenID);
4851 }
4852
4853 case Builtin::BIbzero:
4854 case Builtin::BI__builtin_bzero: {
4856 Value *SizeVal = EmitScalarExpr(E->getArg(1));
4857 EmitNonNullArgCheck(Dest, E->getArg(0)->getType(),
4858 E->getArg(0)->getExprLoc(), FD, 0);
4859 auto *I = Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
4860 addInstToNewSourceAtom(I, nullptr);
4861 return RValue::get(nullptr);
4862 }
4863
4864 case Builtin::BIbcopy:
4865 case Builtin::BI__builtin_bcopy: {
4868 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4870 E->getArg(0)->getType(), E->getArg(0)->getExprLoc(), FD,
4871 0);
4873 E->getArg(1)->getType(), E->getArg(1)->getExprLoc(), FD,
4874 0);
4875 auto *I = Builder.CreateMemMove(Dest, Src, SizeVal, false);
4876 addInstToNewSourceAtom(I, nullptr);
4877 return RValue::get(nullptr);
4878 }
4879
4880 case Builtin::BImemcpy:
4881 case Builtin::BI__builtin_memcpy:
4882 case Builtin::BImempcpy:
4883 case Builtin::BI__builtin_mempcpy: {
4886 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4887 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
4888 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
4889 auto *I = Builder.CreateMemCpy(Dest, Src, SizeVal, false);
4890 addInstToNewSourceAtom(I, nullptr);
4891 if (BuiltinID == Builtin::BImempcpy ||
4892 BuiltinID == Builtin::BI__builtin_mempcpy)
4893 return RValue::get(Builder.CreateInBoundsGEP(
4894 Dest.getElementType(), Dest.emitRawPointer(*this), SizeVal));
4895 else
4896 return RValue::get(Dest, *this);
4897 }
4898
4899 case Builtin::BI__builtin_memcpy_inline: {
4902 uint64_t Size =
4903 E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
4904 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
4905 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
4906 auto *I = Builder.CreateMemCpyInline(Dest, Src, Size);
4907 addInstToNewSourceAtom(I, nullptr);
4908 return RValue::get(nullptr);
4909 }
4910
4911 case Builtin::BI__builtin_char_memchr:
4912 BuiltinID = Builtin::BI__builtin_memchr;
4913 break;
4914
4915 case Builtin::BI__builtin___memcpy_chk: {
4916 // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
4917 Expr::EvalResult SizeResult, DstSizeResult;
4918 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
4919 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
4920 break;
4921 llvm::APSInt Size = SizeResult.Val.getInt();
4922 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
4923 if (Size.ugt(DstSize))
4924 break;
4927 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
4928 auto *I = Builder.CreateMemCpy(Dest, Src, SizeVal, false);
4929 addInstToNewSourceAtom(I, nullptr);
4930 return RValue::get(Dest, *this);
4931 }
4932
4933 case Builtin::BI__builtin_objc_memmove_collectable: {
4934 Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
4935 Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
4936 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4937 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
4938 DestAddr, SrcAddr, SizeVal);
4939 return RValue::get(DestAddr, *this);
4940 }
4941
4942 case Builtin::BI__builtin___memmove_chk: {
4943 // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
4944 Expr::EvalResult SizeResult, DstSizeResult;
4945 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
4946 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
4947 break;
4948 llvm::APSInt Size = SizeResult.Val.getInt();
4949 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
4950 if (Size.ugt(DstSize))
4951 break;
4954 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
4955 auto *I = Builder.CreateMemMove(Dest, Src, SizeVal, false);
4956 addInstToNewSourceAtom(I, nullptr);
4957 return RValue::get(Dest, *this);
4958 }
4959
4960 case Builtin::BI__builtin_trivially_relocate:
4961 case Builtin::BImemmove:
4962 case Builtin::BI__builtin_memmove: {
4965 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4966 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_trivially_relocate)
4967 SizeVal = Builder.CreateMul(
4968 SizeVal,
4969 ConstantInt::get(
4970 SizeVal->getType(),
4971 getContext()
4972 .getTypeSizeInChars(E->getArg(0)->getType()->getPointeeType())
4973 .getQuantity()));
4974 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
4975 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
4976 auto *I = Builder.CreateMemMove(Dest, Src, SizeVal, false);
4977 addInstToNewSourceAtom(I, nullptr);
4978 return RValue::get(Dest, *this);
4979 }
4980 case Builtin::BImemset:
4981 case Builtin::BI__builtin_memset: {
4983 Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
4984 Builder.getInt8Ty());
4985 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4986 EmitNonNullArgCheck(Dest, E->getArg(0)->getType(),
4987 E->getArg(0)->getExprLoc(), FD, 0);
4988 auto *I = Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
4989 addInstToNewSourceAtom(I, ByteVal);
4990 return RValue::get(Dest, *this);
4991 }
4992 case Builtin::BI__builtin_memset_inline: {
4994 Value *ByteVal =
4995 Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)), Builder.getInt8Ty());
4996 uint64_t Size =
4997 E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
4999 E->getArg(0)->getType(), E->getArg(0)->getExprLoc(), FD,
5000 0);
5001 auto *I = Builder.CreateMemSetInline(Dest, ByteVal, Size);
5002 addInstToNewSourceAtom(I, nullptr);
5003 return RValue::get(nullptr);
5004 }
5005 case Builtin::BI__builtin___memset_chk: {
5006 // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
5007 Expr::EvalResult SizeResult, DstSizeResult;
5008 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
5009 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
5010 break;
5011 llvm::APSInt Size = SizeResult.Val.getInt();
5012 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
5013 if (Size.ugt(DstSize))
5014 break;
5016 Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
5017 Builder.getInt8Ty());
5018 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
5019 auto *I = Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
5020 addInstToNewSourceAtom(I, nullptr);
5021 return RValue::get(Dest, *this);
5022 }
5023 case Builtin::BI__builtin_wmemchr: {
5024 // The MSVC runtime library does not provide a definition of wmemchr, so we
5025 // need an inline implementation.
5026 if (!getTarget().getTriple().isOSMSVCRT())
5027 break;
5028
5029 llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
5030 Value *Str = EmitScalarExpr(E->getArg(0));
5031 Value *Chr = EmitScalarExpr(E->getArg(1));
5032 Value *Size = EmitScalarExpr(E->getArg(2));
5033
5034 BasicBlock *Entry = Builder.GetInsertBlock();
5035 BasicBlock *CmpEq = createBasicBlock("wmemchr.eq");
5036 BasicBlock *Next = createBasicBlock("wmemchr.next");
5037 BasicBlock *Exit = createBasicBlock("wmemchr.exit");
5038 Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
5039 Builder.CreateCondBr(SizeEq0, Exit, CmpEq);
5040
5041 EmitBlock(CmpEq);
5042 PHINode *StrPhi = Builder.CreatePHI(Str->getType(), 2);
5043 StrPhi->addIncoming(Str, Entry);
5044 PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
5045 SizePhi->addIncoming(Size, Entry);
5046 CharUnits WCharAlign =
5048 Value *StrCh = Builder.CreateAlignedLoad(WCharTy, StrPhi, WCharAlign);
5049 Value *FoundChr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 0);
5050 Value *StrEqChr = Builder.CreateICmpEQ(StrCh, Chr);
5051 Builder.CreateCondBr(StrEqChr, Exit, Next);
5052
5053 EmitBlock(Next);
5054 Value *NextStr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 1);
5055 Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
5056 Value *NextSizeEq0 =
5057 Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
5058 Builder.CreateCondBr(NextSizeEq0, Exit, CmpEq);
5059 StrPhi->addIncoming(NextStr, Next);
5060 SizePhi->addIncoming(NextSize, Next);
5061
5062 EmitBlock(Exit);
5063 PHINode *Ret = Builder.CreatePHI(Str->getType(), 3);
5064 Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Entry);
5065 Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Next);
5066 Ret->addIncoming(FoundChr, CmpEq);
5067 return RValue::get(Ret);
5068 }
5069 case Builtin::BI__builtin_wmemcmp: {
5070 // The MSVC runtime library does not provide a definition of wmemcmp, so we
5071 // need an inline implementation.
5072 if (!getTarget().getTriple().isOSMSVCRT())
5073 break;
5074
5075 llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
5076
5077 Value *Dst = EmitScalarExpr(E->getArg(0));
5078 Value *Src = EmitScalarExpr(E->getArg(1));
5079 Value *Size = EmitScalarExpr(E->getArg(2));
5080
5081 BasicBlock *Entry = Builder.GetInsertBlock();
5082 BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
5083 BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
5084 BasicBlock *Next = createBasicBlock("wmemcmp.next");
5085 BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
5086 Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
5087 Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
5088
5089 EmitBlock(CmpGT);
5090 PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
5091 DstPhi->addIncoming(Dst, Entry);
5092 PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
5093 SrcPhi->addIncoming(Src, Entry);
5094 PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
5095 SizePhi->addIncoming(Size, Entry);
5096 CharUnits WCharAlign =
5098 Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
5099 Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
5100 Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
5101 Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
5102
5103 EmitBlock(CmpLT);
5104 Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
5105 Builder.CreateCondBr(DstLtSrc, Exit, Next);
5106
5107 EmitBlock(Next);
5108 Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
5109 Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
5110 Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
5111 Value *NextSizeEq0 =
5112 Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
5113 Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
5114 DstPhi->addIncoming(NextDst, Next);
5115 SrcPhi->addIncoming(NextSrc, Next);
5116 SizePhi->addIncoming(NextSize, Next);
5117
5118 EmitBlock(Exit);
5119 PHINode *Ret = Builder.CreatePHI(IntTy, 4);
5120 Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
5121 Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
5122 Ret->addIncoming(ConstantInt::getAllOnesValue(IntTy), CmpLT);
5123 Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
5124 return RValue::get(Ret);
5125 }
5126 case Builtin::BI__builtin_dwarf_cfa: {
5127 // The offset in bytes from the first argument to the CFA.
5128 //
5129 // Why on earth is this in the frontend? Is there any reason at
5130 // all that the backend can't reasonably determine this while
5131 // lowering llvm.eh.dwarf.cfa()?
5132 //
5133 // TODO: If there's a satisfactory reason, add a target hook for
5134 // this instead of hard-coding 0, which is correct for most targets.
5135 int32_t Offset = 0;
5136
5137 Function *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
5138 return RValue::get(Builder.CreateCall(F,
5139 llvm::ConstantInt::get(Int32Ty, Offset)));
5140 }
5141 case Builtin::BI__builtin_return_address: {
5142 Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
5143 getContext().UnsignedIntTy);
5144 Function *F =
5145 CGM.getIntrinsic(Intrinsic::returnaddress, {CGM.ProgramPtrTy});
5146 return RValue::get(Builder.CreateCall(F, Depth));
5147 }
5148 case Builtin::BI_ReturnAddress: {
5149 Function *F =
5150 CGM.getIntrinsic(Intrinsic::returnaddress, {CGM.ProgramPtrTy});
5151 return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
5152 }
5153 case Builtin::BI__builtin_frame_address: {
5154 Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
5155 getContext().UnsignedIntTy);
5156 Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
5157 return RValue::get(Builder.CreateCall(F, Depth));
5158 }
5159 case Builtin::BI__builtin_stack_address: {
5160 return RValue::get(Builder.CreateCall(
5161 CGM.getIntrinsic(Intrinsic::stackaddress, AllocaInt8PtrTy)));
5162 }
5163 case Builtin::BI__builtin_extract_return_addr: {
5166 return RValue::get(Result);
5167 }
5168 case Builtin::BI__builtin_frob_return_addr: {
5171 return RValue::get(Result);
5172 }
5173 case Builtin::BI__builtin_dwarf_sp_column: {
5174 llvm::IntegerType *Ty
5177 if (Column == -1) {
5178 CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
5179 return RValue::get(llvm::UndefValue::get(Ty));
5180 }
5181 return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
5182 }
5183 case Builtin::BI__builtin_init_dwarf_reg_size_table: {
5185 if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
5186 CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
5187 return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
5188 }
5189 case Builtin::BI__builtin_eh_return: {
5190 Value *Int = EmitScalarExpr(E->getArg(0));
5191 Value *Ptr = EmitScalarExpr(E->getArg(1));
5192
5193 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
5194 assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&
5195 "LLVM's __builtin_eh_return only supports 32- and 64-bit variants");
5196 Function *F =
5197 CGM.getIntrinsic(IntTy->getBitWidth() == 32 ? Intrinsic::eh_return_i32
5198 : Intrinsic::eh_return_i64);
5199 Builder.CreateCall(F, {Int, Ptr});
5200 Builder.CreateUnreachable();
5201
5202 // We do need to preserve an insertion point.
5203 EmitBlock(createBasicBlock("builtin_eh_return.cont"));
5204
5205 return RValue::get(nullptr);
5206 }
5207 case Builtin::BI__builtin_unwind_init: {
5208 Function *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
5209 Builder.CreateCall(F);
5210 return RValue::get(nullptr);
5211 }
5212 case Builtin::BI__builtin_extend_pointer: {
5213 // Extends a pointer to the size of an _Unwind_Word, which is
5214 // uint64_t on all platforms. Generally this gets poked into a
5215 // register and eventually used as an address, so if the
5216 // addressing registers are wider than pointers and the platform
5217 // doesn't implicitly ignore high-order bits when doing
5218 // addressing, we need to make sure we zext / sext based on
5219 // the platform's expectations.
5220 //
5221 // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
5222
5223 // Cast the pointer to intptr_t.
5224 Value *Ptr = EmitScalarExpr(E->getArg(0));
5225 Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
5226
5227 // If that's 64 bits, we're done.
5228 if (IntPtrTy->getBitWidth() == 64)
5229 return RValue::get(Result);
5230
5231 // Otherwise, ask the codegen data what to do.
5232 if (getTargetHooks().extendPointerWithSExt())
5233 return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
5234 else
5235 return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
5236 }
5237 case Builtin::BI__builtin_setjmp: {
5238 // Buffer is a void**.
5240
5241 if (getTarget().getTriple().getArch() == llvm::Triple::systemz) {
5242 // On this target, the back end fills in the context buffer completely.
5243 // It doesn't really matter if the frontend stores to the buffer before
5244 // calling setjmp, the back-end is going to overwrite them anyway.
5245 Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
5246 return RValue::get(Builder.CreateCall(F, Buf.emitRawPointer(*this)));
5247 }
5248
5249 // Store the frame pointer to the setjmp buffer.
5250 Value *FrameAddr = Builder.CreateCall(
5251 CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy),
5252 ConstantInt::get(Int32Ty, 0));
5253 Builder.CreateStore(FrameAddr, Buf);
5254
5255 // Store the stack pointer to the setjmp buffer.
5256 Value *StackAddr = Builder.CreateStackSave();
5257 assert(Buf.emitRawPointer(*this)->getType() == StackAddr->getType());
5258
5259 Address StackSaveSlot = Builder.CreateConstInBoundsGEP(Buf, 2);
5260 Builder.CreateStore(StackAddr, StackSaveSlot);
5261
5262 // Call LLVM's EH setjmp, which is lightweight.
5263 Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
5264 return RValue::get(Builder.CreateCall(F, Buf.emitRawPointer(*this)));
5265 }
5266 case Builtin::BI__builtin_longjmp: {
5267 Value *Buf = EmitScalarExpr(E->getArg(0));
5268
5269 // Call LLVM's EH longjmp, which is lightweight.
5270 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
5271
5272 // longjmp doesn't return; mark this as unreachable.
5273 Builder.CreateUnreachable();
5274
5275 // We do need to preserve an insertion point.
5276 EmitBlock(createBasicBlock("longjmp.cont"));
5277
5278 return RValue::get(nullptr);
5279 }
5280 case Builtin::BI__builtin_launder: {
5281 const Expr *Arg = E->getArg(0);
5282 QualType ArgTy = Arg->getType()->getPointeeType();
5283 Value *Ptr = EmitScalarExpr(Arg);
5284 if (TypeRequiresBuiltinLaunder(CGM, ArgTy))
5285 Ptr = Builder.CreateLaunderInvariantGroup(Ptr);
5286
5287 return RValue::get(Ptr);
5288 }
5289 case Builtin::BI__builtin_clear_padding: {
5291 auto PointeeTy = E->getArg(0)->getType()->getPointeeType();
5292
5294 getContext().getPaddingIntervals(PointeeTy);
5295 for (const auto &Interval : Padding)
5296 ClearPadding(*this, Src, Interval);
5297
5298 return RValue::get(nullptr);
5299 }
5300 case Builtin::BI__sync_fetch_and_add:
5301 case Builtin::BI__sync_fetch_and_sub:
5302 case Builtin::BI__sync_fetch_and_or:
5303 case Builtin::BI__sync_fetch_and_and:
5304 case Builtin::BI__sync_fetch_and_xor:
5305 case Builtin::BI__sync_fetch_and_nand:
5306 case Builtin::BI__sync_add_and_fetch:
5307 case Builtin::BI__sync_sub_and_fetch:
5308 case Builtin::BI__sync_and_and_fetch:
5309 case Builtin::BI__sync_or_and_fetch:
5310 case Builtin::BI__sync_xor_and_fetch:
5311 case Builtin::BI__sync_nand_and_fetch:
5312 case Builtin::BI__sync_val_compare_and_swap:
5313 case Builtin::BI__sync_bool_compare_and_swap:
5314 case Builtin::BI__sync_lock_test_and_set:
5315 case Builtin::BI__sync_lock_release:
5316 case Builtin::BI__sync_swap:
5317 llvm_unreachable("Shouldn't make it through sema");
5318 case Builtin::BI__sync_fetch_and_add_1:
5319 case Builtin::BI__sync_fetch_and_add_2:
5320 case Builtin::BI__sync_fetch_and_add_4:
5321 case Builtin::BI__sync_fetch_and_add_8:
5322 case Builtin::BI__sync_fetch_and_add_16:
5323 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
5324 case Builtin::BI__sync_fetch_and_sub_1:
5325 case Builtin::BI__sync_fetch_and_sub_2:
5326 case Builtin::BI__sync_fetch_and_sub_4:
5327 case Builtin::BI__sync_fetch_and_sub_8:
5328 case Builtin::BI__sync_fetch_and_sub_16:
5329 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
5330 case Builtin::BI__sync_fetch_and_or_1:
5331 case Builtin::BI__sync_fetch_and_or_2:
5332 case Builtin::BI__sync_fetch_and_or_4:
5333 case Builtin::BI__sync_fetch_and_or_8:
5334 case Builtin::BI__sync_fetch_and_or_16:
5335 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
5336 case Builtin::BI__sync_fetch_and_and_1:
5337 case Builtin::BI__sync_fetch_and_and_2:
5338 case Builtin::BI__sync_fetch_and_and_4:
5339 case Builtin::BI__sync_fetch_and_and_8:
5340 case Builtin::BI__sync_fetch_and_and_16:
5341 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
5342 case Builtin::BI__sync_fetch_and_xor_1:
5343 case Builtin::BI__sync_fetch_and_xor_2:
5344 case Builtin::BI__sync_fetch_and_xor_4:
5345 case Builtin::BI__sync_fetch_and_xor_8:
5346 case Builtin::BI__sync_fetch_and_xor_16:
5347 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
5348 case Builtin::BI__sync_fetch_and_nand_1:
5349 case Builtin::BI__sync_fetch_and_nand_2:
5350 case Builtin::BI__sync_fetch_and_nand_4:
5351 case Builtin::BI__sync_fetch_and_nand_8:
5352 case Builtin::BI__sync_fetch_and_nand_16:
5353 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
5354
5355 // Clang extensions: not overloaded yet.
5356 case Builtin::BI__sync_fetch_and_min:
5357 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
5358 case Builtin::BI__sync_fetch_and_max:
5359 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
5360 case Builtin::BI__sync_fetch_and_umin:
5361 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
5362 case Builtin::BI__sync_fetch_and_umax:
5363 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
5364
5365 case Builtin::BI__sync_add_and_fetch_1:
5366 case Builtin::BI__sync_add_and_fetch_2:
5367 case Builtin::BI__sync_add_and_fetch_4:
5368 case Builtin::BI__sync_add_and_fetch_8:
5369 case Builtin::BI__sync_add_and_fetch_16:
5370 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Add, E,
5371 llvm::Instruction::Add);
5372 case Builtin::BI__sync_sub_and_fetch_1:
5373 case Builtin::BI__sync_sub_and_fetch_2:
5374 case Builtin::BI__sync_sub_and_fetch_4:
5375 case Builtin::BI__sync_sub_and_fetch_8:
5376 case Builtin::BI__sync_sub_and_fetch_16:
5377 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Sub, E,
5378 llvm::Instruction::Sub);
5379 case Builtin::BI__sync_and_and_fetch_1:
5380 case Builtin::BI__sync_and_and_fetch_2:
5381 case Builtin::BI__sync_and_and_fetch_4:
5382 case Builtin::BI__sync_and_and_fetch_8:
5383 case Builtin::BI__sync_and_and_fetch_16:
5384 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::And, E,
5385 llvm::Instruction::And);
5386 case Builtin::BI__sync_or_and_fetch_1:
5387 case Builtin::BI__sync_or_and_fetch_2:
5388 case Builtin::BI__sync_or_and_fetch_4:
5389 case Builtin::BI__sync_or_and_fetch_8:
5390 case Builtin::BI__sync_or_and_fetch_16:
5391 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
5392 llvm::Instruction::Or);
5393 case Builtin::BI__sync_xor_and_fetch_1:
5394 case Builtin::BI__sync_xor_and_fetch_2:
5395 case Builtin::BI__sync_xor_and_fetch_4:
5396 case Builtin::BI__sync_xor_and_fetch_8:
5397 case Builtin::BI__sync_xor_and_fetch_16:
5398 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
5399 llvm::Instruction::Xor);
5400 case Builtin::BI__sync_nand_and_fetch_1:
5401 case Builtin::BI__sync_nand_and_fetch_2:
5402 case Builtin::BI__sync_nand_and_fetch_4:
5403 case Builtin::BI__sync_nand_and_fetch_8:
5404 case Builtin::BI__sync_nand_and_fetch_16:
5405 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
5406 llvm::Instruction::And, true);
5407
5408 case Builtin::BI__sync_val_compare_and_swap_1:
5409 case Builtin::BI__sync_val_compare_and_swap_2:
5410 case Builtin::BI__sync_val_compare_and_swap_4:
5411 case Builtin::BI__sync_val_compare_and_swap_8:
5412 case Builtin::BI__sync_val_compare_and_swap_16:
5414 *this, E, false, AtomicOrdering::SequentiallyConsistent,
5415 AtomicOrdering::SequentiallyConsistent));
5416
5417 case Builtin::BI__sync_bool_compare_and_swap_1:
5418 case Builtin::BI__sync_bool_compare_and_swap_2:
5419 case Builtin::BI__sync_bool_compare_and_swap_4:
5420 case Builtin::BI__sync_bool_compare_and_swap_8:
5421 case Builtin::BI__sync_bool_compare_and_swap_16:
5423 *this, E, true, AtomicOrdering::SequentiallyConsistent,
5424 AtomicOrdering::SequentiallyConsistent));
5425
5426 case Builtin::BI__sync_swap_1:
5427 case Builtin::BI__sync_swap_2:
5428 case Builtin::BI__sync_swap_4:
5429 case Builtin::BI__sync_swap_8:
5430 case Builtin::BI__sync_swap_16:
5431 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
5432
5433 case Builtin::BI__sync_lock_test_and_set_1:
5434 case Builtin::BI__sync_lock_test_and_set_2:
5435 case Builtin::BI__sync_lock_test_and_set_4:
5436 case Builtin::BI__sync_lock_test_and_set_8:
5437 case Builtin::BI__sync_lock_test_and_set_16:
5438 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
5439
5440 case Builtin::BI__sync_lock_release_1:
5441 case Builtin::BI__sync_lock_release_2:
5442 case Builtin::BI__sync_lock_release_4:
5443 case Builtin::BI__sync_lock_release_8:
5444 case Builtin::BI__sync_lock_release_16: {
5445 Address Ptr = CheckAtomicAlignment(*this, E);
5446 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
5447
5448 llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
5449 getContext().getTypeSize(ElTy));
5450 llvm::StoreInst *Store =
5451 Builder.CreateStore(llvm::Constant::getNullValue(ITy), Ptr);
5452 Store->setAtomic(llvm::AtomicOrdering::Release);
5453 return RValue::get(nullptr);
5454 }
5455
5456 case Builtin::BI__sync_synchronize: {
5457 // We assume this is supposed to correspond to a C++0x-style
5458 // sequentially-consistent fence (i.e. this is only usable for
5459 // synchronization, not device I/O or anything like that). This intrinsic
5460 // is really badly designed in the sense that in theory, there isn't
5461 // any way to safely use it... but in practice, it mostly works
5462 // to use it with non-atomic loads and stores to get acquire/release
5463 // semantics.
5464 Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
5465 return RValue::get(nullptr);
5466 }
5467
5468 case Builtin::BI__builtin_nontemporal_load:
5469 return RValue::get(EmitNontemporalLoad(*this, E));
5470 case Builtin::BI__builtin_nontemporal_store:
5471 return RValue::get(EmitNontemporalStore(*this, E));
5472 case Builtin::BI__c11_atomic_is_lock_free:
5473 case Builtin::BI__atomic_is_lock_free: {
5474 // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
5475 // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
5476 // _Atomic(T) is always properly-aligned.
5477 const char *LibCallName = "__atomic_is_lock_free";
5478 CallArgList Args;
5479 Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
5480 getContext().getSizeType());
5481 if (BuiltinID == Builtin::BI__atomic_is_lock_free)
5482 Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
5484 else
5485 Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
5487 const CGFunctionInfo &FuncInfo =
5488 CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
5489 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
5490 llvm::FunctionCallee Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
5491 return EmitCall(FuncInfo, CGCallee::forDirect(Func),
5492 ReturnValueSlot(), Args);
5493 }
5494
5495 case Builtin::BI__atomic_thread_fence:
5496 case Builtin::BI__atomic_signal_fence:
5497 case Builtin::BI__c11_atomic_thread_fence:
5498 case Builtin::BI__c11_atomic_signal_fence: {
5499 llvm::SyncScope::ID SSID;
5500 if (BuiltinID == Builtin::BI__atomic_signal_fence ||
5501 BuiltinID == Builtin::BI__c11_atomic_signal_fence)
5502 SSID = llvm::SyncScope::SingleThread;
5503 else
5504 SSID = llvm::SyncScope::System;
5505 Value *Order = EmitScalarExpr(E->getArg(0));
5506 if (isa<llvm::ConstantInt>(Order)) {
5507 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
5508 switch (ord) {
5509 case 0: // memory_order_relaxed
5510 default: // invalid order
5511 break;
5512 case 1: // memory_order_consume
5513 case 2: // memory_order_acquire
5514 emitAtomicFence(llvm::AtomicOrdering::Acquire, SSID);
5515 break;
5516 case 3: // memory_order_release
5517 emitAtomicFence(llvm::AtomicOrdering::Release, SSID);
5518 break;
5519 case 4: // memory_order_acq_rel
5520 emitAtomicFence(llvm::AtomicOrdering::AcquireRelease, SSID);
5521 break;
5522 case 5: // memory_order_seq_cst
5523 emitAtomicFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
5524 break;
5525 }
5526 return RValue::get(nullptr);
5527 }
5528
5529 llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
5530 AcquireBB = createBasicBlock("acquire", CurFn);
5531 ReleaseBB = createBasicBlock("release", CurFn);
5532 AcqRelBB = createBasicBlock("acqrel", CurFn);
5533 SeqCstBB = createBasicBlock("seqcst", CurFn);
5534 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
5535
5536 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
5537 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
5538
5539 Builder.SetInsertPoint(AcquireBB);
5540 emitAtomicFence(llvm::AtomicOrdering::Acquire, SSID);
5541 Builder.CreateBr(ContBB);
5542 SI->addCase(Builder.getInt32(1), AcquireBB);
5543 SI->addCase(Builder.getInt32(2), AcquireBB);
5544
5545 Builder.SetInsertPoint(ReleaseBB);
5546 emitAtomicFence(llvm::AtomicOrdering::Release, SSID);
5547 Builder.CreateBr(ContBB);
5548 SI->addCase(Builder.getInt32(3), ReleaseBB);
5549
5550 Builder.SetInsertPoint(AcqRelBB);
5551 emitAtomicFence(llvm::AtomicOrdering::AcquireRelease, SSID);
5552 Builder.CreateBr(ContBB);
5553 SI->addCase(Builder.getInt32(4), AcqRelBB);
5554
5555 Builder.SetInsertPoint(SeqCstBB);
5556 emitAtomicFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
5557 Builder.CreateBr(ContBB);
5558 SI->addCase(Builder.getInt32(5), SeqCstBB);
5559
5560 Builder.SetInsertPoint(ContBB);
5561 return RValue::get(nullptr);
5562 }
5563 case Builtin::BI__scoped_atomic_thread_fence: {
5565
5566 Value *Order = EmitScalarExpr(E->getArg(0));
5567 Value *Scope = EmitScalarExpr(E->getArg(1));
5568 auto Ord = dyn_cast<llvm::ConstantInt>(Order);
5569 auto Scp = dyn_cast<llvm::ConstantInt>(Scope);
5570 if (Ord && Scp) {
5571 SyncScope SS = ScopeModel->isValid(Scp->getZExtValue())
5572 ? ScopeModel->map(Scp->getZExtValue())
5573 : ScopeModel->map(ScopeModel->getFallBackValue());
5574 switch (Ord->getZExtValue()) {
5575 case 0: // memory_order_relaxed
5576 default: // invalid order
5577 break;
5578 case 1: // memory_order_consume
5579 case 2: // memory_order_acquire
5580 emitAtomicFence(llvm::AtomicOrdering::Acquire,
5581 getTargetHooks().getLLVMSyncScopeID(
5582 getLangOpts(), SS, llvm::AtomicOrdering::Acquire,
5583 getLLVMContext()));
5584 break;
5585 case 3: // memory_order_release
5586 emitAtomicFence(llvm::AtomicOrdering::Release,
5587 getTargetHooks().getLLVMSyncScopeID(
5588 getLangOpts(), SS, llvm::AtomicOrdering::Release,
5589 getLLVMContext()));
5590 break;
5591 case 4: // memory_order_acq_rel
5592 emitAtomicFence(llvm::AtomicOrdering::AcquireRelease,
5593 getTargetHooks().getLLVMSyncScopeID(
5594 getLangOpts(), SS,
5595 llvm::AtomicOrdering::AcquireRelease,
5596 getLLVMContext()));
5597 break;
5598 case 5: // memory_order_seq_cst
5599 emitAtomicFence(llvm::AtomicOrdering::SequentiallyConsistent,
5600 getTargetHooks().getLLVMSyncScopeID(
5601 getLangOpts(), SS,
5602 llvm::AtomicOrdering::SequentiallyConsistent,
5603 getLLVMContext()));
5604 break;
5605 }
5606 return RValue::get(nullptr);
5607 }
5608
5609 llvm::BasicBlock *ContBB = createBasicBlock("atomic.scope.continue", CurFn);
5610
5612 OrderBBs;
5613 if (Ord) {
5614 switch (Ord->getZExtValue()) {
5615 case 0: // memory_order_relaxed
5616 default: // invalid order
5617 ContBB->eraseFromParent();
5618 return RValue::get(nullptr);
5619 case 1: // memory_order_consume
5620 case 2: // memory_order_acquire
5621 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5622 llvm::AtomicOrdering::Acquire);
5623 break;
5624 case 3: // memory_order_release
5625 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5626 llvm::AtomicOrdering::Release);
5627 break;
5628 case 4: // memory_order_acq_rel
5629 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5630 llvm::AtomicOrdering::AcquireRelease);
5631 break;
5632 case 5: // memory_order_seq_cst
5633 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5634 llvm::AtomicOrdering::SequentiallyConsistent);
5635 break;
5636 }
5637 } else {
5638 llvm::BasicBlock *AcquireBB = createBasicBlock("acquire", CurFn);
5639 llvm::BasicBlock *ReleaseBB = createBasicBlock("release", CurFn);
5640 llvm::BasicBlock *AcqRelBB = createBasicBlock("acqrel", CurFn);
5641 llvm::BasicBlock *SeqCstBB = createBasicBlock("seqcst", CurFn);
5642
5643 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
5644 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
5645 SI->addCase(Builder.getInt32(1), AcquireBB);
5646 SI->addCase(Builder.getInt32(2), AcquireBB);
5647 SI->addCase(Builder.getInt32(3), ReleaseBB);
5648 SI->addCase(Builder.getInt32(4), AcqRelBB);
5649 SI->addCase(Builder.getInt32(5), SeqCstBB);
5650
5651 OrderBBs.emplace_back(AcquireBB, llvm::AtomicOrdering::Acquire);
5652 OrderBBs.emplace_back(ReleaseBB, llvm::AtomicOrdering::Release);
5653 OrderBBs.emplace_back(AcqRelBB, llvm::AtomicOrdering::AcquireRelease);
5654 OrderBBs.emplace_back(SeqCstBB,
5655 llvm::AtomicOrdering::SequentiallyConsistent);
5656 }
5657
5658 for (auto &[OrderBB, Ordering] : OrderBBs) {
5659 Builder.SetInsertPoint(OrderBB);
5660 if (Scp) {
5661 SyncScope SS = ScopeModel->isValid(Scp->getZExtValue())
5662 ? ScopeModel->map(Scp->getZExtValue())
5663 : ScopeModel->map(ScopeModel->getFallBackValue());
5664 emitAtomicFence(Ordering,
5665 getTargetHooks().getLLVMSyncScopeID(
5666 getLangOpts(), SS, Ordering, getLLVMContext()));
5667 Builder.CreateBr(ContBB);
5668 } else {
5669 llvm::DenseMap<unsigned, llvm::BasicBlock *> BBs;
5670 for (unsigned Scp : ScopeModel->getRuntimeValues())
5671 BBs[Scp] = createBasicBlock(getAsString(ScopeModel->map(Scp)), CurFn);
5672
5673 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
5674 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, ContBB);
5675 for (unsigned Scp : ScopeModel->getRuntimeValues()) {
5676 auto *B = BBs[Scp];
5677 SI->addCase(Builder.getInt32(Scp), B);
5678
5679 Builder.SetInsertPoint(B);
5680 emitAtomicFence(Ordering, getTargetHooks().getLLVMSyncScopeID(
5681 getLangOpts(), ScopeModel->map(Scp),
5682 Ordering, getLLVMContext()));
5683 Builder.CreateBr(ContBB);
5684 }
5685 }
5686 }
5687
5688 Builder.SetInsertPoint(ContBB);
5689 return RValue::get(nullptr);
5690 }
5691
5692 case Builtin::BI__builtin_signbit:
5693 case Builtin::BI__builtin_signbitf:
5694 case Builtin::BI__builtin_signbitl: {
5695 return RValue::get(
5696 Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
5697 ConvertType(E->getType())));
5698 }
5699 case Builtin::BI__warn_memset_zero_len:
5700 return RValue::getIgnored();
5701 case Builtin::BI__annotation: {
5702 // Re-encode each wide string to UTF8 and make an MDString.
5704 for (const Expr *Arg : E->arguments()) {
5705 const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
5706 assert(Str->getCharByteWidth() == 2 || Str->getCharByteWidth() == 4);
5707 StringRef WideBytes = Str->getBytes();
5708 std::string StrUtf8;
5709 bool Converted =
5710 (Str->getCharByteWidth() == 2)
5711 ? convertUTF16ToUTF8String(
5712 ArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)
5713 : convertUTF32ToUTF8String(
5714 ArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8);
5715 if (!Converted) {
5716 CGM.ErrorUnsupported(E, "non-Unicode __annotation argument");
5717 continue;
5718 }
5719 Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
5720 }
5721
5722 // Build and MDTuple of MDStrings and emit the intrinsic call.
5723 llvm::Function *F = CGM.getIntrinsic(Intrinsic::codeview_annotation, {});
5724 MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
5725 Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
5726 return RValue::getIgnored();
5727 }
5728 case Builtin::BI__builtin_annotation: {
5729 llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
5730 llvm::Function *F = CGM.getIntrinsic(
5731 Intrinsic::annotation, {AnnVal->getType(), CGM.ConstGlobalsPtrTy});
5732
5733 // Get the annotation string, go through casts. Sema requires this to be a
5734 // non-wide string literal, potentially casted, so the cast<> is safe.
5735 const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
5736 StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
5737 return RValue::get(
5738 EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc(), nullptr));
5739 }
5740 case Builtin::BI__builtin_addcb:
5741 case Builtin::BI__builtin_addcs:
5742 case Builtin::BI__builtin_addc:
5743 case Builtin::BI__builtin_addcl:
5744 case Builtin::BI__builtin_addcll:
5745 case Builtin::BI__builtin_subcb:
5746 case Builtin::BI__builtin_subcs:
5747 case Builtin::BI__builtin_subc:
5748 case Builtin::BI__builtin_subcl:
5749 case Builtin::BI__builtin_subcll: {
5750
5751 // We translate all of these builtins from expressions of the form:
5752 // int x = ..., y = ..., carryin = ..., carryout, result;
5753 // result = __builtin_addc(x, y, carryin, &carryout);
5754 //
5755 // to LLVM IR of the form:
5756 //
5757 // %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
5758 // %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
5759 // %carry1 = extractvalue {i32, i1} %tmp1, 1
5760 // %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
5761 // i32 %carryin)
5762 // %result = extractvalue {i32, i1} %tmp2, 0
5763 // %carry2 = extractvalue {i32, i1} %tmp2, 1
5764 // %tmp3 = or i1 %carry1, %carry2
5765 // %tmp4 = zext i1 %tmp3 to i32
5766 // store i32 %tmp4, i32* %carryout
5767
5768 // Scalarize our inputs.
5769 llvm::Value *X = EmitScalarExpr(E->getArg(0));
5770 llvm::Value *Y = EmitScalarExpr(E->getArg(1));
5771 llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
5772 Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
5773
5774 // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
5775 Intrinsic::ID IntrinsicId;
5776 switch (BuiltinID) {
5777 default: llvm_unreachable("Unknown multiprecision builtin id.");
5778 case Builtin::BI__builtin_addcb:
5779 case Builtin::BI__builtin_addcs:
5780 case Builtin::BI__builtin_addc:
5781 case Builtin::BI__builtin_addcl:
5782 case Builtin::BI__builtin_addcll:
5783 IntrinsicId = Intrinsic::uadd_with_overflow;
5784 break;
5785 case Builtin::BI__builtin_subcb:
5786 case Builtin::BI__builtin_subcs:
5787 case Builtin::BI__builtin_subc:
5788 case Builtin::BI__builtin_subcl:
5789 case Builtin::BI__builtin_subcll:
5790 IntrinsicId = Intrinsic::usub_with_overflow;
5791 break;
5792 }
5793
5794 // Construct our resulting LLVM IR expression.
5795 llvm::Value *Carry1;
5796 llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
5797 X, Y, Carry1);
5798 llvm::Value *Carry2;
5799 llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
5800 Sum1, Carryin, Carry2);
5801 llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
5802 X->getType());
5803 Builder.CreateStore(CarryOut, CarryOutPtr);
5804 return RValue::get(Sum2);
5805 }
5806
5807 case Builtin::BI__builtin_add_overflow:
5808 case Builtin::BI__builtin_sub_overflow:
5809 case Builtin::BI__builtin_mul_overflow: {
5810 const clang::Expr *LeftArg = E->getArg(0);
5811 const clang::Expr *RightArg = E->getArg(1);
5812 const clang::Expr *ResultArg = E->getArg(2);
5813
5814 clang::QualType ResultQTy =
5815 ResultArg->getType()->castAs<PointerType>()->getPointeeType();
5816
5817 WidthAndSignedness LeftInfo =
5818 getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
5819 WidthAndSignedness RightInfo =
5820 getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
5821 WidthAndSignedness ResultInfo =
5822 getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
5823
5824 // Handle mixed-sign multiplication as a special case, because adding
5825 // runtime or backend support for our generic irgen would be too expensive.
5826 if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
5827 return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
5828 RightInfo, ResultArg, ResultQTy,
5829 ResultInfo);
5830
5831 if (isSpecialUnsignedMultiplySignedResult(BuiltinID, LeftInfo, RightInfo,
5832 ResultInfo))
5834 *this, LeftArg, LeftInfo, RightArg, RightInfo, ResultArg, ResultQTy,
5835 ResultInfo);
5836
5837 WidthAndSignedness EncompassingInfo =
5838 EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
5839
5840 llvm::Type *EncompassingLLVMTy =
5841 llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
5842
5843 llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
5844
5845 Intrinsic::ID IntrinsicId;
5846 switch (BuiltinID) {
5847 default:
5848 llvm_unreachable("Unknown overflow builtin id.");
5849 case Builtin::BI__builtin_add_overflow:
5850 IntrinsicId = EncompassingInfo.Signed ? Intrinsic::sadd_with_overflow
5851 : Intrinsic::uadd_with_overflow;
5852 break;
5853 case Builtin::BI__builtin_sub_overflow:
5854 IntrinsicId = EncompassingInfo.Signed ? Intrinsic::ssub_with_overflow
5855 : Intrinsic::usub_with_overflow;
5856 break;
5857 case Builtin::BI__builtin_mul_overflow:
5858 IntrinsicId = EncompassingInfo.Signed ? Intrinsic::smul_with_overflow
5859 : Intrinsic::umul_with_overflow;
5860 break;
5861 }
5862
5863 llvm::Value *Left = EmitScalarExpr(LeftArg);
5864 llvm::Value *Right = EmitScalarExpr(RightArg);
5865 Address ResultPtr = EmitPointerWithAlignment(ResultArg);
5866
5867 // Extend each operand to the encompassing type.
5868 Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
5869 Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
5870
5871 // Perform the operation on the extended values.
5872 llvm::Value *Overflow, *Result;
5873 Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
5874
5875 if (EncompassingInfo.Width > ResultInfo.Width) {
5876 // The encompassing type is wider than the result type, so we need to
5877 // truncate it.
5878 llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
5879
5880 // To see if the truncation caused an overflow, we will extend
5881 // the result and then compare it to the original result.
5882 llvm::Value *ResultTruncExt = Builder.CreateIntCast(
5883 ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
5884 llvm::Value *TruncationOverflow =
5885 Builder.CreateICmpNE(Result, ResultTruncExt);
5886
5887 Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
5888 Result = ResultTrunc;
5889 }
5890
5891 // Finally, store the result using the pointer.
5892 bool isVolatile =
5893 ResultArg->getType()->getPointeeType().isVolatileQualified();
5894 Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
5895
5896 return RValue::get(Overflow);
5897 }
5898
5899 case Builtin::BI__builtin_uadd_overflow:
5900 case Builtin::BI__builtin_uaddl_overflow:
5901 case Builtin::BI__builtin_uaddll_overflow:
5902 case Builtin::BI__builtin_usub_overflow:
5903 case Builtin::BI__builtin_usubl_overflow:
5904 case Builtin::BI__builtin_usubll_overflow:
5905 case Builtin::BI__builtin_umul_overflow:
5906 case Builtin::BI__builtin_umull_overflow:
5907 case Builtin::BI__builtin_umulll_overflow:
5908 case Builtin::BI__builtin_sadd_overflow:
5909 case Builtin::BI__builtin_saddl_overflow:
5910 case Builtin::BI__builtin_saddll_overflow:
5911 case Builtin::BI__builtin_ssub_overflow:
5912 case Builtin::BI__builtin_ssubl_overflow:
5913 case Builtin::BI__builtin_ssubll_overflow:
5914 case Builtin::BI__builtin_smul_overflow:
5915 case Builtin::BI__builtin_smull_overflow:
5916 case Builtin::BI__builtin_smulll_overflow: {
5917
5918 // We translate all of these builtins directly to the relevant llvm IR node.
5919
5920 // Scalarize our inputs.
5921 llvm::Value *X = EmitScalarExpr(E->getArg(0));
5922 llvm::Value *Y = EmitScalarExpr(E->getArg(1));
5923 Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
5924
5925 // Decide which of the overflow intrinsics we are lowering to:
5926 Intrinsic::ID IntrinsicId;
5927 switch (BuiltinID) {
5928 default: llvm_unreachable("Unknown overflow builtin id.");
5929 case Builtin::BI__builtin_uadd_overflow:
5930 case Builtin::BI__builtin_uaddl_overflow:
5931 case Builtin::BI__builtin_uaddll_overflow:
5932 IntrinsicId = Intrinsic::uadd_with_overflow;
5933 break;
5934 case Builtin::BI__builtin_usub_overflow:
5935 case Builtin::BI__builtin_usubl_overflow:
5936 case Builtin::BI__builtin_usubll_overflow:
5937 IntrinsicId = Intrinsic::usub_with_overflow;
5938 break;
5939 case Builtin::BI__builtin_umul_overflow:
5940 case Builtin::BI__builtin_umull_overflow:
5941 case Builtin::BI__builtin_umulll_overflow:
5942 IntrinsicId = Intrinsic::umul_with_overflow;
5943 break;
5944 case Builtin::BI__builtin_sadd_overflow:
5945 case Builtin::BI__builtin_saddl_overflow:
5946 case Builtin::BI__builtin_saddll_overflow:
5947 IntrinsicId = Intrinsic::sadd_with_overflow;
5948 break;
5949 case Builtin::BI__builtin_ssub_overflow:
5950 case Builtin::BI__builtin_ssubl_overflow:
5951 case Builtin::BI__builtin_ssubll_overflow:
5952 IntrinsicId = Intrinsic::ssub_with_overflow;
5953 break;
5954 case Builtin::BI__builtin_smul_overflow:
5955 case Builtin::BI__builtin_smull_overflow:
5956 case Builtin::BI__builtin_smulll_overflow:
5957 IntrinsicId = Intrinsic::smul_with_overflow;
5958 break;
5959 }
5960
5961
5962 llvm::Value *Carry;
5963 llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
5964 Builder.CreateStore(Sum, SumOutPtr);
5965
5966 return RValue::get(Carry);
5967 }
5968 case Builtin::BIaddressof:
5969 case Builtin::BI__addressof:
5970 case Builtin::BI__builtin_addressof:
5971 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
5972 case Builtin::BI__builtin_function_start:
5973 return RValue::get(CGM.GetFunctionStart(
5974 E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext())));
5975 case Builtin::BI__builtin_operator_new:
5977 E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
5978 case Builtin::BI__builtin_operator_delete:
5980 E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
5981 return RValue::get(nullptr);
5982
5983 case Builtin::BI__builtin_is_aligned:
5984 return EmitBuiltinIsAligned(E);
5985 case Builtin::BI__builtin_align_up:
5986 return EmitBuiltinAlignTo(E, true);
5987 case Builtin::BI__builtin_align_down:
5988 return EmitBuiltinAlignTo(E, false);
5989
5990 case Builtin::BI__noop:
5991 // __noop always evaluates to an integer literal zero.
5992 return RValue::get(ConstantInt::get(IntTy, 0));
5993 case Builtin::BI__builtin_call_with_static_chain: {
5994 const CallExpr *Call = cast<CallExpr>(E->getArg(0));
5995 const Expr *Chain = E->getArg(1);
5996 return EmitCall(Call->getCallee()->getType(),
5997 EmitCallee(Call->getCallee()), Call, ReturnValue,
5998 EmitScalarExpr(Chain));
5999 }
6000 case Builtin::BI_InterlockedExchange8:
6001 case Builtin::BI_InterlockedExchange16:
6002 case Builtin::BI_InterlockedExchange:
6003 case Builtin::BI_InterlockedExchangePointer:
6004 return RValue::get(
6006 case Builtin::BI_InterlockedCompareExchangePointer:
6007 return RValue::get(
6009 case Builtin::BI_InterlockedCompareExchangePointer_nf:
6010 return RValue::get(
6012 case Builtin::BI_InterlockedCompareExchange8:
6013 case Builtin::BI_InterlockedCompareExchange16:
6014 case Builtin::BI_InterlockedCompareExchange:
6015 case Builtin::BI_InterlockedCompareExchange64:
6016 return RValue::get(EmitAtomicCmpXchgForMSIntrin(*this, E));
6017 case Builtin::BI_InterlockedIncrement16:
6018 case Builtin::BI_InterlockedIncrement:
6019 return RValue::get(
6021 case Builtin::BI_InterlockedDecrement16:
6022 case Builtin::BI_InterlockedDecrement:
6023 return RValue::get(
6025 case Builtin::BI_InterlockedAnd8:
6026 case Builtin::BI_InterlockedAnd16:
6027 case Builtin::BI_InterlockedAnd:
6029 case Builtin::BI_InterlockedExchangeAdd8:
6030 case Builtin::BI_InterlockedExchangeAdd16:
6031 case Builtin::BI_InterlockedExchangeAdd:
6032 return RValue::get(
6034 case Builtin::BI_InterlockedExchangeSub8:
6035 case Builtin::BI_InterlockedExchangeSub16:
6036 case Builtin::BI_InterlockedExchangeSub:
6037 return RValue::get(
6039 case Builtin::BI_InterlockedOr8:
6040 case Builtin::BI_InterlockedOr16:
6041 case Builtin::BI_InterlockedOr:
6043 case Builtin::BI_InterlockedXor8:
6044 case Builtin::BI_InterlockedXor16:
6045 case Builtin::BI_InterlockedXor:
6047
6048 case Builtin::BI_bittest64:
6049 case Builtin::BI_bittest:
6050 case Builtin::BI_bittestandcomplement64:
6051 case Builtin::BI_bittestandcomplement:
6052 case Builtin::BI_bittestandreset64:
6053 case Builtin::BI_bittestandreset:
6054 case Builtin::BI_bittestandset64:
6055 case Builtin::BI_bittestandset:
6056 case Builtin::BI_interlockedbittestandreset:
6057 case Builtin::BI_interlockedbittestandreset64:
6058 case Builtin::BI_interlockedbittestandreset64_acq:
6059 case Builtin::BI_interlockedbittestandreset64_rel:
6060 case Builtin::BI_interlockedbittestandreset64_nf:
6061 case Builtin::BI_interlockedbittestandset64:
6062 case Builtin::BI_interlockedbittestandset64_acq:
6063 case Builtin::BI_interlockedbittestandset64_rel:
6064 case Builtin::BI_interlockedbittestandset64_nf:
6065 case Builtin::BI_interlockedbittestandset:
6066 case Builtin::BI_interlockedbittestandset_acq:
6067 case Builtin::BI_interlockedbittestandset_rel:
6068 case Builtin::BI_interlockedbittestandset_nf:
6069 case Builtin::BI_interlockedbittestandreset_acq:
6070 case Builtin::BI_interlockedbittestandreset_rel:
6071 case Builtin::BI_interlockedbittestandreset_nf:
6072 return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
6073
6074 // These builtins exist to emit regular volatile loads and stores not
6075 // affected by the -fms-volatile setting.
6076 case Builtin::BI__iso_volatile_load8:
6077 case Builtin::BI__iso_volatile_load16:
6078 case Builtin::BI__iso_volatile_load32:
6079 case Builtin::BI__iso_volatile_load64:
6080 return RValue::get(EmitISOVolatileLoad(*this, E));
6081 case Builtin::BI__iso_volatile_store8:
6082 case Builtin::BI__iso_volatile_store16:
6083 case Builtin::BI__iso_volatile_store32:
6084 case Builtin::BI__iso_volatile_store64:
6085 return RValue::get(EmitISOVolatileStore(*this, E));
6086
6087 case Builtin::BI__builtin_ptrauth_sign_constant:
6088 return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
6089
6090 case Builtin::BI__builtin_ptrauth_auth:
6091 case Builtin::BI__builtin_ptrauth_auth_and_resign:
6092 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
6093 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
6094 case Builtin::BI__builtin_ptrauth_blend_discriminator:
6095 case Builtin::BI__builtin_ptrauth_sign_generic_data:
6096 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
6097 case Builtin::BI__builtin_ptrauth_strip: {
6098 // Emit the arguments.
6100 for (auto argExpr : E->arguments())
6101 Args.push_back(EmitScalarExpr(argExpr));
6102
6103 // Cast the value to intptr_t, saving its original type.
6104 llvm::Type *OrigValueType = Args[0]->getType();
6105 if (OrigValueType->isPointerTy())
6106 Args[0] = Builder.CreatePtrToInt(Args[0], IntPtrTy);
6107
6108 switch (BuiltinID) {
6109 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
6110 // Convert oldDiscriminator (arg 2), oldPC (arg 3) and newDiscriminator
6111 // (arg 5) to intptr_t
6112 if (Args[2]->getType()->isPointerTy())
6113 Args[2] = Builder.CreatePtrToInt(Args[2], IntPtrTy);
6114 if (Args[3]->getType()->isPointerTy())
6115 Args[3] = Builder.CreatePtrToInt(Args[3], IntPtrTy);
6116 if (Args[5]->getType()->isPointerTy())
6117 Args[5] = Builder.CreatePtrToInt(Args[5], IntPtrTy);
6118 break;
6119
6120 case Builtin::BI__builtin_ptrauth_auth_and_resign:
6121 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
6122 if (Args[4]->getType()->isPointerTy())
6123 Args[4] = Builder.CreatePtrToInt(Args[4], IntPtrTy);
6124 [[fallthrough]];
6125
6126 case Builtin::BI__builtin_ptrauth_auth:
6127 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
6128 if (Args[2]->getType()->isPointerTy())
6129 Args[2] = Builder.CreatePtrToInt(Args[2], IntPtrTy);
6130 break;
6131
6132 case Builtin::BI__builtin_ptrauth_sign_generic_data:
6133 if (Args[1]->getType()->isPointerTy())
6134 Args[1] = Builder.CreatePtrToInt(Args[1], IntPtrTy);
6135 break;
6136
6137 case Builtin::BI__builtin_ptrauth_blend_discriminator:
6138 case Builtin::BI__builtin_ptrauth_strip:
6139 break;
6140 }
6141
6142 // Call the intrinsic.
6143 auto IntrinsicID = [&]() -> unsigned {
6144 switch (BuiltinID) {
6145 case Builtin::BI__builtin_ptrauth_auth:
6146 return Intrinsic::ptrauth_auth;
6147 case Builtin::BI__builtin_ptrauth_auth_and_resign:
6148 return Intrinsic::ptrauth_resign;
6149 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
6150 return Intrinsic::ptrauth_auth_with_pc_and_resign;
6151 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
6152 return Intrinsic::ptrauth_resign_load_relative;
6153 case Builtin::BI__builtin_ptrauth_blend_discriminator:
6154 return Intrinsic::ptrauth_blend;
6155 case Builtin::BI__builtin_ptrauth_sign_generic_data:
6156 return Intrinsic::ptrauth_sign_generic;
6157 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
6158 return Intrinsic::ptrauth_sign;
6159 case Builtin::BI__builtin_ptrauth_strip:
6160 return Intrinsic::ptrauth_strip;
6161 }
6162 llvm_unreachable("bad ptrauth intrinsic");
6163 }();
6164 auto Intrinsic = CGM.getIntrinsic(IntrinsicID);
6165 llvm::Value *Result = EmitRuntimeCall(Intrinsic, Args);
6166
6167 if (BuiltinID != Builtin::BI__builtin_ptrauth_sign_generic_data &&
6168 BuiltinID != Builtin::BI__builtin_ptrauth_blend_discriminator &&
6169 OrigValueType->isPointerTy()) {
6170 Result = Builder.CreateIntToPtr(Result, OrigValueType);
6171 }
6172 return RValue::get(Result);
6173 }
6174
6175 case Builtin::BI__builtin_get_vtable_pointer: {
6176 const Expr *Target = E->getArg(0);
6177 QualType TargetType = Target->getType();
6178 const CXXRecordDecl *Decl = TargetType->getPointeeCXXRecordDecl();
6179 assert(Decl);
6180 auto ThisAddress = EmitPointerWithAlignment(Target);
6181 assert(ThisAddress.isValid());
6182 llvm::Value *VTablePointer =
6184 return RValue::get(VTablePointer);
6185 }
6186
6187 case Builtin::BI__exception_code:
6188 case Builtin::BI_exception_code:
6190 case Builtin::BI__exception_info:
6191 case Builtin::BI_exception_info:
6193 case Builtin::BI__abnormal_termination:
6194 case Builtin::BI_abnormal_termination:
6196 case Builtin::BI_setjmpex:
6197 if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
6198 E->getArg(0)->getType()->isPointerType())
6199 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
6200 break;
6201 case Builtin::BI_setjmp:
6202 if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
6203 E->getArg(0)->getType()->isPointerType()) {
6204 if (getTarget().getTriple().getArch() == llvm::Triple::x86)
6205 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
6206 else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
6207 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
6208 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
6209 }
6210 break;
6211
6212 // C++ std:: builtins.
6213 case Builtin::BImove:
6214 case Builtin::BImove_if_noexcept:
6215 case Builtin::BIforward:
6216 case Builtin::BIforward_like:
6217 case Builtin::BIas_const:
6218 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
6219 case Builtin::BI__GetExceptionInfo: {
6220 if (llvm::GlobalVariable *GV =
6221 CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
6222 return RValue::get(GV);
6223 break;
6224 }
6225
6226 case Builtin::BI__fastfail:
6228
6229 case Builtin::BI__builtin_coro_id:
6230 return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
6231 case Builtin::BI__builtin_coro_promise:
6232 return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
6233 case Builtin::BI__builtin_coro_resume:
6234 EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
6235 return RValue::get(nullptr);
6236 case Builtin::BI__builtin_coro_frame:
6237 return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
6238 case Builtin::BI__builtin_coro_noop:
6239 return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
6240 case Builtin::BI__builtin_coro_free:
6241 return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
6242 case Builtin::BI__builtin_coro_destroy:
6243 EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
6244 return RValue::get(nullptr);
6245 case Builtin::BI__builtin_coro_done:
6246 return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
6247 case Builtin::BI__builtin_coro_alloc:
6248 return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
6249 case Builtin::BI__builtin_coro_begin:
6250 return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
6251 case Builtin::BI__builtin_coro_end:
6252 return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
6253 case Builtin::BI__builtin_coro_suspend:
6254 return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
6255 case Builtin::BI__builtin_coro_size:
6256 return EmitCoroutineIntrinsic(E, Intrinsic::coro_size);
6257 case Builtin::BI__builtin_coro_align:
6258 return EmitCoroutineIntrinsic(E, Intrinsic::coro_align);
6259
6260 // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
6261 case Builtin::BIread_pipe:
6262 case Builtin::BIwrite_pipe: {
6263 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
6264 *Arg1 = EmitScalarExpr(E->getArg(1));
6265 CGOpenCLRuntime OpenCLRT(CGM);
6266 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6267 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6268
6269 // Type of the generic packet parameter.
6270 unsigned GenericAS =
6272 llvm::Type *I8PTy = llvm::PointerType::get(getLLVMContext(), GenericAS);
6273
6274 // Testing which overloaded version we should generate the call for.
6275 if (2U == E->getNumArgs()) {
6276 const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
6277 : "__write_pipe_2";
6278 // Creating a generic function type to be able to call with any builtin or
6279 // user defined type.
6280 llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
6281 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6282 Value *ACast = Builder.CreateAddrSpaceCast(Arg1, I8PTy);
6283 return RValue::get(
6284 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6285 {Arg0, ACast, PacketSize, PacketAlign}));
6286 } else {
6287 assert(4 == E->getNumArgs() &&
6288 "Illegal number of parameters to pipe function");
6289 const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
6290 : "__write_pipe_4";
6291
6292 llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
6293 Int32Ty, Int32Ty};
6294 Value *Arg2 = EmitScalarExpr(E->getArg(2)),
6295 *Arg3 = EmitScalarExpr(E->getArg(3));
6296 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6297 Value *ACast = Builder.CreateAddrSpaceCast(Arg3, I8PTy);
6298 // We know the third argument is an integer type, but we may need to cast
6299 // it to i32.
6300 if (Arg2->getType() != Int32Ty)
6301 Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
6302 return RValue::get(
6303 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6304 {Arg0, Arg1, Arg2, ACast, PacketSize, PacketAlign}));
6305 }
6306 }
6307 // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
6308 // functions
6309 case Builtin::BIreserve_read_pipe:
6310 case Builtin::BIreserve_write_pipe:
6311 case Builtin::BIwork_group_reserve_read_pipe:
6312 case Builtin::BIwork_group_reserve_write_pipe:
6313 case Builtin::BIsub_group_reserve_read_pipe:
6314 case Builtin::BIsub_group_reserve_write_pipe: {
6315 // Composing the mangled name for the function.
6316 const char *Name;
6317 if (BuiltinID == Builtin::BIreserve_read_pipe)
6318 Name = "__reserve_read_pipe";
6319 else if (BuiltinID == Builtin::BIreserve_write_pipe)
6320 Name = "__reserve_write_pipe";
6321 else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
6322 Name = "__work_group_reserve_read_pipe";
6323 else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
6324 Name = "__work_group_reserve_write_pipe";
6325 else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
6326 Name = "__sub_group_reserve_read_pipe";
6327 else
6328 Name = "__sub_group_reserve_write_pipe";
6329
6330 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
6331 *Arg1 = EmitScalarExpr(E->getArg(1));
6332 llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
6333 CGOpenCLRuntime OpenCLRT(CGM);
6334 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6335 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6336
6337 // Building the generic function prototype.
6338 llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
6339 llvm::FunctionType *FTy =
6340 llvm::FunctionType::get(ReservedIDTy, ArgTys, false);
6341 // We know the second argument is an integer type, but we may need to cast
6342 // it to i32.
6343 if (Arg1->getType() != Int32Ty)
6344 Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
6345 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6346 {Arg0, Arg1, PacketSize, PacketAlign}));
6347 }
6348 // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
6349 // functions
6350 case Builtin::BIcommit_read_pipe:
6351 case Builtin::BIcommit_write_pipe:
6352 case Builtin::BIwork_group_commit_read_pipe:
6353 case Builtin::BIwork_group_commit_write_pipe:
6354 case Builtin::BIsub_group_commit_read_pipe:
6355 case Builtin::BIsub_group_commit_write_pipe: {
6356 const char *Name;
6357 if (BuiltinID == Builtin::BIcommit_read_pipe)
6358 Name = "__commit_read_pipe";
6359 else if (BuiltinID == Builtin::BIcommit_write_pipe)
6360 Name = "__commit_write_pipe";
6361 else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
6362 Name = "__work_group_commit_read_pipe";
6363 else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
6364 Name = "__work_group_commit_write_pipe";
6365 else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
6366 Name = "__sub_group_commit_read_pipe";
6367 else
6368 Name = "__sub_group_commit_write_pipe";
6369
6370 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
6371 *Arg1 = EmitScalarExpr(E->getArg(1));
6372 CGOpenCLRuntime OpenCLRT(CGM);
6373 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6374 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6375
6376 // Building the generic function prototype.
6377 llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
6378 llvm::FunctionType *FTy = llvm::FunctionType::get(
6379 llvm::Type::getVoidTy(getLLVMContext()), ArgTys, false);
6380
6381 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6382 {Arg0, Arg1, PacketSize, PacketAlign}));
6383 }
6384 // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
6385 case Builtin::BIget_pipe_num_packets:
6386 case Builtin::BIget_pipe_max_packets: {
6387 const char *BaseName;
6388 const auto *PipeTy = E->getArg(0)->getType()->castAs<PipeType>();
6389 if (BuiltinID == Builtin::BIget_pipe_num_packets)
6390 BaseName = "__get_pipe_num_packets";
6391 else
6392 BaseName = "__get_pipe_max_packets";
6393 std::string Name = std::string(BaseName) +
6394 std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
6395
6396 // Building the generic function prototype.
6397 Value *Arg0 = EmitScalarExpr(E->getArg(0));
6398 CGOpenCLRuntime OpenCLRT(CGM);
6399 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6400 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6401 llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
6402 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6403
6404 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6405 {Arg0, PacketSize, PacketAlign}));
6406 }
6407
6408 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
6409 case Builtin::BIto_global:
6410 case Builtin::BIto_local:
6411 case Builtin::BIto_private: {
6412 auto Arg0 = EmitScalarExpr(E->getArg(0));
6413 auto NewArgT = llvm::PointerType::get(
6415 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
6416 auto NewRetT = llvm::PointerType::get(
6418 CGM.getContext().getTargetAddressSpace(
6420 auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
6421 llvm::Value *NewArg;
6422 if (Arg0->getType()->getPointerAddressSpace() !=
6423 NewArgT->getPointerAddressSpace())
6424 NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
6425 else
6426 NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
6427 auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
6428 auto NewCall =
6429 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
6430 return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
6431 ConvertType(E->getType())));
6432 }
6433
6434 // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
6435 // Table 6.13.17.1 specifies four overload forms of enqueue_kernel.
6436 // The code below expands the builtin call to a call to one of the following
6437 // functions that an OpenCL runtime library will have to provide:
6438 // __enqueue_kernel_basic
6439 // __enqueue_kernel_varargs
6440 // __enqueue_kernel_basic_events
6441 // __enqueue_kernel_events_varargs
6442 case Builtin::BIenqueue_kernel: {
6443 StringRef Name; // Generated function call name
6444 unsigned NumArgs = E->getNumArgs();
6445
6446 llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
6447 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6448 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6449
6450 llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
6451 llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
6452 LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
6453 llvm::Value *Range = NDRangeL.getAddress().emitRawPointer(*this);
6454
6455 // FIXME: Look through the addrspacecast which may exist to the stack
6456 // temporary as a hack.
6457 //
6458 // This is hardcoding the assumed ABI of the target function. This assumes
6459 // direct passing for every argument except NDRange, which is assumed to be
6460 // byval or byref indirect passed.
6461 //
6462 // This should be fixed to query a signature from CGOpenCLRuntime, and go
6463 // through EmitCallArgs to get the correct target ABI.
6464 Range = Range->stripPointerCasts();
6465
6466 llvm::Type *RangePtrTy = Range->getType();
6467
6468 if (NumArgs == 4) {
6469 // The most basic form of the call with parameters:
6470 // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
6471 Name = "__enqueue_kernel_basic";
6472 llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangePtrTy, GenericVoidPtrTy,
6473 GenericVoidPtrTy};
6474 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6475
6476 auto Info =
6477 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
6478 llvm::Value *Kernel =
6479 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6480 llvm::Value *Block =
6481 Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6482
6483 auto RTCall = EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6484 {Queue, Flags, Range, Kernel, Block});
6485 return RValue::get(RTCall);
6486 }
6487 assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
6488
6489 // Create a temporary array to hold the sizes of local pointer arguments
6490 // for the block. \p First is the position of the first size argument.
6491 auto CreateArrayForSizeVar =
6492 [=](unsigned First) -> std::pair<llvm::Value *, llvm::Value *> {
6493 llvm::APInt ArraySize(32, NumArgs - First);
6495 getContext().getSizeType(), ArraySize, nullptr,
6497 /*IndexTypeQuals=*/0);
6498 auto Tmp = CreateMemTempWithoutCast(SizeArrayTy, "block_sizes");
6499 llvm::Value *Alloca = Tmp.getPointer();
6500 llvm::Value *ElemPtr;
6501 EmitLifetimeStart(Alloca);
6502 // Each of the following arguments specifies the size of the corresponding
6503 // argument passed to the enqueued block.
6504 auto *Zero = llvm::ConstantInt::get(IntTy, 0);
6505 for (unsigned I = First; I < NumArgs; ++I) {
6506 auto *Index = llvm::ConstantInt::get(IntTy, I - First);
6507 auto *GEP =
6508 Builder.CreateGEP(Tmp.getElementType(), Alloca, {Zero, Index});
6509 if (I == First)
6510 ElemPtr = GEP;
6511 auto *V =
6512 Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
6513 Builder.CreateAlignedStore(
6514 V, GEP, CGM.getDataLayout().getPrefTypeAlign(SizeTy));
6515 }
6516 return {ElemPtr, Alloca};
6517 };
6518
6519 // Could have events and/or varargs.
6520 if (E->getArg(3)->getType()->isBlockPointerType()) {
6521 // No events passed, but has variadic arguments.
6522 Name = "__enqueue_kernel_varargs";
6523 auto Info =
6524 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
6525 llvm::Value *Kernel =
6526 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6527 auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6528 auto [ElemPtr, TmpPtr] = CreateArrayForSizeVar(4);
6529
6530 // Create a vector of the arguments, as well as a constant value to
6531 // express to the runtime the number of variadic arguments.
6532 llvm::Value *const Args[] = {Queue, Flags,
6533 Range, Kernel,
6534 Block, ConstantInt::get(IntTy, NumArgs - 4),
6535 ElemPtr};
6536 llvm::Type *const ArgTys[] = {
6537 QueueTy, IntTy, RangePtrTy, GenericVoidPtrTy,
6538 GenericVoidPtrTy, IntTy, ElemPtr->getType()};
6539
6540 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6541 auto Call = RValue::get(
6542 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
6543 EmitLifetimeEnd(TmpPtr);
6544 return Call;
6545 }
6546 // Any calls now have event arguments passed.
6547 if (NumArgs >= 7) {
6548 llvm::PointerType *PtrTy = llvm::PointerType::get(
6549 CGM.getLLVMContext(),
6550 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
6551
6552 llvm::Value *NumEvents =
6553 Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
6554
6555 // Since SemaOpenCLBuiltinEnqueueKernel allows fifth and sixth arguments
6556 // to be a null pointer constant (including `0` literal), we can take it
6557 // into account and emit null pointer directly.
6558 llvm::Value *EventWaitList = nullptr;
6559 if (E->getArg(4)->isNullPointerConstant(
6561 EventWaitList = llvm::ConstantPointerNull::get(PtrTy);
6562 } else {
6563 EventWaitList =
6564 E->getArg(4)->getType()->isArrayType()
6566 : EmitScalarExpr(E->getArg(4));
6567 // Convert to generic address space.
6568 EventWaitList = Builder.CreatePointerCast(EventWaitList, PtrTy);
6569 }
6570 llvm::Value *EventRet = nullptr;
6571 if (E->getArg(5)->isNullPointerConstant(
6573 EventRet = llvm::ConstantPointerNull::get(PtrTy);
6574 } else {
6575 EventRet =
6576 Builder.CreatePointerCast(EmitScalarExpr(E->getArg(5)), PtrTy);
6577 }
6578
6579 auto Info =
6580 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
6581 llvm::Value *Kernel =
6582 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6583 llvm::Value *Block =
6584 Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6585
6586 std::vector<llvm::Type *> ArgTys = {
6587 QueueTy, Int32Ty, RangePtrTy, Int32Ty,
6588 PtrTy, PtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
6589
6590 std::vector<llvm::Value *> Args = {Queue, Flags, Range,
6591 NumEvents, EventWaitList, EventRet,
6592 Kernel, Block};
6593
6594 if (NumArgs == 7) {
6595 // Has events but no variadics.
6596 Name = "__enqueue_kernel_basic_events";
6597 llvm::FunctionType *FTy =
6598 llvm::FunctionType::get(Int32Ty, ArgTys, false);
6599 return RValue::get(
6600 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
6601 }
6602 // Has event info and variadics
6603 // Pass the number of variadics to the runtime function too.
6604 Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
6605 ArgTys.push_back(Int32Ty);
6606 Name = "__enqueue_kernel_events_varargs";
6607
6608 auto [ElemPtr, TmpPtr] = CreateArrayForSizeVar(7);
6609 Args.push_back(ElemPtr);
6610 ArgTys.push_back(ElemPtr->getType());
6611
6612 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6613 auto Call = RValue::get(
6614 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
6615 EmitLifetimeEnd(TmpPtr);
6616 return Call;
6617 }
6618 llvm_unreachable("Unexpected enqueue_kernel signature");
6619 }
6620 // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
6621 // parameter.
6622 case Builtin::BIget_kernel_work_group_size: {
6623 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6624 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6625 auto Info =
6626 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
6627 Value *Kernel =
6628 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6629 Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6631 CGM.CreateRuntimeFunction(
6632 llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
6633 false),
6634 "__get_kernel_work_group_size_impl"),
6635 {Kernel, Arg}));
6636 }
6637 case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
6638 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6639 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6640 auto Info =
6641 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
6642 Value *Kernel =
6643 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6644 Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6646 CGM.CreateRuntimeFunction(
6647 llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
6648 false),
6649 "__get_kernel_preferred_work_group_size_multiple_impl"),
6650 {Kernel, Arg}));
6651 }
6652 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
6653 case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
6654 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6655 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6656 LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
6657 llvm::Value *NDRange = NDRangeL.getAddress().emitRawPointer(*this);
6658 auto Info =
6659 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
6660 Value *Kernel =
6661 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6662 Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6663 const char *Name =
6664 BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
6665 ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
6666 : "__get_kernel_sub_group_count_for_ndrange_impl";
6668 CGM.CreateRuntimeFunction(
6669 llvm::FunctionType::get(
6670 IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
6671 false),
6672 Name),
6673 {NDRange, Kernel, Block}));
6674 }
6675 case Builtin::BI__builtin_store_half:
6676 case Builtin::BI__builtin_store_halff: {
6677 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
6678 Value *Val = EmitScalarExpr(E->getArg(0));
6680 Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
6681 Builder.CreateStore(HalfVal, Address);
6682 return RValue::get(nullptr);
6683 }
6684 case Builtin::BI__builtin_load_half: {
6686 Value *HalfVal = Builder.CreateLoad(Address);
6687 return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
6688 }
6689 case Builtin::BI__builtin_load_halff: {
6691 Value *HalfVal = Builder.CreateLoad(Address);
6692 return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
6693 }
6694 case Builtin::BI__builtin_printf:
6695 case Builtin::BIprintf:
6696 if (getTarget().getTriple().isNVPTX() ||
6697 getTarget().getTriple().isAMDGCN() ||
6698 (getTarget().getTriple().isSPIRV() &&
6699 getTarget().getTriple().getVendor() == Triple::VendorType::AMD)) {
6700 if (getTarget().getTriple().isNVPTX())
6702 if ((getTarget().getTriple().isAMDGCN() ||
6703 getTarget().getTriple().isSPIRV()) &&
6704 getLangOpts().HIP)
6706 }
6707
6708 break;
6709 case Builtin::BI__builtin_canonicalize:
6710 case Builtin::BI__builtin_canonicalizef:
6711 case Builtin::BI__builtin_canonicalizef16:
6712 case Builtin::BI__builtin_canonicalizel:
6713 return RValue::get(
6714 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::canonicalize));
6715
6716 case Builtin::BI__builtin_thread_pointer: {
6717 if (!getContext().getTargetInfo().isTLSSupported())
6718 CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
6719
6720 return RValue::get(Builder.CreateIntrinsic(llvm::Intrinsic::thread_pointer,
6721 {GlobalsInt8PtrTy}, {}));
6722 }
6723 case Builtin::BI__builtin_os_log_format:
6724 return emitBuiltinOSLogFormat(*E);
6725
6726 case Builtin::BI__xray_customevent: {
6728 return RValue::getIgnored();
6729
6730 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
6732 return RValue::getIgnored();
6733
6734 if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
6735 if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
6736 return RValue::getIgnored();
6737
6738 Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
6739 auto FTy = F->getFunctionType();
6740 auto Arg0 = E->getArg(0);
6741 auto Arg0Val = EmitScalarExpr(Arg0);
6742 auto Arg0Ty = Arg0->getType();
6743 auto PTy0 = FTy->getParamType(0);
6744 if (PTy0 != Arg0Val->getType()) {
6745 if (Arg0Ty->isArrayType())
6746 Arg0Val = EmitArrayToPointerDecay(Arg0).emitRawPointer(*this);
6747 else
6748 Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
6749 }
6750 auto Arg1 = EmitScalarExpr(E->getArg(1));
6751 auto PTy1 = FTy->getParamType(1);
6752 if (PTy1 != Arg1->getType())
6753 Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
6754 return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
6755 }
6756
6757 case Builtin::BI__xray_typedevent: {
6758 // TODO: There should be a way to always emit events even if the current
6759 // function is not instrumented. Losing events in a stream can cripple
6760 // a trace.
6762 return RValue::getIgnored();
6763
6764 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
6766 return RValue::getIgnored();
6767
6768 if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
6769 if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
6770 return RValue::getIgnored();
6771
6772 Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
6773 auto FTy = F->getFunctionType();
6774 auto Arg0 = EmitScalarExpr(E->getArg(0));
6775 auto PTy0 = FTy->getParamType(0);
6776 if (PTy0 != Arg0->getType())
6777 Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
6778 auto Arg1 = E->getArg(1);
6779 auto Arg1Val = EmitScalarExpr(Arg1);
6780 auto Arg1Ty = Arg1->getType();
6781 auto PTy1 = FTy->getParamType(1);
6782 if (PTy1 != Arg1Val->getType()) {
6783 if (Arg1Ty->isArrayType())
6784 Arg1Val = EmitArrayToPointerDecay(Arg1).emitRawPointer(*this);
6785 else
6786 Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
6787 }
6788 auto Arg2 = EmitScalarExpr(E->getArg(2));
6789 auto PTy2 = FTy->getParamType(2);
6790 if (PTy2 != Arg2->getType())
6791 Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
6792 return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
6793 }
6794
6795 case Builtin::BI__builtin_ms_va_start:
6796 case Builtin::BI__builtin_ms_va_end:
6797 return RValue::get(
6799 BuiltinID == Builtin::BI__builtin_ms_va_start));
6800
6801 case Builtin::BI__builtin_ms_va_copy: {
6802 // Lower this manually. We can't reliably determine whether or not any
6803 // given va_copy() is for a Win64 va_list from the calling convention
6804 // alone, because it's legal to do this from a System V ABI function.
6805 // With opaque pointer types, we won't have enough information in LLVM
6806 // IR to determine this from the argument types, either. Best to do it
6807 // now, while we have enough information.
6808 Address DestAddr = EmitMSVAListRef(E->getArg(0));
6809 Address SrcAddr = EmitMSVAListRef(E->getArg(1));
6810
6811 DestAddr = DestAddr.withElementType(Int8PtrTy);
6812 SrcAddr = SrcAddr.withElementType(Int8PtrTy);
6813
6814 Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
6815 return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
6816 }
6817
6818 case Builtin::BI__builtin_zos_va_start:
6819 case Builtin::BI__builtin_zos_va_end: {
6820 // The va_list is an array with 2 elements, called curr and next.
6821 // Element curr is set to 0. For builtin_zos_va_start, next is initialized
6822 // with a call to @llvm.va_start. Otherwise, next is passed to @llvm.va_end.
6823 Address VAList = EmitZOSVAListRef(E->getArg(0));
6824 llvm::Type *VAListTy = ConvertType(getContext().getBuiltinZOSVaListType());
6825 VAList = VAList.withElementType(VAListTy);
6826 Address Curr = Builder.CreateConstArrayGEP(VAList, 0, "curr");
6827 Value *Zero = llvm::Constant::getNullValue(VoidPtrTy);
6828 Builder.CreateStore(Zero, Curr);
6829 Address Next = Builder.CreateConstArrayGEP(VAList, 1, "next");
6830 return RValue::get(
6831 EmitVAStartEnd(Next.emitRawPointer(*this),
6832 BuiltinID == Builtin::BI__builtin_zos_va_start));
6833 }
6834 case Builtin::BI__builtin_zos_va_copy: {
6835 // Lower this manually because later can't reliably determine the type.
6836 Address Dest = EmitZOSVAListRef(E->getArg(0));
6837 Address Src = EmitZOSVAListRef(E->getArg(1));
6838 llvm::Type *VAListTy = ConvertType(getContext().getBuiltinZOSVaListType());
6839 uint64_t SizeBytes =
6840 CGM.getDataLayout().getTypeAllocSize(VAListTy).getFixedValue();
6841 Value *SizeVal = llvm::ConstantInt::get(Int64Ty, SizeBytes);
6842 Builder.CreateMemCpy(Dest, Src, SizeVal, false);
6843 return RValue::get(Dest.emitRawPointer(*this));
6844 }
6845
6846 case Builtin::BI__builtin_get_device_side_mangled_name: {
6847 auto Name = CGM.getCUDARuntime().getDeviceSideName(
6848 cast<DeclRefExpr>(E->getArg(0)->IgnoreImpCasts())->getDecl());
6849 auto Str = CGM.GetAddrOfConstantCString(Name, "");
6850 return RValue::get(Str.getPointer());
6851 }
6852 }
6853
6854 // If this is an alias for a lib function (e.g. __builtin_sin), emit
6855 // the call using the normal call path, but using the unmangled
6856 // version of the function name.
6857 const auto &BI = getContext().BuiltinInfo;
6858 if (!shouldEmitBuiltinAsIR(BuiltinID, BI, *this) &&
6859 BI.isLibFunction(BuiltinID))
6860 return emitLibraryCall(*this, FD, E,
6861 CGM.getBuiltinLibFunction(FD, BuiltinID));
6862
6863 // If this is a predefined lib function (e.g. malloc), emit the call
6864 // using exactly the normal call path.
6865 if (BI.isPredefinedLibFunction(BuiltinID))
6866 return emitLibraryCall(*this, FD, E, CGM.getRawFunctionPointer(FD));
6867
6868 // Check that a call to a target specific builtin has the correct target
6869 // features.
6870 // This is down here to avoid non-target specific builtins, however, if
6871 // generic builtins start to require generic target features then we
6872 // can move this up to the beginning of the function.
6873 checkTargetFeatures(E, FD);
6874
6875 if (unsigned VectorWidth = getContext().BuiltinInfo.getRequiredVectorWidth(BuiltinID))
6876 LargestVectorWidth = std::max(LargestVectorWidth, VectorWidth);
6877
6878 // See if we have a target specific intrinsic.
6879 std::string Name = getContext().BuiltinInfo.getName(BuiltinID);
6880 Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
6881 StringRef Prefix =
6882 llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
6883 if (!Prefix.empty()) {
6884 IntrinsicID = Intrinsic::getIntrinsicForClangBuiltin(Prefix.data(), Name);
6885 if (IntrinsicID == Intrinsic::not_intrinsic && Prefix == "spv" &&
6886 getTarget().getTriple().getOS() == llvm::Triple::OSType::AMDHSA)
6887 IntrinsicID = Intrinsic::getIntrinsicForClangBuiltin("amdgcn", Name);
6888 // NOTE we don't need to perform a compatibility flag check here since the
6889 // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
6890 // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
6891 if (IntrinsicID == Intrinsic::not_intrinsic)
6892 IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
6893 }
6894
6895 if (IntrinsicID != Intrinsic::not_intrinsic) {
6897
6898 // Find out if any arguments are required to be integer constant
6899 // expressions.
6900 unsigned ICEArguments = 0;
6902 getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
6903 assert(Error == ASTContext::GE_None && "Should not codegen an error");
6904
6905 Function *F = CGM.getIntrinsic(IntrinsicID);
6906 llvm::FunctionType *FTy = F->getFunctionType();
6907
6908 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
6909 Value *ArgValue = EmitScalarOrConstFoldImmArg(ICEArguments, i, E);
6910 // If the intrinsic arg type is different from the builtin arg type
6911 // we need to do a bit cast.
6912 llvm::Type *PTy = FTy->getParamType(i);
6913 if (PTy != ArgValue->getType()) {
6914 // XXX - vector of pointers?
6915 if (auto *PtrTy = dyn_cast<llvm::PointerType>(PTy)) {
6916 if (PtrTy->getAddressSpace() !=
6917 ArgValue->getType()->getPointerAddressSpace()) {
6918 ArgValue = Builder.CreateAddrSpaceCast(
6919 ArgValue, llvm::PointerType::get(getLLVMContext(),
6920 PtrTy->getAddressSpace()));
6921 }
6922 }
6923
6924 // Cast vector type (e.g., v256i32) to x86_amx, this only happen
6925 // in amx intrinsics.
6926 if (PTy->isX86_AMXTy())
6927 ArgValue = Builder.CreateIntrinsic(Intrinsic::x86_cast_vector_to_tile,
6928 {ArgValue->getType()}, {ArgValue});
6929 else
6930 ArgValue = Builder.CreateBitCast(ArgValue, PTy);
6931 }
6932
6933 Args.push_back(ArgValue);
6934 }
6935
6937
6938 Value *V = Builder.CreateCall(F, Args);
6939 QualType BuiltinRetType = E->getType();
6940
6941 llvm::Type *RetTy = VoidTy;
6942 if (!BuiltinRetType->isVoidType())
6943 RetTy = ConvertType(BuiltinRetType);
6944
6945 if (RetTy != V->getType()) {
6946 // XXX - vector of pointers?
6947 if (auto *PtrTy = dyn_cast<llvm::PointerType>(RetTy)) {
6948 if (PtrTy->getAddressSpace() != V->getType()->getPointerAddressSpace()) {
6949 V = Builder.CreateAddrSpaceCast(
6950 V, llvm::PointerType::get(getLLVMContext(),
6951 PtrTy->getAddressSpace()));
6952 }
6953 }
6954
6955 // Cast x86_amx to vector type (e.g., v256i32), this only happen
6956 // in amx intrinsics.
6957 if (V->getType()->isX86_AMXTy())
6958 V = Builder.CreateIntrinsic(Intrinsic::x86_cast_tile_to_vector, {RetTy},
6959 {V});
6960 else
6961 V = Builder.CreateBitCast(V, RetTy);
6962 }
6963
6964 if (RetTy->isVoidTy())
6965 return RValue::get(nullptr);
6966
6967 return RValue::get(V);
6968 }
6969
6970 // Some target-specific builtins can have aggregate return values, e.g.
6971 // __builtin_arm_mve_vld2q_u32. So if the result is an aggregate, force
6972 // ReturnValue to be non-null, so that the target-specific emission code can
6973 // always just emit into it.
6975 if (EvalKind == TEK_Aggregate && ReturnValue.isNull()) {
6976 Address DestPtr = CreateMemTemp(E->getType(), "agg.tmp");
6977 ReturnValue = ReturnValueSlot(DestPtr, false);
6978 }
6979
6980 // Now see if we can emit a target-specific builtin.
6981 if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E, ReturnValue)) {
6982 switch (EvalKind) {
6983 case TEK_Scalar:
6984 if (V->getType()->isVoidTy())
6985 return RValue::get(nullptr);
6986 return RValue::get(V);
6987 case TEK_Aggregate:
6988 return RValue::getAggregate(ReturnValue.getAddress(),
6989 ReturnValue.isVolatile());
6990 case TEK_Complex:
6991 llvm_unreachable("No current target builtin returns complex");
6992 }
6993 llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
6994 }
6995
6996 // EmitHLSLBuiltinExpr will check getLangOpts().HLSL
6997 if (Value *V = EmitHLSLBuiltinExpr(BuiltinID, E, ReturnValue)) {
6998 switch (EvalKind) {
6999 case TEK_Scalar:
7000 if (V->getType()->isVoidTy())
7001 return RValue::get(nullptr);
7002 return RValue::get(V);
7003 case TEK_Aggregate:
7004 return RValue::getAggregate(ReturnValue.getAddress(),
7005 ReturnValue.isVolatile());
7006 case TEK_Complex:
7007 llvm_unreachable("No current hlsl builtin returns complex");
7008 }
7009 llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
7010 }
7011
7012 if (getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice)
7013 return EmitHipStdParUnsupportedBuiltin(this, FD);
7014
7015 ErrorUnsupported(E, "builtin function");
7016
7017 // Unknown builtin, for now just dump it out and return undef.
7018 return GetUndefRValue(E->getType());
7019}
7020
7021namespace {
7022struct BuiltinAlignArgs {
7023 llvm::Value *Src = nullptr;
7024 llvm::Type *SrcType = nullptr;
7025 llvm::Value *Alignment = nullptr;
7026 llvm::Value *Mask = nullptr;
7027 llvm::IntegerType *IntType = nullptr;
7028
7029 BuiltinAlignArgs(const CallExpr *E, CodeGenFunction &CGF) {
7030 QualType AstType = E->getArg(0)->getType();
7031 if (AstType->isArrayType())
7032 Src = CGF.EmitArrayToPointerDecay(E->getArg(0)).emitRawPointer(CGF);
7033 else
7034 Src = CGF.EmitScalarExpr(E->getArg(0));
7035 SrcType = Src->getType();
7036 if (SrcType->isPointerTy()) {
7037 IntType = IntegerType::get(
7038 CGF.getLLVMContext(),
7039 CGF.CGM.getDataLayout().getIndexTypeSizeInBits(SrcType));
7040 } else {
7041 assert(SrcType->isIntegerTy());
7042 IntType = cast<llvm::IntegerType>(SrcType);
7043 }
7044 Alignment = CGF.EmitScalarExpr(E->getArg(1));
7045 Alignment = CGF.Builder.CreateZExtOrTrunc(Alignment, IntType, "alignment");
7046 auto *One = llvm::ConstantInt::get(IntType, 1);
7047 Mask = CGF.Builder.CreateSub(Alignment, One, "mask");
7048 }
7049};
7050} // namespace
7051
7052/// Generate (x & (y-1)) == 0.
7054 BuiltinAlignArgs Args(E, *this);
7055 llvm::Value *SrcAddress = Args.Src;
7056 if (Args.SrcType->isPointerTy())
7057 SrcAddress =
7058 Builder.CreateBitOrPointerCast(Args.Src, Args.IntType, "src_addr");
7059 return RValue::get(Builder.CreateICmpEQ(
7060 Builder.CreateAnd(SrcAddress, Args.Mask, "set_bits"),
7061 llvm::Constant::getNullValue(Args.IntType), "is_aligned"));
7062}
7063
7064/// Generate (x & ~(y-1)) to align down or ((x+(y-1)) & ~(y-1)) to align up.
7065/// Note: For pointer types we can avoid ptrtoint/inttoptr pairs by using the
7066/// llvm.ptrmask intrinsic (with a GEP before in the align_up case).
7068 BuiltinAlignArgs Args(E, *this);
7069 llvm::Value *SrcForMask = Args.Src;
7070 if (AlignUp) {
7071 // When aligning up we have to first add the mask to ensure we go over the
7072 // next alignment value and then align down to the next valid multiple.
7073 // By adding the mask, we ensure that align_up on an already aligned
7074 // value will not change the value.
7075 if (Args.Src->getType()->isPointerTy()) {
7076 if (getLangOpts().PointerOverflowDefined)
7077 SrcForMask =
7078 Builder.CreateGEP(Int8Ty, SrcForMask, Args.Mask, "over_boundary");
7079 else
7080 SrcForMask = EmitCheckedInBoundsGEP(Int8Ty, SrcForMask, Args.Mask,
7081 /*SignedIndices=*/true,
7082 /*isSubtraction=*/false,
7083 E->getExprLoc(), "over_boundary");
7084 } else {
7085 SrcForMask = Builder.CreateAdd(SrcForMask, Args.Mask, "over_boundary");
7086 }
7087 }
7088 // Invert the mask to only clear the lower bits.
7089 llvm::Value *InvertedMask = Builder.CreateNot(Args.Mask, "inverted_mask");
7090 llvm::Value *Result = nullptr;
7091 if (Args.Src->getType()->isPointerTy()) {
7092 Result = Builder.CreateIntrinsic(
7093 Intrinsic::ptrmask, {Args.SrcType, Args.IntType},
7094 {SrcForMask, InvertedMask}, nullptr, "aligned_result");
7095 } else {
7096 Result = Builder.CreateAnd(SrcForMask, InvertedMask, "aligned_result");
7097 }
7098 assert(Result->getType() == Args.SrcType);
7099 return RValue::get(Result);
7100}
#define V(N, I)
static void ClearPadding(CodeGenFunction &CGF, Address Src, const ASTContext::BitInterval &PaddingInterval)
static char bitActionToX86BTCode(BitTest::ActionKind A)
static Value * EmitAtomicCmpXchg128ForMSIntrin(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering SuccessOrdering)
static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E, Intrinsic::ID IntrinsicID)
static CanQualType getOSLogArgType(ASTContext &C, int Size)
Get the argument type for arguments to os_log_helper.
static Value * EmitOverflowCheckedAbs(CodeGenFunction &CGF, const CallExpr *E, bool SanitizeOverflow)
static llvm::Value * EmitBitCountExpr(CodeGenFunction &CGF, const Expr *E)
static Value * tryUseTestFPKind(CodeGenFunction &CGF, unsigned BuiltinID, Value *V)
static bool areBOSTypesCompatible(int From, int To)
Checks if using the result of __builtin_object_size(p, From) in place of __builtin_object_size(p,...
static std::pair< llvm::Value *, llvm::Value * > GetCountFieldAndIndex(CodeGenFunction &CGF, const MemberExpr *ME, const FieldDecl *ArrayFD, const FieldDecl *CountFD, const Expr *Idx, llvm::IntegerType *ResType, bool IsSigned)
Value * EmitFromInt(CodeGenFunction &CGF, llvm::Value *V, QualType T, llvm::Type *ResultType)
Value * MakeAtomicCmpXchgValue(CodeGenFunction &CGF, const CallExpr *E, bool ReturnBool, llvm::AtomicOrdering SuccessOrdering, llvm::AtomicOrdering FailureOrdering)
Utility to insert an atomic cmpxchg instruction.
static Value * EmitAtomicIncrementValue(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering Ordering=AtomicOrdering::SequentiallyConsistent)
static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind, const CallExpr *E)
MSVC handles setjmp a bit differently on different platforms.
#define MUTATE_LDBL(func)
static Value * emitMaybeConstrainedFPToIntRoundBuiltin(CodeGenFunction &CGF, const CallExpr *E, unsigned IntrinsicID, unsigned ConstrainedIntrinsicID)
static bool TypeRequiresBuiltinLaunder(CodeGenModule &CGM, QualType Ty)
Determine if the specified type requires laundering by checking if it is a dynamic class type or cont...
static Value * EmitISOVolatileLoad(CodeGenFunction &CGF, const CallExpr *E)
static Value * EmitTargetArchBuiltinExpr(CodeGenFunction *CGF, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue, llvm::Triple::ArchType Arch)
Definition CGBuiltin.cpp:74
static RValue EmitBinaryAtomicPost(CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E, Instruction::BinaryOps Op, bool Invert=false)
Utility to insert an atomic instruction based Intrinsic::ID and the expression node,...
Value * EmitToInt(CodeGenFunction &CGF, llvm::Value *V, QualType T, llvm::IntegerType *IntType)
Emit the conversions required to turn the given value into an integer of the given size.
static llvm::Value * EmitBitTestIntrinsic(CodeGenFunction &CGF, unsigned BuiltinID, const CallExpr *E)
Emit a _bittest* intrinsic.
static Value * EmitSignBit(CodeGenFunction &CGF, Value *V)
Emit the computation of the sign bit for a floating point value.
static Value * EmitFAbs(CodeGenFunction &CGF, Value *V)
EmitFAbs - Emit a call to @llvm.fabs().
static llvm::Value * EmitPositiveResultOrZero(CodeGenFunction &CGF, llvm::Value *Res, llvm::Value *Index, llvm::IntegerType *ResType, bool IsSigned)
static bool shouldEmitBuiltinAsIR(unsigned BuiltinID, const Builtin::Context &BI, const CodeGenFunction &CGF)
Some builtins do not have library implementation on some targets and are instead emitted as LLVM IRs ...
Definition CGBuiltin.cpp:50
void appendDefaultIntrinsicArgs(SmallVectorImpl< llvm::Value * > &Args, llvm::Function *F)
static bool isSpecialUnsignedMultiplySignedResult(unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info, WidthAndSignedness ResultInfo)
static llvm::Value * getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType)
static RValue EmitCheckedMixedSignMultiply(CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info, const clang::Expr *Op2, WidthAndSignedness Op2Info, const clang::Expr *ResultArg, QualType ResultQTy, WidthAndSignedness ResultInfo)
Emit a checked mixed-sign multiply.
static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID)
static RValue EmitBinaryAtomic(CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E)
static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size, Align AlignmentInBytes)
static Value * EmitAtomicCmpXchgForMSIntrin(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering SuccessOrdering=AtomicOrdering::SequentiallyConsistent)
This function should be invoked to emit atomic cmpxchg for Microsoft's _InterlockedCompareExchange* i...
static bool isSpecialMixedSignMultiply(unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info, WidthAndSignedness ResultInfo)
Determine if a binop is a checked mixed-sign multiply we can specialize.
static Value * emitFrexpBuiltin(CodeGenFunction &CGF, const CallExpr *E, Intrinsic::ID IntrinsicID)
static llvm::Value * emitModfBuiltin(CodeGenFunction &CGF, const CallExpr *E, Intrinsic::ID IntrinsicID)
static Value * EmitNontemporalStore(CodeGenFunction &CGF, const CallExpr *E)
static const FieldDecl * FindFlexibleArrayMemberField(CodeGenFunction &CGF, ASTContext &Ctx, const RecordDecl *RD)
Find a struct's flexible array member.
static Value * EmitISOVolatileStore(CodeGenFunction &CGF, const CallExpr *E)
static RValue EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF, const FunctionDecl *FD)
static llvm::Value * EmitX86BitTestIntrinsic(CodeGenFunction &CGF, BitTest BT, const CallExpr *E, Value *BitBase, Value *BitPos)
static RValue EmitCheckedUnsignedMultiplySignedResult(CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info, const clang::Expr *Op2, WidthAndSignedness Op2Info, const clang::Expr *ResultArg, QualType ResultQTy, WidthAndSignedness ResultInfo)
Address CheckAtomicAlignment(CodeGenFunction &CGF, const CallExpr *E)
static Value * EmitNontemporalLoad(CodeGenFunction &CGF, const CallExpr *E)
static llvm::AtomicOrdering getBitTestAtomicOrdering(BitTest::InterlockingKind I)
static bool GetFieldOffset(ASTContext &Ctx, const RecordDecl *RD, const FieldDecl *FD, int64_t &Offset)
Calculate the offset of a struct field.
Value * MakeBinaryAtomicValue(CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E, AtomicOrdering Ordering)
Utility to insert an atomic instruction based on Intrinsic::ID and the expression node.
llvm::Value * EmitOverflowIntrinsic(CodeGenFunction &CGF, const Intrinsic::ID IntrinsicID, llvm::Value *X, llvm::Value *Y, llvm::Value *&Carry)
Emit a call to llvm.
static Value * EmitAbs(CodeGenFunction &CGF, Value *ArgValue, bool HasNSW)
static Value * EmitAtomicDecrementValue(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering Ordering=AtomicOrdering::SequentiallyConsistent)
llvm::Value * emitBuiltinWithOneOverloadedType(clang::CodeGen::CodeGenFunction &CGF, const clang::CallExpr *E, unsigned IntrinsicID, llvm::StringRef Name="")
Definition CGBuiltin.h:63
static mlir::Value emitBinaryExpMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr *e, llvm::StringRef intrinsicName, llvm::StringRef constrainedIntrinsicName)
static mlir::Value emitBinaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitUnaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static bool shouldEmitBuiltinAsIR(unsigned builtinID, const Builtin::Context &bi, const CIRGenFunction &cgf)
static RValue emitTernaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitLibraryCall(CIRGenFunction &cgf, const FunctionDecl *fd, const CallExpr *e, mlir::Operation *calleeValue)
static WidthAndSignedness getIntegerWidthAndSignedness(const clang::ASTContext &astContext, const clang::QualType type)
static struct WidthAndSignedness EncompassingIntegerType(ArrayRef< struct WidthAndSignedness > types)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
static StringRef getTriple(const Command &Job)
SanitizerHandler
static QualType getPointeeType(const MemRegion *R)
__DEVICE__ float modf(float __x, float *__iptr)
__DEVICE__ double nan(const char *)
APSInt & getInt()
Definition APValue.h:511
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType VoidPtrTy
IdentifierTable & Idents
Definition ASTContext.h:846
Builtin::Context & BuiltinInfo
Definition ASTContext.h:848
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
llvm::ArrayRef< BitInterval > getPaddingIntervals(QualType Ty) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:965
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
unsigned getTargetAddressSpace(LangAS AS) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
QualType getElementType() const
Definition TypeBase.h:3812
static std::unique_ptr< AtomicScopeModel > create(AtomicScopeModelKind K)
Create an atomic scope model by AtomicScopeModelKind.
Definition SyncScope.h:299
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
bool shouldGenerateFPMathIntrinsic(unsigned BuiltinID, llvm::Triple Trip, std::optional< bool > ErrnoOverwritten, bool MathErrnoEnabled, bool HasOptNoneAttr, bool IsOptimizationEnabled) const
Determine whether we can generate LLVM intrinsics for the given builtin ID, based on whether it has s...
Definition Builtins.cpp:242
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
bool hasStoredFPFeatures() const
Definition Expr.h:3146
SourceLocation getBeginLoc() const
Definition Expr.h:3321
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
Expr * getCallee()
Definition Expr.h:3134
FPOptionsOverride getFPFeatures() const
Definition Expr.h:3286
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
arg_range arguments()
Definition Expr.h:3239
CastKind getCastKind() const
Definition Expr.h:3764
Expr * getSubExpr()
Definition Expr.h:3770
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition CGBuilder.h:153
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:302
llvm::AtomicRMWInst * CreateAtomicRMW(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Ordering, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Definition CGBuilder.h:190
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:430
llvm::AtomicCmpXchgInst * CreateAtomicCmpXchg(Address Addr, llvm::Value *Cmp, llvm::Value *New, llvm::AtomicOrdering SuccessOrdering, llvm::AtomicOrdering FailureOrdering, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Definition CGBuilder.h:179
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:138
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition CGBuilder.h:356
All available information about a concrete callee.
Definition CGCall.h:66
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:140
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
CGFunctionInfo - Class to encapsulate the information about a function definition.
llvm::Value * getPipeElemAlign(const Expr *PipeArg)
llvm::Value * getPipeElemSize(const Expr *PipeArg)
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:277
void add(RValue rvalue, QualType type)
Definition CGCall.h:305
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2743
RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E)
llvm::Value * EmitAVRBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition AVR.cpp:22
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID, bool EnsureInsertPoint=true)
Emit a call to trap or debugtrap.
Definition CGExpr.cpp:4625
RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID)
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
llvm::Value * EmitScalarOrConstFoldImmArg(unsigned ICEArguments, unsigned Idx, const CallExpr *E)
SanitizerSet SanOpts
Sanitizers enabled for this function.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Definition CGExpr.cpp:1220
llvm::Type * ConvertType(QualType T)
void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
Add KeyInstruction and an optional Backup instruction to a new atom group (See ApplyAtomGroup for mor...
BuiltinCheckKind
Specifies which type of sanitizer check to apply when handling a particular builtin.
llvm::Value * EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition SystemZ.cpp:86
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5512
llvm::Value * EmitSEHAbnormalTermination()
RValue emitStdcFirstBit(const CallExpr *E, llvm::Intrinsic::ID IntID, bool InvertArg)
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition CGObjC.cpp:2347
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
llvm::Value * EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart)
Emits a call to an LLVM variable-argument intrinsic, either llvm.va_start or llvm....
RValue emitStdcBitWidthMinus(const CallExpr *E, llvm::Intrinsic::ID IntID, bool IsPop)
llvm::Value * EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition AMDGPU.cpp:558
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4060
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:7281
RValue emitBuiltinOSLogFormat(const CallExpr &E)
Emit IR for __builtin_os_log_format.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::Function * generateBuiltinOSLogHelperFunction(const analyze_os_log::OSLogBufferLayout &Layout, CharUnits BufferAlignment)
const LangOptions & getLangOpts() const
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
llvm::Value * EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
Definition RISCV.cpp:1079
llvm::Value * EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind)
Emits an argument for a call to a builtin.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:3950
void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, AbstractCallee AC, unsigned ParmNum)
Create a check for a function parameter that may potentially be declared as non-null.
Definition CGCall.cpp:4963
const TargetInfo & getTarget() const
RValue emitRotate(const CallExpr *E, bool IsRotateRight)
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location, const AnnotateAttr *Attr)
Emit an annotation call (intrinsic).
llvm::Value * EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue, llvm::Triple::ArchType Arch)
Definition ARM.cpp:2100
CGCallee EmitCallee(const Expr *E)
Definition CGExpr.cpp:6620
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:260
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
llvm::Value * EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition ARM.cpp:7171
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:241
llvm::Value * EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition PPC.cpp:205
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4208
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1364
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1342
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2263
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5668
const TargetCodeGenInfo & getTargetHooks() const
RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp)
Emit IR for __builtin_align_up/__builtin_align_down.
void EmitLifetimeEnd(llvm::Value *Addr)
Definition CGDecl.cpp:1376
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:233
llvm::Value * EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
llvm::FenceInst * emitAtomicFence(llvm::AtomicOrdering Order, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Emit a fence instruction, applying relevant target-specific metadata when applicable.
llvm::Value * EmitDirectXBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition DirectX.cpp:22
llvm::Value * EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E, llvm::Triple::ArchType Arch)
Definition ARM.cpp:4415
llvm::Value * EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E)
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4662
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2359
llvm::Value * EmitSPIRVBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition SPIR.cpp:22
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
Address EmitVAListRef(const Expr *E)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition CGExpr.cpp:1634
RValue EmitBuiltinIsAligned(const CallExpr *E)
Emit IR for __builtin_is_aligned.
RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, const CallExpr *TheCallExpr, bool IsDelete)
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition Hexagon.cpp:77
Address EmitZOSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_zos_va_list; this is always the address of the expression,...
CodeGenTypes & getTypes() const
RValue emitStdcCountIntrinsic(const CallExpr *E, llvm::Intrinsic::ID IntID, bool InvertArg, bool IsPop=false)
llvm::Value * EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition X86.cpp:784
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1617
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:197
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4547
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2297
llvm::Value * EmitCheckedArgForAssume(const Expr *E)
Emits an argument for a call to a __builtin_assume.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Definition CGExpr.cpp:1273
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
llvm::Value * EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition NVPTX.cpp:446
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition CGExpr.cpp:4535
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1733
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
EmitTargetBuiltinExpr - Emit the given builtin call.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
llvm::Value * EmitHLSLBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
void EmitARCIntrinsicUse(ArrayRef< llvm::Value * > values)
Given a number of pointers, inform the optimizer that they're being intrinsically used up until this ...
Definition CGObjC.cpp:2186
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:651
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::Constant * getBuiltinLibFunction(const FunctionDecl *FD, unsigned BuiltinID)
Given a builtin id for a function like "__builtin_fabsf", return a Function* for "fabsf".
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
const llvm::Triple & getTriple() const
ASTContext & getContext() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:2051
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition CGValue.h:373
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
static RValue getIgnored()
Definition CGValue.h:94
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
An abstract representation of an aligned address.
Definition Address.h:42
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:384
virtual bool supportsLibCall() const
supportsLibCall - Query to whether or not target supports all lib calls.
Definition TargetInfo.h:109
virtual llvm::Value * encodeReturnAddress(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const
Performs the code-generation required to convert the address of an instruction into a return address ...
Definition TargetInfo.h:207
virtual llvm::Value * decodeReturnAddress(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const
Performs the code-generation required to convert a return address as stored by the system into the ac...
Definition TargetInfo.h:197
virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const
Determines the DWARF register number for the stack pointer, for exception-handling purposes.
Definition TargetInfo.h:179
virtual llvm::Value * testFPKind(llvm::Value *V, unsigned BuiltinID, CGBuilderTy &Builder, CodeGenModule &CGM) const
Performs a target specific test of a floating point value for things like IsNaN, Infinity,...
Definition TargetInfo.h:216
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4465
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3498
DynamicCountPointerKind getKind() const
Definition TypeBase.h:3528
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:463
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool hasAttr() const
Definition DeclBase.h:585
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Definition Expr.h:113
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3150
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
bool isPRValue() const
Definition Expr.h:286
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3722
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4104
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:232
Represents difference between two FPOptions values.
LangOptions::FPExceptionModeKind getExceptionMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4922
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5385
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5669
@ FPE_Ignore
Assume that floating-point exceptions are masked.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:318
PipeType - OpenCL20.
Definition TypeBase.h:8247
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8502
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8544
bool requiresBuiltinLaunder(const ASTContext &Context) const
Returns true if this type requires laundering by checking if it is a dynamic class type,...
Definition Type.cpp:5649
Represents a struct/union/class.
Definition Decl.h:4460
field_range fields() const
Definition Decl.h:4663
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isUnion() const
Definition Decl.h:4063
Exposes information about the current target.
Definition TargetInfo.h:226
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isBigEndian() const
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
unsigned getSuitableAlign() const
Return the alignment that is the largest alignment ever used for any scalar/SIMD data type on the tar...
Definition TargetInfo.h:741
virtual std::string_view getClobbers() const =0
Returns a string of target-specific clobbers, in LLVM format.
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8675
bool isVoidType() const
Definition TypeBase.h:9027
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isArrayType() const
Definition TypeBase.h:8754
bool isCountAttributedType() const
Definition Type.cpp:778
bool isPointerType() const
Definition TypeBase.h:8655
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9071
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:1984
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2340
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2559
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9254
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a GCC generic vector type.
Definition TypeBase.h:4253
QualType getElementType() const
Definition TypeBase.h:4267
SmallVector< OSLogBufferItem, 4 > Items
Definition OSLog.h:113
unsigned char getNumArgsByte() const
Definition OSLog.h:148
unsigned char getSummaryByte() const
Definition OSLog.h:139
Defines the clang::TargetInfo interface.
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
llvm::Constant * initializationPatternFor(CodeGenModule &, llvm::Type *)
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
constexpr XRayInstrMask Typed
Definition XRayInstr.h:42
constexpr XRayInstrMask Custom
Definition XRayInstr.h:41
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:501
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const Expr * findStructFieldAccess(const Expr *E, const Expr **OutArrayIndex=nullptr, QualType *OutArrayElementTy=nullptr)
Walk E through parens, implicit casts, unary &/*, array subscripts and comma operators to find the he...
Definition Expr.cpp:5794
@ Success
Annotation was successful.
Definition Parser.h:65
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:43
llvm::StringRef getAsString(SyncScope S)
Definition SyncScope.h:63
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1775
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition Sanitizers.h:195
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
#define sinh(__x)
Definition tgmath.h:373
#define asin(__x)
Definition tgmath.h:112
#define scalbln(__x, __y)
Definition tgmath.h:1182
#define sqrt(__x)
Definition tgmath.h:520
#define acos(__x)
Definition tgmath.h:83
#define fmin(__x, __y)
Definition tgmath.h:780
#define exp(__x)
Definition tgmath.h:431
#define ilogb(__x)
Definition tgmath.h:851
#define copysign(__x, __y)
Definition tgmath.h:618
#define erf(__x)
Definition tgmath.h:636
#define atanh(__x)
Definition tgmath.h:228
#define remquo(__x, __y, __z)
Definition tgmath.h:1111
#define nextafter(__x, __y)
Definition tgmath.h:1055
#define frexp(__x, __y)
Definition tgmath.h:816
#define asinh(__x)
Definition tgmath.h:199
#define erfc(__x)
Definition tgmath.h:653
#define atan2(__x, __y)
Definition tgmath.h:566
#define nexttoward(__x, __y)
Definition tgmath.h:1073
#define hypot(__x, __y)
Definition tgmath.h:833
#define exp2(__x)
Definition tgmath.h:670
#define sin(__x)
Definition tgmath.h:286
#define cbrt(__x)
Definition tgmath.h:584
#define log2(__x)
Definition tgmath.h:970
#define llround(__x)
Definition tgmath.h:919
#define cosh(__x)
Definition tgmath.h:344
#define trunc(__x)
Definition tgmath.h:1216
#define fmax(__x, __y)
Definition tgmath.h:762
#define ldexp(__x, __y)
Definition tgmath.h:868
#define acosh(__x)
Definition tgmath.h:170
#define tgamma(__x)
Definition tgmath.h:1199
#define scalbn(__x, __y)
Definition tgmath.h:1165
#define round(__x)
Definition tgmath.h:1148
#define fmod(__x, __y)
Definition tgmath.h:798
#define llrint(__x)
Definition tgmath.h:902
#define tan(__x)
Definition tgmath.h:315
#define cos(__x)
Definition tgmath.h:257
#define log10(__x)
Definition tgmath.h:936
#define fabs(__x)
Definition tgmath.h:549
#define pow(__x, __y)
Definition tgmath.h:490
#define log1p(__x)
Definition tgmath.h:953
#define rint(__x)
Definition tgmath.h:1131
#define expm1(__x)
Definition tgmath.h:687
#define remainder(__x, __y)
Definition tgmath.h:1090
#define fdim(__x, __y)
Definition tgmath.h:704
#define lgamma(__x)
Definition tgmath.h:885
#define tanh(__x)
Definition tgmath.h:402
#define lrint(__x)
Definition tgmath.h:1004
#define atan(__x)
Definition tgmath.h:141
#define floor(__x)
Definition tgmath.h:722
#define ceil(__x)
Definition tgmath.h:601
#define log(__x)
Definition tgmath.h:460
#define logb(__x)
Definition tgmath.h:987
#define nearbyint(__x)
Definition tgmath.h:1038
#define lround(__x)
Definition tgmath.h:1021
#define fma(__x, __y, __z)
Definition tgmath.h:742