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