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