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