Bug Summary

File:build/source/clang/lib/CodeGen/CGBuiltin.cpp
Warning:line 12655, column 22
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CGBuiltin.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/CodeGen -I /build/source/clang/lib/CodeGen -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/CodeGen/CGBuiltin.cpp
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 "ABIInfo.h"
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CGObjCRuntime.h"
17#include "CGOpenCLRuntime.h"
18#include "CGRecordLayout.h"
19#include "CodeGenFunction.h"
20#include "CodeGenModule.h"
21#include "ConstantEmitter.h"
22#include "PatternInit.h"
23#include "TargetInfo.h"
24#include "clang/AST/ASTContext.h"
25#include "clang/AST/Attr.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/OSLog.h"
28#include "clang/Basic/TargetBuiltins.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/CodeGen/CGFunctionInfo.h"
31#include "clang/Frontend/FrontendDiagnostic.h"
32#include "llvm/ADT/APFloat.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/StringExtras.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/IntrinsicsAArch64.h"
41#include "llvm/IR/IntrinsicsAMDGPU.h"
42#include "llvm/IR/IntrinsicsARM.h"
43#include "llvm/IR/IntrinsicsBPF.h"
44#include "llvm/IR/IntrinsicsHexagon.h"
45#include "llvm/IR/IntrinsicsLoongArch.h"
46#include "llvm/IR/IntrinsicsNVPTX.h"
47#include "llvm/IR/IntrinsicsPowerPC.h"
48#include "llvm/IR/IntrinsicsR600.h"
49#include "llvm/IR/IntrinsicsRISCV.h"
50#include "llvm/IR/IntrinsicsS390.h"
51#include "llvm/IR/IntrinsicsVE.h"
52#include "llvm/IR/IntrinsicsWebAssembly.h"
53#include "llvm/IR/IntrinsicsX86.h"
54#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/MatrixBuilder.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/ScopedPrinter.h"
58#include "llvm/TargetParser/AArch64TargetParser.h"
59#include "llvm/TargetParser/X86TargetParser.h"
60#include <optional>
61#include <sstream>
62
63using namespace clang;
64using namespace CodeGen;
65using namespace llvm;
66
67static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
68 Align AlignmentInBytes) {
69 ConstantInt *Byte;
70 switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
71 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
72 // Nothing to initialize.
73 return;
74 case LangOptions::TrivialAutoVarInitKind::Zero:
75 Byte = CGF.Builder.getInt8(0x00);
76 break;
77 case LangOptions::TrivialAutoVarInitKind::Pattern: {
78 llvm::Type *Int8 = llvm::IntegerType::getInt8Ty(CGF.CGM.getLLVMContext());
79 Byte = llvm::dyn_cast<llvm::ConstantInt>(
80 initializationPatternFor(CGF.CGM, Int8));
81 break;
82 }
83 }
84 if (CGF.CGM.stopAutoInit())
85 return;
86 auto *I = CGF.Builder.CreateMemSet(AI, Byte, Size, AlignmentInBytes);
87 I->addAnnotationMetadata("auto-init");
88}
89
90/// getBuiltinLibFunction - Given a builtin id for a function like
91/// "__builtin_fabsf", return a Function* for "fabsf".
92llvm::Constant *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
93 unsigned BuiltinID) {
94 assert(Context.BuiltinInfo.isLibFunction(BuiltinID))(static_cast <bool> (Context.BuiltinInfo.isLibFunction(
BuiltinID)) ? void (0) : __assert_fail ("Context.BuiltinInfo.isLibFunction(BuiltinID)"
, "clang/lib/CodeGen/CGBuiltin.cpp", 94, __extension__ __PRETTY_FUNCTION__
))
;
95
96 // Get the name, skip over the __builtin_ prefix (if necessary).
97 StringRef Name;
98 GlobalDecl D(FD);
99
100 // TODO: This list should be expanded or refactored after all GCC-compatible
101 // std libcall builtins are implemented.
102 static SmallDenseMap<unsigned, StringRef, 8> F128Builtins{
103 {Builtin::BI__builtin_printf, "__printfieee128"},
104 {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128"},
105 {Builtin::BI__builtin_vsprintf, "__vsprintfieee128"},
106 {Builtin::BI__builtin_sprintf, "__sprintfieee128"},
107 {Builtin::BI__builtin_snprintf, "__snprintfieee128"},
108 {Builtin::BI__builtin_fprintf, "__fprintfieee128"},
109 {Builtin::BI__builtin_nexttowardf128, "__nexttowardieee128"},
110 };
111
112 // The AIX library functions frexpl, ldexpl, and modfl are for 128-bit
113 // IBM 'long double' (i.e. __ibm128). Map to the 'double' versions
114 // if it is 64-bit 'long double' mode.
115 static SmallDenseMap<unsigned, StringRef, 4> AIXLongDouble64Builtins{
116 {Builtin::BI__builtin_frexpl, "frexp"},
117 {Builtin::BI__builtin_ldexpl, "ldexp"},
118 {Builtin::BI__builtin_modfl, "modf"},
119 };
120
121 // If the builtin has been declared explicitly with an assembler label,
122 // use the mangled name. This differs from the plain label on platforms
123 // that prefix labels.
124 if (FD->hasAttr<AsmLabelAttr>())
125 Name = getMangledName(D);
126 else {
127 // TODO: This mutation should also be applied to other targets other than
128 // PPC, after backend supports IEEE 128-bit style libcalls.
129 if (getTriple().isPPC64() &&
130 &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() &&
131 F128Builtins.find(BuiltinID) != F128Builtins.end())
132 Name = F128Builtins[BuiltinID];
133 else if (getTriple().isOSAIX() &&
134 &getTarget().getLongDoubleFormat() ==
135 &llvm::APFloat::IEEEdouble() &&
136 AIXLongDouble64Builtins.find(BuiltinID) !=
137 AIXLongDouble64Builtins.end())
138 Name = AIXLongDouble64Builtins[BuiltinID];
139 else
140 Name = Context.BuiltinInfo.getName(BuiltinID).substr(10);
141 }
142
143 llvm::FunctionType *Ty =
144 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
145
146 return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
147}
148
149/// Emit the conversions required to turn the given value into an
150/// integer of the given size.
151static Value *EmitToInt(CodeGenFunction &CGF, llvm::Value *V,
152 QualType T, llvm::IntegerType *IntType) {
153 V = CGF.EmitToMemory(V, T);
154
155 if (V->getType()->isPointerTy())
156 return CGF.Builder.CreatePtrToInt(V, IntType);
157
158 assert(V->getType() == IntType)(static_cast <bool> (V->getType() == IntType) ? void
(0) : __assert_fail ("V->getType() == IntType", "clang/lib/CodeGen/CGBuiltin.cpp"
, 158, __extension__ __PRETTY_FUNCTION__))
;
159 return V;
160}
161
162static Value *EmitFromInt(CodeGenFunction &CGF, llvm::Value *V,
163 QualType T, llvm::Type *ResultType) {
164 V = CGF.EmitFromMemory(V, T);
165
166 if (ResultType->isPointerTy())
167 return CGF.Builder.CreateIntToPtr(V, ResultType);
168
169 assert(V->getType() == ResultType)(static_cast <bool> (V->getType() == ResultType) ? void
(0) : __assert_fail ("V->getType() == ResultType", "clang/lib/CodeGen/CGBuiltin.cpp"
, 169, __extension__ __PRETTY_FUNCTION__))
;
170 return V;
171}
172
173static llvm::Value *CheckAtomicAlignment(CodeGenFunction &CGF,
174 const CallExpr *E) {
175 ASTContext &Ctx = CGF.getContext();
176 Address Ptr = CGF.EmitPointerWithAlignment(E->getArg(0));
177 unsigned Bytes = Ptr.getElementType()->isPointerTy()
178 ? Ctx.getTypeSizeInChars(Ctx.VoidPtrTy).getQuantity()
179 : Ptr.getElementType()->getScalarSizeInBits() / 8;
180 unsigned Align = Ptr.getAlignment().getQuantity();
181 if (Align % Bytes != 0) {
182 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
183 Diags.Report(E->getBeginLoc(), diag::warn_sync_op_misaligned);
184 }
185 return Ptr.getPointer();
186}
187
188/// Utility to insert an atomic instruction based on Intrinsic::ID
189/// and the expression node.
190static Value *MakeBinaryAtomicValue(
191 CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
192 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
193
194 QualType T = E->getType();
195 assert(E->getArg(0)->getType()->isPointerType())(static_cast <bool> (E->getArg(0)->getType()->
isPointerType()) ? void (0) : __assert_fail ("E->getArg(0)->getType()->isPointerType()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 195, __extension__ __PRETTY_FUNCTION__
))
;
196 assert(CGF.getContext().hasSameUnqualifiedType(T,(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(T, E->getArg(0)->getType()->getPointeeType())) ? void
(0) : __assert_fail ("CGF.getContext().hasSameUnqualifiedType(T, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 197, __extension__ __PRETTY_FUNCTION__
))
197 E->getArg(0)->getType()->getPointeeType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(T, E->getArg(0)->getType()->getPointeeType())) ? void
(0) : __assert_fail ("CGF.getContext().hasSameUnqualifiedType(T, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 197, __extension__ __PRETTY_FUNCTION__
))
;
198 assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(T, E->getArg(1)->getType())) ? void (0) : __assert_fail
("CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 198, __extension__ __PRETTY_FUNCTION__
))
;
199
200 llvm::Value *DestPtr = CheckAtomicAlignment(CGF, E);
201 unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
202
203 llvm::IntegerType *IntType =
204 llvm::IntegerType::get(CGF.getLLVMContext(),
205 CGF.getContext().getTypeSize(T));
206 llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
207
208 llvm::Value *Args[2];
209 Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
210 Args[1] = CGF.EmitScalarExpr(E->getArg(1));
211 llvm::Type *ValueType = Args[1]->getType();
212 Args[1] = EmitToInt(CGF, Args[1], T, IntType);
213
214 llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
215 Kind, Args[0], Args[1], Ordering);
216 return EmitFromInt(CGF, Result, T, ValueType);
217}
218
219static Value *EmitNontemporalStore(CodeGenFunction &CGF, const CallExpr *E) {
220 Value *Val = CGF.EmitScalarExpr(E->getArg(0));
221 Value *Address = CGF.EmitScalarExpr(E->getArg(1));
222
223 // Convert the type of the pointer to a pointer to the stored type.
224 Val = CGF.EmitToMemory(Val, E->getArg(0)->getType());
225 unsigned SrcAddrSpace = Address->getType()->getPointerAddressSpace();
226 Value *BC = CGF.Builder.CreateBitCast(
227 Address, llvm::PointerType::get(Val->getType(), SrcAddrSpace), "cast");
228 LValue LV = CGF.MakeNaturalAlignAddrLValue(BC, E->getArg(0)->getType());
229 LV.setNontemporal(true);
230 CGF.EmitStoreOfScalar(Val, LV, false);
231 return nullptr;
232}
233
234static Value *EmitNontemporalLoad(CodeGenFunction &CGF, const CallExpr *E) {
235 Value *Address = CGF.EmitScalarExpr(E->getArg(0));
236
237 LValue LV = CGF.MakeNaturalAlignAddrLValue(Address, E->getType());
238 LV.setNontemporal(true);
239 return CGF.EmitLoadOfScalar(LV, E->getExprLoc());
240}
241
242static RValue EmitBinaryAtomic(CodeGenFunction &CGF,
243 llvm::AtomicRMWInst::BinOp Kind,
244 const CallExpr *E) {
245 return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E));
246}
247
248/// Utility to insert an atomic instruction based Intrinsic::ID and
249/// the expression node, where the return value is the result of the
250/// operation.
251static RValue EmitBinaryAtomicPost(CodeGenFunction &CGF,
252 llvm::AtomicRMWInst::BinOp Kind,
253 const CallExpr *E,
254 Instruction::BinaryOps Op,
255 bool Invert = false) {
256 QualType T = E->getType();
257 assert(E->getArg(0)->getType()->isPointerType())(static_cast <bool> (E->getArg(0)->getType()->
isPointerType()) ? void (0) : __assert_fail ("E->getArg(0)->getType()->isPointerType()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 257, __extension__ __PRETTY_FUNCTION__
))
;
258 assert(CGF.getContext().hasSameUnqualifiedType(T,(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(T, E->getArg(0)->getType()->getPointeeType())) ? void
(0) : __assert_fail ("CGF.getContext().hasSameUnqualifiedType(T, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 259, __extension__ __PRETTY_FUNCTION__
))
259 E->getArg(0)->getType()->getPointeeType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(T, E->getArg(0)->getType()->getPointeeType())) ? void
(0) : __assert_fail ("CGF.getContext().hasSameUnqualifiedType(T, E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 259, __extension__ __PRETTY_FUNCTION__
))
;
260 assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(T, E->getArg(1)->getType())) ? void (0) : __assert_fail
("CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 260, __extension__ __PRETTY_FUNCTION__
))
;
261
262 llvm::Value *DestPtr = CheckAtomicAlignment(CGF, E);
263 unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
264
265 llvm::IntegerType *IntType =
266 llvm::IntegerType::get(CGF.getLLVMContext(),
267 CGF.getContext().getTypeSize(T));
268 llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
269
270 llvm::Value *Args[2];
271 Args[1] = CGF.EmitScalarExpr(E->getArg(1));
272 llvm::Type *ValueType = Args[1]->getType();
273 Args[1] = EmitToInt(CGF, Args[1], T, IntType);
274 Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
275
276 llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
277 Kind, Args[0], Args[1], llvm::AtomicOrdering::SequentiallyConsistent);
278 Result = CGF.Builder.CreateBinOp(Op, Result, Args[1]);
279 if (Invert)
280 Result =
281 CGF.Builder.CreateBinOp(llvm::Instruction::Xor, Result,
282 llvm::ConstantInt::getAllOnesValue(IntType));
283 Result = EmitFromInt(CGF, Result, T, ValueType);
284 return RValue::get(Result);
285}
286
287/// Utility to insert an atomic cmpxchg instruction.
288///
289/// @param CGF The current codegen function.
290/// @param E Builtin call expression to convert to cmpxchg.
291/// arg0 - address to operate on
292/// arg1 - value to compare with
293/// arg2 - new value
294/// @param ReturnBool Specifies whether to return success flag of
295/// cmpxchg result or the old value.
296///
297/// @returns result of cmpxchg, according to ReturnBool
298///
299/// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics
300/// invoke the function EmitAtomicCmpXchgForMSIntrin.
301static Value *MakeAtomicCmpXchgValue(CodeGenFunction &CGF, const CallExpr *E,
302 bool ReturnBool) {
303 QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType();
304 llvm::Value *DestPtr = CheckAtomicAlignment(CGF, E);
305 unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
306
307 llvm::IntegerType *IntType = llvm::IntegerType::get(
308 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
309 llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
310
311 Value *Args[3];
312 Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
313 Args[1] = CGF.EmitScalarExpr(E->getArg(1));
314 llvm::Type *ValueType = Args[1]->getType();
315 Args[1] = EmitToInt(CGF, Args[1], T, IntType);
316 Args[2] = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType);
317
318 Value *Pair = CGF.Builder.CreateAtomicCmpXchg(
319 Args[0], Args[1], Args[2], llvm::AtomicOrdering::SequentiallyConsistent,
320 llvm::AtomicOrdering::SequentiallyConsistent);
321 if (ReturnBool)
322 // Extract boolean success flag and zext it to int.
323 return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1),
324 CGF.ConvertType(E->getType()));
325 else
326 // Extract old value and emit it using the same type as compare value.
327 return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T,
328 ValueType);
329}
330
331/// This function should be invoked to emit atomic cmpxchg for Microsoft's
332/// _InterlockedCompareExchange* intrinsics which have the following signature:
333/// T _InterlockedCompareExchange(T volatile *Destination,
334/// T Exchange,
335/// T Comparand);
336///
337/// Whereas the llvm 'cmpxchg' instruction has the following syntax:
338/// cmpxchg *Destination, Comparand, Exchange.
339/// So we need to swap Comparand and Exchange when invoking
340/// CreateAtomicCmpXchg. That is the reason we could not use the above utility
341/// function MakeAtomicCmpXchgValue since it expects the arguments to be
342/// already swapped.
343
344static
345Value *EmitAtomicCmpXchgForMSIntrin(CodeGenFunction &CGF, const CallExpr *E,
346 AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) {
347 assert(E->getArg(0)->getType()->isPointerType())(static_cast <bool> (E->getArg(0)->getType()->
isPointerType()) ? void (0) : __assert_fail ("E->getArg(0)->getType()->isPointerType()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 347, __extension__ __PRETTY_FUNCTION__
))
;
348 assert(CGF.getContext().hasSameUnqualifiedType((static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
( E->getType(), E->getArg(0)->getType()->getPointeeType
())) ? void (0) : __assert_fail ("CGF.getContext().hasSameUnqualifiedType( E->getType(), E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 349, __extension__ __PRETTY_FUNCTION__
))
349 E->getType(), E->getArg(0)->getType()->getPointeeType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
( E->getType(), E->getArg(0)->getType()->getPointeeType
())) ? void (0) : __assert_fail ("CGF.getContext().hasSameUnqualifiedType( E->getType(), E->getArg(0)->getType()->getPointeeType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 349, __extension__ __PRETTY_FUNCTION__
))
;
350 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(E->getType(), E->getArg(1)->getType())) ? void (0) :
__assert_fail ("CGF.getContext().hasSameUnqualifiedType(E->getType(), E->getArg(1)->getType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 351, __extension__ __PRETTY_FUNCTION__
))
351 E->getArg(1)->getType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(E->getType(), E->getArg(1)->getType())) ? void (0) :
__assert_fail ("CGF.getContext().hasSameUnqualifiedType(E->getType(), E->getArg(1)->getType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 351, __extension__ __PRETTY_FUNCTION__
))
;
352 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(E->getType(), E->getArg(2)->getType())) ? void (0) :
__assert_fail ("CGF.getContext().hasSameUnqualifiedType(E->getType(), E->getArg(2)->getType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 353, __extension__ __PRETTY_FUNCTION__
))
353 E->getArg(2)->getType()))(static_cast <bool> (CGF.getContext().hasSameUnqualifiedType
(E->getType(), E->getArg(2)->getType())) ? void (0) :
__assert_fail ("CGF.getContext().hasSameUnqualifiedType(E->getType(), E->getArg(2)->getType())"
, "clang/lib/CodeGen/CGBuiltin.cpp", 353, __extension__ __PRETTY_FUNCTION__
))
;
354
355 auto *Destination = CGF.EmitScalarExpr(E->getArg(0));
356 auto *Comparand = CGF.EmitScalarExpr(E->getArg(2));
357 auto *Exchange = CGF.EmitScalarExpr(E->getArg(1));
358
359 // For Release ordering, the failure ordering should be Monotonic.
360 auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ?
361 AtomicOrdering::Monotonic :
362 SuccessOrdering;
363
364 // The atomic instruction is marked volatile for consistency with MSVC. This
365 // blocks the few atomics optimizations that LLVM has. If we want to optimize
366 // _Interlocked* operations in the future, we will have to remove the volatile
367 // marker.
368 auto *Result = CGF.Builder.CreateAtomicCmpXchg(
369 Destination, Comparand, Exchange,
370 SuccessOrdering, FailureOrdering);
371 Result->setVolatile(true);
372 return CGF.Builder.CreateExtractValue(Result, 0);
373}
374
375// 64-bit Microsoft platforms support 128 bit cmpxchg operations. They are
376// prototyped like this:
377//
378// unsigned char _InterlockedCompareExchange128...(
379// __int64 volatile * _Destination,
380// __int64 _ExchangeHigh,
381// __int64 _ExchangeLow,
382// __int64 * _ComparandResult);
383static Value *EmitAtomicCmpXchg128ForMSIntrin(CodeGenFunction &CGF,
384 const CallExpr *E,
385 AtomicOrdering SuccessOrdering) {
386 assert(E->getNumArgs() == 4)(static_cast <bool> (E->getNumArgs() == 4) ? void (0
) : __assert_fail ("E->getNumArgs() == 4", "clang/lib/CodeGen/CGBuiltin.cpp"
, 386, __extension__ __PRETTY_FUNCTION__))
;
387 llvm::Value *Destination = CGF.EmitScalarExpr(E->getArg(0));
388 llvm::Value *ExchangeHigh = CGF.EmitScalarExpr(E->getArg(1));
389 llvm::Value *ExchangeLow = CGF.EmitScalarExpr(E->getArg(2));
390 llvm::Value *ComparandPtr = CGF.EmitScalarExpr(E->getArg(3));
391
392 assert(Destination->getType()->isPointerTy())(static_cast <bool> (Destination->getType()->isPointerTy
()) ? void (0) : __assert_fail ("Destination->getType()->isPointerTy()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 392, __extension__ __PRETTY_FUNCTION__
))
;
393 assert(!ExchangeHigh->getType()->isPointerTy())(static_cast <bool> (!ExchangeHigh->getType()->isPointerTy
()) ? void (0) : __assert_fail ("!ExchangeHigh->getType()->isPointerTy()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 393, __extension__ __PRETTY_FUNCTION__
))
;
394 assert(!ExchangeLow->getType()->isPointerTy())(static_cast <bool> (!ExchangeLow->getType()->isPointerTy
()) ? void (0) : __assert_fail ("!ExchangeLow->getType()->isPointerTy()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 394, __extension__ __PRETTY_FUNCTION__
))
;
395 assert(ComparandPtr->getType()->isPointerTy())(static_cast <bool> (ComparandPtr->getType()->isPointerTy
()) ? void (0) : __assert_fail ("ComparandPtr->getType()->isPointerTy()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 395, __extension__ __PRETTY_FUNCTION__
))
;
396
397 // For Release ordering, the failure ordering should be Monotonic.
398 auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release
399 ? AtomicOrdering::Monotonic
400 : SuccessOrdering;
401
402 // Convert to i128 pointers and values.
403 llvm::Type *Int128Ty = llvm::IntegerType::get(CGF.getLLVMContext(), 128);
404 llvm::Type *Int128PtrTy = Int128Ty->getPointerTo();
405 Destination = CGF.Builder.CreateBitCast(Destination, Int128PtrTy);
406 Address ComparandResult(CGF.Builder.CreateBitCast(ComparandPtr, Int128PtrTy),
407 Int128Ty, CGF.getContext().toCharUnitsFromBits(128));
408
409 // (((i128)hi) << 64) | ((i128)lo)
410 ExchangeHigh = CGF.Builder.CreateZExt(ExchangeHigh, Int128Ty);
411 ExchangeLow = CGF.Builder.CreateZExt(ExchangeLow, Int128Ty);
412 ExchangeHigh =
413 CGF.Builder.CreateShl(ExchangeHigh, llvm::ConstantInt::get(Int128Ty, 64));
414 llvm::Value *Exchange = CGF.Builder.CreateOr(ExchangeHigh, ExchangeLow);
415
416 // Load the comparand for the instruction.
417 llvm::Value *Comparand = CGF.Builder.CreateLoad(ComparandResult);
418
419 auto *CXI = CGF.Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
420 SuccessOrdering, FailureOrdering);
421
422 // The atomic instruction is marked volatile for consistency with MSVC. This
423 // blocks the few atomics optimizations that LLVM has. If we want to optimize
424 // _Interlocked* operations in the future, we will have to remove the volatile
425 // marker.
426 CXI->setVolatile(true);
427
428 // Store the result as an outparameter.
429 CGF.Builder.CreateStore(CGF.Builder.CreateExtractValue(CXI, 0),
430 ComparandResult);
431
432 // Get the success boolean and zero extend it to i8.
433 Value *Success = CGF.Builder.CreateExtractValue(CXI, 1);
434 return CGF.Builder.CreateZExt(Success, CGF.Int8Ty);
435}
436
437static Value *EmitAtomicIncrementValue(CodeGenFunction &CGF, const CallExpr *E,
438 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
439 assert(E->getArg(0)->getType()->isPointerType())(static_cast <bool> (E->getArg(0)->getType()->
isPointerType()) ? void (0) : __assert_fail ("E->getArg(0)->getType()->isPointerType()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 439, __extension__ __PRETTY_FUNCTION__
))
;
440
441 auto *IntTy = CGF.ConvertType(E->getType());
442 auto *Result = CGF.Builder.CreateAtomicRMW(
443 AtomicRMWInst::Add,
444 CGF.EmitScalarExpr(E->getArg(0)),
445 ConstantInt::get(IntTy, 1),
446 Ordering);
447 return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1));
448}
449
450static Value *EmitAtomicDecrementValue(CodeGenFunction &CGF, const CallExpr *E,
451 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
452 assert(E->getArg(0)->getType()->isPointerType())(static_cast <bool> (E->getArg(0)->getType()->
isPointerType()) ? void (0) : __assert_fail ("E->getArg(0)->getType()->isPointerType()"
, "clang/lib/CodeGen/CGBuiltin.cpp", 452, __extension__ __PRETTY_FUNCTION__
))
;
453
454 auto *IntTy = CGF.ConvertType(E->getType());
455 auto *Result = CGF.Builder.CreateAtomicRMW(
456 AtomicRMWInst::Sub,
457 CGF.EmitScalarExpr(E->getArg(0)),
458 ConstantInt::get(IntTy, 1),
459 Ordering);
460 return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1));
461}
462
463// Build a plain volatile load.
464static Value *EmitISOVolatileLoad(CodeGenFunction &CGF, const CallExpr *E) {
465 Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
466 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
467 CharUnits LoadSize = CGF.getContext().getTypeSizeInChars(ElTy);
468 llvm::Type *ITy =
469 llvm::IntegerType::get(CGF.getLLVMContext(), LoadSize.getQuantity() * 8);
470 Ptr = CGF.Builder.CreateBitCast(Ptr, ITy->getPointerTo());
471 llvm::LoadInst *Load = CGF.Builder.CreateAlignedLoad(ITy, Ptr, LoadSize);
472 Load->setVolatile(true);
473 return Load;
474}
475
476// Build a plain volatile store.
477static Value *EmitISOVolatileStore(CodeGenFunction &CGF, const CallExpr *E) {
478 Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
479 Value *Value = CGF.EmitScalarExpr(E->getArg(1));
480 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
481 CharUnits StoreSize = CGF.getContext().getTypeSizeInChars(ElTy);
482 llvm::Type *ITy =
483 llvm::IntegerType::get(CGF.getLLVMContext(), StoreSize.getQuantity() * 8);
484 Ptr = CGF.Builder.CreateBitCast(Ptr, ITy->getPointerTo());
485 llvm::StoreInst *Store =
486 CGF.Builder.CreateAlignedStore(Value, Ptr, StoreSize);
487 Store->setVolatile(true);
488 return Store;
489}
490
491// Emit a simple mangled intrinsic that has 1 argument and a return type
492// matching the argument type. Depending on mode, this may be a constrained
493// floating-point intrinsic.
494static Value *emitUnaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
495 const CallExpr *E, unsigned IntrinsicID,
496 unsigned ConstrainedIntrinsicID) {
497 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
498
499 if (CGF.Builder.getIsFPConstrained()) {
500 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
501 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
502 return CGF.Builder.CreateConstrainedFPCall(F, { Src0 });
503 } else {
504 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
505 return CGF.Builder.CreateCall(F, Src0);
506 }
507}
508
509// Emit an intrinsic that has 2 operands of the same type as its result.
510// Depending on mode, this may be a constrained floating-point intrinsic.
511static Value *emitBinaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
512 const CallExpr *E, unsigned IntrinsicID,
513 unsigned ConstrainedIntrinsicID) {
514 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
515 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
516
517 if (CGF.Builder.getIsFPConstrained()) {
518 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
519 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
520 return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1 });
521 } else {
522 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
523 return CGF.Builder.CreateCall(F, { Src0, Src1 });
524 }
525}
526
527// Emit an intrinsic that has 3 operands of the same type as its result.
528// Depending on mode, this may be a constrained floating-point intrinsic.
529static Value *emitTernaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
530 const CallExpr *E, unsigned IntrinsicID,
531 unsigned ConstrainedIntrinsicID) {
532 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
533 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
534 llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
535
536 if (CGF.Builder.getIsFPConstrained()) {
537 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
538 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
539 return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1, Src2 });
540 } else {
541 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
542 return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
543 }
544}
545
546// Emit an intrinsic where all operands are of the same type as the result.
547// Depending on mode, this may be a constrained floating-point intrinsic.
548static Value *emitCallMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
549 unsigned IntrinsicID,
550 unsigned ConstrainedIntrinsicID,
551 llvm::Type *Ty,
552 ArrayRef<Value *> Args) {
553 Function *F;
554 if (CGF.Builder.getIsFPConstrained())
555 F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Ty);
556 else
557 F = CGF.CGM.getIntrinsic(IntrinsicID, Ty);
558
559 if (CGF.Builder.getIsFPConstrained())
560 return CGF.Builder.CreateConstrainedFPCall(F, Args);
561 else
562 return CGF.Builder.CreateCall(F, Args);
563}
564
565// Emit a simple mangled intrinsic that has 1 argument and a return type
566// matching the argument type.
567static Value *emitUnaryBuiltin(CodeGenFunction &CGF, const CallExpr *E,
568 unsigned IntrinsicID,
569 llvm::StringRef Name = "") {
570 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
571
572 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
573 return CGF.Builder.CreateCall(F, Src0, Name);
574}
575
576// Emit an intrinsic that has 2 operands of the same type as its result.
577static Value *emitBinaryBuiltin(CodeGenFunction &CGF,
578 const CallExpr *E,
579 unsigned IntrinsicID) {
580 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
581 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
582
583 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
584 return CGF.Builder.CreateCall(F, { Src0, Src1 });
585}
586
587// Emit an intrinsic that has 3 operands of the same type as its result.
588static Value *emitTernaryBuiltin(CodeGenFunction &CGF,
589 const CallExpr *E,
590 unsigned IntrinsicID) {
591 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
592 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
593 llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
594
595 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
596 return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
597}
598
599// Emit an intrinsic that has 1 float or double operand, and 1 integer.
600static Value *emitFPIntBuiltin(CodeGenFunction &CGF,
601 const CallExpr *E,
602 unsigned IntrinsicID) {
603 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
604 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
605
606 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
607 return CGF.Builder.CreateCall(F, {Src0, Src1});
608}
609
610// Emit an intrinsic that has overloaded integer result and fp operand.
611static Value *
612emitMaybeConstrainedFPToIntRoundBuiltin(CodeGenFunction &CGF, const CallExpr *E,
613 unsigned IntrinsicID,
614 unsigned ConstrainedIntrinsicID) {
615 llvm::Type *ResultType = CGF.ConvertType(E->getType());
616 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
617
618 if (CGF.Builder.getIsFPConstrained()) {
619 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
620 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
621 {ResultType, Src0->getType()});
622 return CGF.Builder.CreateConstrainedFPCall(F, {Src0});
623 } else {
624 Function *F =
625 CGF.CGM.getIntrinsic(IntrinsicID, {ResultType, Src0->getType()});
626 return CGF.Builder.CreateCall(F, Src0);
627 }
628}
629
630/// EmitFAbs - Emit a call to @llvm.fabs().
631static Value *EmitFAbs(CodeGenFunction &CGF, Value *V) {
632 Function *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType());
633 llvm::CallInst *Call = CGF.Builder.CreateCall(F, V);
634 Call->setDoesNotAccessMemory();
635 return Call;
636}
637
638/// Emit the computation of the sign bit for a floating point value. Returns
639/// the i1 sign bit value.
640static Value *EmitSignBit(CodeGenFunction &CGF, Value *V) {
641 LLVMContext &C = CGF.CGM.getLLVMContext();
642
643 llvm::Type *Ty = V->getType();
644 int Width = Ty->getPrimitiveSizeInBits();
645 llvm::Type *IntTy = llvm::IntegerType::get(C, Width);
646 V = CGF.Builder.CreateBitCast(V, IntTy);
647 if (Ty->isPPC_FP128Ty()) {
648 // We want the sign bit of the higher-order double. The bitcast we just
649 // did works as if the double-double was stored to memory and then
650 // read as an i128. The "store" will put the higher-order double in the
651 // lower address in both little- and big-Endian modes, but the "load"
652 // will treat those bits as a different part of the i128: the low bits in
653 // little-Endian, the high bits in big-Endian. Therefore, on big-Endian
654 // we need to shift the high bits down to the low before truncating.
655 Width >>= 1;
656 if (CGF.getTarget().isBigEndian()) {
657 Value *ShiftCst = llvm::ConstantInt::get(IntTy, Width);
658 V = CGF.Builder.CreateLShr(V, ShiftCst);
659 }
660 // We are truncating value in order to extract the higher-order
661 // double, which we will be using to extract the sign from.
662 IntTy = llvm::IntegerType::get(C, Width);
663 V = CGF.Builder.CreateTrunc(V, IntTy);
664 }
665 Value *Zero = llvm::Constant::getNullValue(IntTy);
666 return CGF.Builder.CreateICmpSLT(V, Zero);
667}
668
669static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD,
670 const CallExpr *E, llvm::Constant *calleeValue) {
671 CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
672 return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
673}
674
675/// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
676/// depending on IntrinsicID.
677///
678/// \arg CGF The current codegen function.
679/// \arg IntrinsicID The ID for the Intrinsic we wish to generate.
680/// \arg X The first argument to the llvm.*.with.overflow.*.
681/// \arg Y The second argument to the llvm.*.with.overflow.*.
682/// \arg Carry The carry returned by the llvm.*.with.overflow.*.
683/// \returns The result (i.e. sum/product) returned by the intrinsic.
684static llvm::Value *EmitOverflowIntrinsic(CodeGenFunction &CGF,
685 const llvm::Intrinsic::ID IntrinsicID,
686 llvm::Value *X, llvm::Value *Y,
687 llvm::Value *&Carry) {
688 // Make sure we have integers of the same width.
689 assert(X->getType() == Y->getType() &&(static_cast <bool> (X->getType() == Y->getType()
&& "Arguments must be the same type. (Did you forget to make sure both "
"arguments have the same integer width?)") ? void (0) : __assert_fail
("X->getType() == Y->getType() && \"Arguments must be the same type. (Did you forget to make sure both \" \"arguments have the same integer width?)\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 691, __extension__ __PRETTY_FUNCTION__
))
690 "Arguments must be the same type. (Did you forget to make sure both "(static_cast <bool> (X->getType() == Y->getType()
&& "Arguments must be the same type. (Did you forget to make sure both "
"arguments have the same integer width?)") ? void (0) : __assert_fail
("X->getType() == Y->getType() && \"Arguments must be the same type. (Did you forget to make sure both \" \"arguments have the same integer width?)\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 691, __extension__ __PRETTY_FUNCTION__
))
691 "arguments have the same integer width?)")(static_cast <bool> (X->getType() == Y->getType()
&& "Arguments must be the same type. (Did you forget to make sure both "
"arguments have the same integer width?)") ? void (0) : __assert_fail
("X->getType() == Y->getType() && \"Arguments must be the same type. (Did you forget to make sure both \" \"arguments have the same integer width?)\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 691, __extension__ __PRETTY_FUNCTION__
))
;
692
693 Function *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType());
694 llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, {X, Y});
695 Carry = CGF.Builder.CreateExtractValue(Tmp, 1);
696 return CGF.Builder.CreateExtractValue(Tmp, 0);
697}
698
699static Value *emitRangedBuiltin(CodeGenFunction &CGF,
700 unsigned IntrinsicID,
701 int low, int high) {
702 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
703 llvm::MDNode *RNode = MDHelper.createRange(APInt(32, low), APInt(32, high));
704 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {});
705 llvm::Instruction *Call = CGF.Builder.CreateCall(F);
706 Call->setMetadata(llvm::LLVMContext::MD_range, RNode);
707 Call->setMetadata(llvm::LLVMContext::MD_noundef,
708 llvm::MDNode::get(CGF.getLLVMContext(), std::nullopt));
709 return Call;
710}
711
712namespace {
713 struct WidthAndSignedness {
714 unsigned Width;
715 bool Signed;
716 };
717}
718
719static WidthAndSignedness
720getIntegerWidthAndSignedness(const clang::ASTContext &context,
721 const clang::QualType Type) {
722 assert(Type->isIntegerType() && "Given type is not an integer.")(static_cast <bool> (Type->isIntegerType() &&
"Given type is not an integer.") ? void (0) : __assert_fail (
"Type->isIntegerType() && \"Given type is not an integer.\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 722, __extension__ __PRETTY_FUNCTION__
))
;
723 unsigned Width = Type->isBooleanType() ? 1
724 : Type->isBitIntType() ? context.getIntWidth(Type)
725 : context.getTypeInfo(Type).Width;
726 bool Signed = Type->isSignedIntegerType();
727 return {Width, Signed};
728}
729
730// Given one or more integer types, this function produces an integer type that
731// encompasses them: any value in one of the given types could be expressed in
732// the encompassing type.
733static struct WidthAndSignedness
734EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) {
735 assert(Types.size() > 0 && "Empty list of types.")(static_cast <bool> (Types.size() > 0 && "Empty list of types."
) ? void (0) : __assert_fail ("Types.size() > 0 && \"Empty list of types.\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 735, __extension__ __PRETTY_FUNCTION__
))
;
736
737 // If any of the given types is signed, we must return a signed type.
738 bool Signed = false;
739 for (const auto &Type : Types) {
740 Signed |= Type.Signed;
741 }
742
743 // The encompassing type must have a width greater than or equal to the width
744 // of the specified types. Additionally, if the encompassing type is signed,
745 // its width must be strictly greater than the width of any unsigned types
746 // given.
747 unsigned Width = 0;
748 for (const auto &Type : Types) {
749 unsigned MinWidth = Type.Width + (Signed && !Type.Signed);
750 if (Width < MinWidth) {
751 Width = MinWidth;
752 }
753 }
754
755 return {Width, Signed};
756}
757
758Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) {
759 llvm::Type *DestType = Int8PtrTy;
760 if (ArgValue->getType() != DestType)
761 ArgValue =
762 Builder.CreateBitCast(ArgValue, DestType, ArgValue->getName().data());
763
764 Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend;
765 return Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue);
766}
767
768/// Checks if using the result of __builtin_object_size(p, @p From) in place of
769/// __builtin_object_size(p, @p To) is correct
770static bool areBOSTypesCompatible(int From, int To) {
771 // Note: Our __builtin_object_size implementation currently treats Type=0 and
772 // Type=2 identically. Encoding this implementation detail here may make
773 // improving __builtin_object_size difficult in the future, so it's omitted.
774 return From == To || (From == 0 && To == 1) || (From == 3 && To == 2);
775}
776
777static llvm::Value *
778getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) {
779 return ConstantInt::get(ResType, (Type & 2) ? 0 : -1, /*isSigned=*/true);
780}
781
782llvm::Value *
783CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
784 llvm::IntegerType *ResType,
785 llvm::Value *EmittedE,
786 bool IsDynamic) {
787 uint64_t ObjectSize;
788 if (!E->tryEvaluateObjectSize(ObjectSize, getContext(), Type))
789 return emitBuiltinObjectSize(E, Type, ResType, EmittedE, IsDynamic);
790 return ConstantInt::get(ResType, ObjectSize, /*isSigned=*/true);
791}
792
793/// Returns a Value corresponding to the size of the given expression.
794/// This Value may be either of the following:
795/// - A llvm::Argument (if E is a param with the pass_object_size attribute on
796/// it)
797/// - A call to the @llvm.objectsize intrinsic
798///
799/// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
800/// and we wouldn't otherwise try to reference a pass_object_size parameter,
801/// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
802llvm::Value *
803CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
804 llvm::IntegerType *ResType,
805 llvm::Value *EmittedE, bool IsDynamic) {
806 // We need to reference an argument if the pointer is a parameter with the
807 // pass_object_size attribute.
808 if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
809 auto *Param = dyn_cast<ParmVarDecl>(D->getDecl());
810 auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>();
811 if (Param != nullptr && PS != nullptr &&
812 areBOSTypesCompatible(PS->getType(), Type)) {
813 auto Iter = SizeArguments.find(Param);
814 assert(Iter != SizeArguments.end())(static_cast <bool> (Iter != SizeArguments.end()) ? void
(0) : __assert_fail ("Iter != SizeArguments.end()", "clang/lib/CodeGen/CGBuiltin.cpp"
, 814, __extension__ __PRETTY_FUNCTION__))
;
815
816 const ImplicitParamDecl *D = Iter->second;
817 auto DIter = LocalDeclMap.find(D);
818 assert(DIter != LocalDeclMap.end())(static_cast <bool> (DIter != LocalDeclMap.end()) ? void
(0) : __assert_fail ("DIter != LocalDeclMap.end()", "clang/lib/CodeGen/CGBuiltin.cpp"
, 818, __extension__ __PRETTY_FUNCTION__))
;
819
820 return EmitLoadOfScalar(DIter->second, /*Volatile=*/false,
821 getContext().getSizeType(), E->getBeginLoc());
822 }
823 }
824
825 // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't
826 // evaluate E for side-effects. In either case, we shouldn't lower to
827 // @llvm.objectsize.
828 if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext())))
829 return getDefaultBuiltinObjectSizeResult(Type, ResType);
830
831 Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
832 assert(Ptr->getType()->isPointerTy() &&(static_cast <bool> (Ptr->getType()->isPointerTy(
) && "Non-pointer passed to __builtin_object_size?") ?
void (0) : __assert_fail ("Ptr->getType()->isPointerTy() && \"Non-pointer passed to __builtin_object_size?\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 833, __extension__ __PRETTY_FUNCTION__
))
833 "Non-pointer passed to __builtin_object_size?")(static_cast <bool> (Ptr->getType()->isPointerTy(
) && "Non-pointer passed to __builtin_object_size?") ?
void (0) : __assert_fail ("Ptr->getType()->isPointerTy() && \"Non-pointer passed to __builtin_object_size?\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 833, __extension__ __PRETTY_FUNCTION__
))
;
834
835 Function *F =
836 CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()});
837
838 // LLVM only supports 0 and 2, make sure that we pass along that as a boolean.
839 Value *Min = Builder.getInt1((Type & 2) != 0);
840 // For GCC compatibility, __builtin_object_size treat NULL as unknown size.
841 Value *NullIsUnknown = Builder.getTrue();
842 Value *Dynamic = Builder.getInt1(IsDynamic);
843 return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic});
844}
845
846namespace {
847/// A struct to generically describe a bit test intrinsic.
848struct BitTest {
849 enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set };
850 enum InterlockingKind : uint8_t {
851 Unlocked,
852 Sequential,
853 Acquire,
854 Release,
855 NoFence
856 };
857
858 ActionKind Action;
859 InterlockingKind Interlocking;
860 bool Is64Bit;
861
862 static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
863};
864} // namespace
865
866BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
867 switch (BuiltinID) {
868 // Main portable variants.
869 case Builtin::BI_bittest:
870 return {TestOnly, Unlocked, false};
871 case Builtin::BI_bittestandcomplement:
872 return {Complement, Unlocked, false};
873 case Builtin::BI_bittestandreset:
874 return {Reset, Unlocked, false};
875 case Builtin::BI_bittestandset:
876 return {Set, Unlocked, false};
877 case Builtin::BI_interlockedbittestandreset:
878 return {Reset, Sequential, false};
879 case Builtin::BI_interlockedbittestandset:
880 return {Set, Sequential, false};
881
882 // X86-specific 64-bit variants.
883 case Builtin::BI_bittest64:
884 return {TestOnly, Unlocked, true};
885 case Builtin::BI_bittestandcomplement64:
886 return {Complement, Unlocked, true};
887 case Builtin::BI_bittestandreset64:
888 return {Reset, Unlocked, true};
889 case Builtin::BI_bittestandset64:
890 return {Set, Unlocked, true};
891 case Builtin::BI_interlockedbittestandreset64:
892 return {Reset, Sequential, true};
893 case Builtin::BI_interlockedbittestandset64:
894 return {Set, Sequential, true};
895
896 // ARM/AArch64-specific ordering variants.
897 case Builtin::BI_interlockedbittestandset_acq:
898 return {Set, Acquire, false};
899 case Builtin::BI_interlockedbittestandset_rel:
900 return {Set, Release, false};
901 case Builtin::BI_interlockedbittestandset_nf:
902 return {Set, NoFence, false};
903 case Builtin::BI_interlockedbittestandreset_acq:
904 return {Reset, Acquire, false};
905 case Builtin::BI_interlockedbittestandreset_rel:
906 return {Reset, Release, false};
907 case Builtin::BI_interlockedbittestandreset_nf:
908 return {Reset, NoFence, false};
909 }
910 llvm_unreachable("expected only bittest intrinsics")::llvm::llvm_unreachable_internal("expected only bittest intrinsics"
, "clang/lib/CodeGen/CGBuiltin.cpp", 910)
;
911}
912
913static char bitActionToX86BTCode(BitTest::ActionKind A) {
914 switch (A) {
915 case BitTest::TestOnly: return '\0';
916 case BitTest::Complement: return 'c';
917 case BitTest::Reset: return 'r';
918 case BitTest::Set: return 's';
919 }
920 llvm_unreachable("invalid action")::llvm::llvm_unreachable_internal("invalid action", "clang/lib/CodeGen/CGBuiltin.cpp"
, 920)
;
921}
922
923static llvm::Value *EmitX86BitTestIntrinsic(CodeGenFunction &CGF,
924 BitTest BT,
925 const CallExpr *E, Value *BitBase,
926 Value *BitPos) {
927 char Action = bitActionToX86BTCode(BT.Action);
928 char SizeSuffix = BT.Is64Bit ? 'q' : 'l';
929
930 // Build the assembly.
931 SmallString<64> Asm;
932 raw_svector_ostream AsmOS(Asm);
933 if (BT.Interlocking != BitTest::Unlocked)
934 AsmOS << "lock ";
935 AsmOS << "bt";
936 if (Action)
937 AsmOS << Action;
938 AsmOS << SizeSuffix << " $2, ($1)";
939
940 // Build the constraints. FIXME: We should support immediates when possible.
941 std::string Constraints = "={@ccc},r,r,~{cc},~{memory}";
942 std::string_view MachineClobbers = CGF.getTarget().getClobbers();
943 if (!MachineClobbers.empty()) {
944 Constraints += ',';
945 Constraints += MachineClobbers;
946 }
947 llvm::IntegerType *IntType = llvm::IntegerType::get(
948 CGF.getLLVMContext(),
949 CGF.getContext().getTypeSize(E->getArg(1)->getType()));
950 llvm::Type *IntPtrType = IntType->getPointerTo();
951 llvm::FunctionType *FTy =
952 llvm::FunctionType::get(CGF.Int8Ty, {IntPtrType, IntType}, false);
953
954 llvm::InlineAsm *IA =
955 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
956 return CGF.Builder.CreateCall(IA, {BitBase, BitPos});
957}
958
959static llvm::AtomicOrdering
960getBitTestAtomicOrdering(BitTest::InterlockingKind I) {
961 switch (I) {
962 case BitTest::Unlocked: return llvm::AtomicOrdering::NotAtomic;
963 case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent;
964 case BitTest::Acquire: return llvm::AtomicOrdering::Acquire;
965 case BitTest::Release: return llvm::AtomicOrdering::Release;
966 case BitTest::NoFence: return llvm::AtomicOrdering::Monotonic;
967 }
968 llvm_unreachable("invalid interlocking")::llvm::llvm_unreachable_internal("invalid interlocking", "clang/lib/CodeGen/CGBuiltin.cpp"
, 968)
;
969}
970
971/// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of
972/// bits and a bit position and read and optionally modify the bit at that
973/// position. The position index can be arbitrarily large, i.e. it can be larger
974/// than 31 or 63, so we need an indexed load in the general case.
975static llvm::Value *EmitBitTestIntrinsic(CodeGenFunction &CGF,
976 unsigned BuiltinID,
977 const CallExpr *E) {
978 Value *BitBase = CGF.EmitScalarExpr(E->getArg(0));
979 Value *BitPos = CGF.EmitScalarExpr(E->getArg(1));
980
981 BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID);
982
983 // X86 has special BT, BTC, BTR, and BTS instructions that handle the array
984 // indexing operation internally. Use them if possible.
985 if (CGF.getTarget().getTriple().isX86())
986 return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos);
987
988 // Otherwise, use generic code to load one byte and test the bit. Use all but
989 // the bottom three bits as the array index, and the bottom three bits to form
990 // a mask.
991 // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0;
992 Value *ByteIndex = CGF.Builder.CreateAShr(
993 BitPos, llvm::ConstantInt::get(BitPos->getType(), 3), "bittest.byteidx");
994 Value *BitBaseI8 = CGF.Builder.CreatePointerCast(BitBase, CGF.Int8PtrTy);
995 Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBaseI8,
996 ByteIndex, "bittest.byteaddr"),
997 CGF.Int8Ty, CharUnits::One());
998 Value *PosLow =
999 CGF.Builder.CreateAnd(CGF.Builder.CreateTrunc(BitPos, CGF.Int8Ty),
1000 llvm::ConstantInt::get(CGF.Int8Ty, 0x7));
1001
1002 // The updating instructions will need a mask.
1003 Value *Mask = nullptr;
1004 if (BT.Action != BitTest::TestOnly) {
1005 Mask = CGF.Builder.CreateShl(llvm::ConstantInt::get(CGF.Int8Ty, 1), PosLow,
1006 "bittest.mask");
1007 }
1008
1009 // Check the action and ordering of the interlocked intrinsics.
1010 llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(BT.Interlocking);
1011
1012 Value *OldByte = nullptr;
1013 if (Ordering != llvm::AtomicOrdering::NotAtomic) {
1014 // Emit a combined atomicrmw load/store operation for the interlocked
1015 // intrinsics.
1016 llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or;
1017 if (BT.Action == BitTest::Reset) {
1018 Mask = CGF.Builder.CreateNot(Mask);
1019 RMWOp = llvm::AtomicRMWInst::And;
1020 }
1021 OldByte = CGF.Builder.CreateAtomicRMW(RMWOp, ByteAddr.getPointer(), Mask,
1022 Ordering);
1023 } else {
1024 // Emit a plain load for the non-interlocked intrinsics.
1025 OldByte = CGF.Builder.CreateLoad(ByteAddr, "bittest.byte");
1026 Value *NewByte = nullptr;
1027 switch (BT.Action) {
1028 case BitTest::TestOnly:
1029 // Don't store anything.
1030 break;
1031 case BitTest::Complement:
1032 NewByte = CGF.Builder.CreateXor(OldByte, Mask);
1033 break;
1034 case BitTest::Reset:
1035 NewByte = CGF.Builder.CreateAnd(OldByte, CGF.Builder.CreateNot(Mask));
1036 break;
1037 case BitTest::Set:
1038 NewByte = CGF.Builder.CreateOr(OldByte, Mask);
1039 break;
1040 }
1041 if (NewByte)
1042 CGF.Builder.CreateStore(NewByte, ByteAddr);
1043 }
1044
1045 // However we loaded the old byte, either by plain load or atomicrmw, shift
1046 // the bit into the low position and mask it to 0 or 1.
1047 Value *ShiftedByte = CGF.Builder.CreateLShr(OldByte, PosLow, "bittest.shr");
1048 return CGF.Builder.CreateAnd(
1049 ShiftedByte, llvm::ConstantInt::get(CGF.Int8Ty, 1), "bittest.res");
1050}
1051
1052static llvm::Value *emitPPCLoadReserveIntrinsic(CodeGenFunction &CGF,
1053 unsigned BuiltinID,
1054 const CallExpr *E) {
1055 Value *Addr = CGF.EmitScalarExpr(E->getArg(0));
1056
1057 SmallString<64> Asm;
1058 raw_svector_ostream AsmOS(Asm);
1059 llvm::IntegerType *RetType = CGF.Int32Ty;
1060
1061 switch (BuiltinID) {
1062 case clang::PPC::BI__builtin_ppc_ldarx:
1063 AsmOS << "ldarx ";
1064 RetType = CGF.Int64Ty;
1065 break;
1066 case clang::PPC::BI__builtin_ppc_lwarx:
1067 AsmOS << "lwarx ";
1068 RetType = CGF.Int32Ty;
1069 break;
1070 case clang::PPC::BI__builtin_ppc_lharx:
1071 AsmOS << "lharx ";
1072 RetType = CGF.Int16Ty;
1073 break;
1074 case clang::PPC::BI__builtin_ppc_lbarx:
1075 AsmOS << "lbarx ";
1076 RetType = CGF.Int8Ty;
1077 break;
1078 default:
1079 llvm_unreachable("Expected only PowerPC load reserve intrinsics")::llvm::llvm_unreachable_internal("Expected only PowerPC load reserve intrinsics"
, "clang/lib/CodeGen/CGBuiltin.cpp", 1079)
;
1080 }
1081
1082 AsmOS << "$0, ${1:y}";
1083
1084 std::string Constraints = "=r,*Z,~{memory}";
1085 std::string_view MachineClobbers = CGF.getTarget().getClobbers();
1086 if (!MachineClobbers.empty()) {
1087 Constraints += ',';
1088 Constraints += MachineClobbers;
1089 }
1090
1091 llvm::Type *IntPtrType = RetType->getPointerTo();
1092 llvm::FunctionType *FTy =
1093 llvm::FunctionType::get(RetType, {IntPtrType}, false);
1094
1095 llvm::InlineAsm *IA =
1096 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1097 llvm::CallInst *CI = CGF.Builder.CreateCall(IA, {Addr});
1098 CI->addParamAttr(
1099 0, Attribute::get(CGF.getLLVMContext(), Attribute::ElementType, RetType));
1100 return CI;
1101}
1102
1103namespace {
1104enum class MSVCSetJmpKind {
1105 _setjmpex,
1106 _setjmp3,
1107 _setjmp
1108};
1109}
1110
1111/// MSVC handles setjmp a bit differently on different platforms. On every
1112/// architecture except 32-bit x86, the frame address is passed. On x86, extra
1113/// parameters can be passed as variadic arguments, but we always pass none.
1114static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind,
1115 const CallExpr *E) {
1116 llvm::Value *Arg1 = nullptr;
1117 llvm::Type *Arg1Ty = nullptr;
1118 StringRef Name;
1119 bool IsVarArg = false;
1120 if (SJKind == MSVCSetJmpKind::_setjmp3) {
1121 Name = "_setjmp3";
1122 Arg1Ty = CGF.Int32Ty;
1123 Arg1 = llvm::ConstantInt::get(CGF.IntTy, 0);
1124 IsVarArg = true;
1125 } else {
1126 Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex";
1127 Arg1Ty = CGF.Int8PtrTy;
1128 if (CGF.getTarget().getTriple().getArch() == llvm::Triple::aarch64) {
1129 Arg1 = CGF.Builder.CreateCall(
1130 CGF.CGM.getIntrinsic(Intrinsic::sponentry, CGF.AllocaInt8PtrTy));
1131 } else
1132 Arg1 = CGF.Builder.CreateCall(
1133 CGF.CGM.getIntrinsic(Intrinsic::frameaddress, CGF.AllocaInt8PtrTy),
1134 llvm::ConstantInt::get(CGF.Int32Ty, 0));
1135 }
1136
1137 // Mark the call site and declaration with ReturnsTwice.
1138 llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty};
1139 llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get(
1140 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex,
1141 llvm::Attribute::ReturnsTwice);
1142 llvm::FunctionCallee SetJmpFn = CGF.CGM.CreateRuntimeFunction(
1143 llvm::FunctionType::get(CGF.IntTy, ArgTypes, IsVarArg), Name,
1144 ReturnsTwiceAttr, /*Local=*/true);
1145
1146 llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast(
1147 CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy);
1148 llvm::Value *Args[] = {Buf, Arg1};
1149 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args);
1150 CB->setAttributes(ReturnsTwiceAttr);
1151 return RValue::get(CB);
1152}
1153
1154// Many of MSVC builtins are on x64, ARM and AArch64; to avoid repeating code,
1155// we handle them here.
1156enum class CodeGenFunction::MSVCIntrin {
1157 _BitScanForward,
1158 _BitScanReverse,
1159 _InterlockedAnd,
1160 _InterlockedDecrement,
1161 _InterlockedExchange,
1162 _InterlockedExchangeAdd,
1163 _InterlockedExchangeSub,
1164 _InterlockedIncrement,
1165 _InterlockedOr,
1166 _InterlockedXor,
1167 _InterlockedExchangeAdd_acq,
1168 _InterlockedExchangeAdd_rel,
1169 _InterlockedExchangeAdd_nf,
1170 _InterlockedExchange_acq,
1171 _InterlockedExchange_rel,
1172 _InterlockedExchange_nf,
1173 _InterlockedCompareExchange_acq,
1174 _InterlockedCompareExchange_rel,
1175 _InterlockedCompareExchange_nf,
1176 _InterlockedCompareExchange128,
1177 _InterlockedCompareExchange128_acq,
1178 _InterlockedCompareExchange128_rel,
1179 _InterlockedCompareExchange128_nf,
1180 _InterlockedOr_acq,
1181 _InterlockedOr_rel,
1182 _InterlockedOr_nf,
1183 _InterlockedXor_acq,
1184 _InterlockedXor_rel,
1185 _InterlockedXor_nf,
1186 _InterlockedAnd_acq,
1187 _InterlockedAnd_rel,
1188 _InterlockedAnd_nf,
1189 _InterlockedIncrement_acq,
1190 _InterlockedIncrement_rel,
1191 _InterlockedIncrement_nf,
1192 _InterlockedDecrement_acq,
1193 _InterlockedDecrement_rel,
1194 _InterlockedDecrement_nf,
1195 __fastfail,
1196};
1197
1198static std::optional<CodeGenFunction::MSVCIntrin>
1199translateArmToMsvcIntrin(unsigned BuiltinID) {
1200 using MSVCIntrin = CodeGenFunction::MSVCIntrin;
1201 switch (BuiltinID) {
1202 default:
1203 return std::nullopt;
1204 case clang::ARM::BI_BitScanForward:
1205 case clang::ARM::BI_BitScanForward64:
1206 return MSVCIntrin::_BitScanForward;
1207 case clang::ARM::BI_BitScanReverse:
1208 case clang::ARM::BI_BitScanReverse64:
1209 return MSVCIntrin::_BitScanReverse;
1210 case clang::ARM::BI_InterlockedAnd64:
1211 return MSVCIntrin::_InterlockedAnd;
1212 case clang::ARM::BI_InterlockedExchange64:
1213 return MSVCIntrin::_InterlockedExchange;
1214 case clang::ARM::BI_InterlockedExchangeAdd64:
1215 return MSVCIntrin::_InterlockedExchangeAdd;
1216 case clang::ARM::BI_InterlockedExchangeSub64:
1217 return MSVCIntrin::_InterlockedExchangeSub;
1218 case clang::ARM::BI_InterlockedOr64:
1219 return MSVCIntrin::_InterlockedOr;
1220 case clang::ARM::BI_InterlockedXor64:
1221 return MSVCIntrin::_InterlockedXor;
1222 case clang::ARM::BI_InterlockedDecrement64:
1223 return MSVCIntrin::_InterlockedDecrement;
1224 case clang::ARM::BI_InterlockedIncrement64:
1225 return MSVCIntrin::_InterlockedIncrement;
1226 case clang::ARM::BI_InterlockedExchangeAdd8_acq:
1227 case clang::ARM::BI_InterlockedExchangeAdd16_acq:
1228 case clang::ARM::BI_InterlockedExchangeAdd_acq:
1229 case clang::ARM::BI_InterlockedExchangeAdd64_acq:
1230 return MSVCIntrin::_InterlockedExchangeAdd_acq;
1231 case clang::ARM::BI_InterlockedExchangeAdd8_rel:
1232 case clang::ARM::BI_InterlockedExchangeAdd16_rel:
1233 case clang::ARM::BI_InterlockedExchangeAdd_rel:
1234 case clang::ARM::BI_InterlockedExchangeAdd64_rel:
1235 return MSVCIntrin::_InterlockedExchangeAdd_rel;
1236 case clang::ARM::BI_InterlockedExchangeAdd8_nf:
1237 case clang::ARM::BI_InterlockedExchangeAdd16_nf:
1238 case clang::ARM::BI_InterlockedExchangeAdd_nf:
1239 case clang::ARM::BI_InterlockedExchangeAdd64_nf:
1240 return MSVCIntrin::_InterlockedExchangeAdd_nf;
1241 case clang::ARM::BI_InterlockedExchange8_acq:
1242 case clang::ARM::BI_InterlockedExchange16_acq:
1243 case clang::ARM::BI_InterlockedExchange_acq:
1244 case clang::ARM::BI_InterlockedExchange64_acq:
1245 return MSVCIntrin::_InterlockedExchange_acq;
1246 case clang::ARM::BI_InterlockedExchange8_rel:
1247 case clang::ARM::BI_InterlockedExchange16_rel:
1248 case clang::ARM::BI_InterlockedExchange_rel:
1249 case clang::ARM::BI_InterlockedExchange64_rel:
1250 return MSVCIntrin::_InterlockedExchange_rel;
1251 case clang::ARM::BI_InterlockedExchange8_nf:
1252 case clang::ARM::BI_InterlockedExchange16_nf:
1253 case clang::ARM::BI_InterlockedExchange_nf:
1254 case clang::ARM::BI_InterlockedExchange64_nf:
1255 return MSVCIntrin::_InterlockedExchange_nf;
1256 case clang::ARM::BI_InterlockedCompareExchange8_acq:
1257 case clang::ARM::BI_InterlockedCompareExchange16_acq:
1258 case clang::ARM::BI_InterlockedCompareExchange_acq:
1259 case clang::ARM::BI_InterlockedCompareExchange64_acq:
1260 return MSVCIntrin::_InterlockedCompareExchange_acq;
1261 case clang::ARM::BI_InterlockedCompareExchange8_rel:
1262 case clang::ARM::BI_InterlockedCompareExchange16_rel:
1263 case clang::ARM::BI_InterlockedCompareExchange_rel:
1264 case clang::ARM::BI_InterlockedCompareExchange64_rel:
1265 return MSVCIntrin::_InterlockedCompareExchange_rel;
1266 case clang::ARM::BI_InterlockedCompareExchange8_nf:
1267 case clang::ARM::BI_InterlockedCompareExchange16_nf:
1268 case clang::ARM::BI_InterlockedCompareExchange_nf:
1269 case clang::ARM::BI_InterlockedCompareExchange64_nf:
1270 return MSVCIntrin::_InterlockedCompareExchange_nf;
1271 case clang::ARM::BI_InterlockedOr8_acq:
1272 case clang::ARM::BI_InterlockedOr16_acq:
1273 case clang::ARM::BI_InterlockedOr_acq:
1274 case clang::ARM::BI_InterlockedOr64_acq:
1275 return MSVCIntrin::_InterlockedOr_acq;
1276 case clang::ARM::BI_InterlockedOr8_rel:
1277 case clang::ARM::BI_InterlockedOr16_rel:
1278 case clang::ARM::BI_InterlockedOr_rel:
1279 case clang::ARM::BI_InterlockedOr64_rel:
1280 return MSVCIntrin::_InterlockedOr_rel;
1281 case clang::ARM::BI_InterlockedOr8_nf:
1282 case clang::ARM::BI_InterlockedOr16_nf:
1283 case clang::ARM::BI_InterlockedOr_nf:
1284 case clang::ARM::BI_InterlockedOr64_nf:
1285 return MSVCIntrin::_InterlockedOr_nf;
1286 case clang::ARM::BI_InterlockedXor8_acq:
1287 case clang::ARM::BI_InterlockedXor16_acq:
1288 case clang::ARM::BI_InterlockedXor_acq:
1289 case clang::ARM::BI_InterlockedXor64_acq:
1290 return MSVCIntrin::_InterlockedXor_acq;
1291 case clang::ARM::BI_InterlockedXor8_rel:
1292 case clang::ARM::BI_InterlockedXor16_rel:
1293 case clang::ARM::BI_InterlockedXor_rel:
1294 case clang::ARM::BI_InterlockedXor64_rel:
1295 return MSVCIntrin::_InterlockedXor_rel;
1296 case clang::ARM::BI_InterlockedXor8_nf:
1297 case clang::ARM::BI_InterlockedXor16_nf:
1298 case clang::ARM::BI_InterlockedXor_nf:
1299 case clang::ARM::BI_InterlockedXor64_nf:
1300 return MSVCIntrin::_InterlockedXor_nf;
1301 case clang::ARM::BI_InterlockedAnd8_acq:
1302 case clang::ARM::BI_InterlockedAnd16_acq:
1303 case clang::ARM::BI_InterlockedAnd_acq:
1304 case clang::ARM::BI_InterlockedAnd64_acq:
1305 return MSVCIntrin::_InterlockedAnd_acq;
1306 case clang::ARM::BI_InterlockedAnd8_rel:
1307 case clang::ARM::BI_InterlockedAnd16_rel:
1308 case clang::ARM::BI_InterlockedAnd_rel:
1309 case clang::ARM::BI_InterlockedAnd64_rel:
1310 return MSVCIntrin::_InterlockedAnd_rel;
1311 case clang::ARM::BI_InterlockedAnd8_nf:
1312 case clang::ARM::BI_InterlockedAnd16_nf:
1313 case clang::ARM::BI_InterlockedAnd_nf:
1314 case clang::ARM::BI_InterlockedAnd64_nf:
1315 return MSVCIntrin::_InterlockedAnd_nf;
1316 case clang::ARM::BI_InterlockedIncrement16_acq:
1317 case clang::ARM::BI_InterlockedIncrement_acq:
1318 case clang::ARM::BI_InterlockedIncrement64_acq:
1319 return MSVCIntrin::_InterlockedIncrement_acq;
1320 case clang::ARM::BI_InterlockedIncrement16_rel:
1321 case clang::ARM::BI_InterlockedIncrement_rel:
1322 case clang::ARM::BI_InterlockedIncrement64_rel:
1323 return MSVCIntrin::_InterlockedIncrement_rel;
1324 case clang::ARM::BI_InterlockedIncrement16_nf:
1325 case clang::ARM::BI_InterlockedIncrement_nf:
1326 case clang::ARM::BI_InterlockedIncrement64_nf:
1327 return MSVCIntrin::_InterlockedIncrement_nf;
1328 case clang::ARM::BI_InterlockedDecrement16_acq:
1329 case clang::ARM::BI_InterlockedDecrement_acq:
1330 case clang::ARM::BI_InterlockedDecrement64_acq:
1331 return MSVCIntrin::_InterlockedDecrement_acq;
1332 case clang::ARM::BI_InterlockedDecrement16_rel:
1333 case clang::ARM::BI_InterlockedDecrement_rel:
1334 case clang::ARM::BI_InterlockedDecrement64_rel:
1335 return MSVCIntrin::_InterlockedDecrement_rel;
1336 case clang::ARM::BI_InterlockedDecrement16_nf:
1337 case clang::ARM::BI_InterlockedDecrement_nf:
1338 case clang::ARM::BI_InterlockedDecrement64_nf:
1339 return MSVCIntrin::_InterlockedDecrement_nf;
1340 }
1341 llvm_unreachable("must return from switch")::llvm::llvm_unreachable_internal("must return from switch", "clang/lib/CodeGen/CGBuiltin.cpp"
, 1341)
;
1342}
1343
1344static std::optional<CodeGenFunction::MSVCIntrin>
1345translateAarch64ToMsvcIntrin(unsigned BuiltinID) {
1346 using MSVCIntrin = CodeGenFunction::MSVCIntrin;
1347 switch (BuiltinID) {
1348 default:
1349 return std::nullopt;
1350 case clang::AArch64::BI_BitScanForward:
1351 case clang::AArch64::BI_BitScanForward64:
1352 return MSVCIntrin::_BitScanForward;
1353 case clang::AArch64::BI_BitScanReverse:
1354 case clang::AArch64::BI_BitScanReverse64:
1355 return MSVCIntrin::_BitScanReverse;
1356 case clang::AArch64::BI_InterlockedAnd64:
1357 return MSVCIntrin::_InterlockedAnd;
1358 case clang::AArch64::BI_InterlockedExchange64:
1359 return MSVCIntrin::_InterlockedExchange;
1360 case clang::AArch64::BI_InterlockedExchangeAdd64:
1361 return MSVCIntrin::_InterlockedExchangeAdd;
1362 case clang::AArch64::BI_InterlockedExchangeSub64:
1363 return MSVCIntrin::_InterlockedExchangeSub;
1364 case clang::AArch64::BI_InterlockedOr64:
1365 return MSVCIntrin::_InterlockedOr;
1366 case clang::AArch64::BI_InterlockedXor64:
1367 return MSVCIntrin::_InterlockedXor;
1368 case clang::AArch64::BI_InterlockedDecrement64:
1369 return MSVCIntrin::_InterlockedDecrement;
1370 case clang::AArch64::BI_InterlockedIncrement64:
1371 return MSVCIntrin::_InterlockedIncrement;
1372 case clang::AArch64::BI_InterlockedExchangeAdd8_acq:
1373 case clang::AArch64::BI_InterlockedExchangeAdd16_acq:
1374 case clang::AArch64::BI_InterlockedExchangeAdd_acq:
1375 case clang::AArch64::BI_InterlockedExchangeAdd64_acq:
1376 return MSVCIntrin::_InterlockedExchangeAdd_acq;
1377 case clang::AArch64::BI_InterlockedExchangeAdd8_rel:
1378 case clang::AArch64::BI_InterlockedExchangeAdd16_rel:
1379 case clang::AArch64::BI_InterlockedExchangeAdd_rel:
1380 case clang::AArch64::BI_InterlockedExchangeAdd64_rel:
1381 return MSVCIntrin::_InterlockedExchangeAdd_rel;
1382 case clang::AArch64::BI_InterlockedExchangeAdd8_nf:
1383 case clang::AArch64::BI_InterlockedExchangeAdd16_nf:
1384 case clang::AArch64::BI_InterlockedExchangeAdd_nf:
1385 case clang::AArch64::BI_InterlockedExchangeAdd64_nf:
1386 return MSVCIntrin::_InterlockedExchangeAdd_nf;
1387 case clang::AArch64::BI_InterlockedExchange8_acq:
1388 case clang::AArch64::BI_InterlockedExchange16_acq:
1389 case clang::AArch64::BI_InterlockedExchange_acq:
1390 case clang::AArch64::BI_InterlockedExchange64_acq:
1391 return MSVCIntrin::_InterlockedExchange_acq;
1392 case clang::AArch64::BI_InterlockedExchange8_rel:
1393 case clang::AArch64::BI_InterlockedExchange16_rel:
1394 case clang::AArch64::BI_InterlockedExchange_rel:
1395 case clang::AArch64::BI_InterlockedExchange64_rel:
1396 return MSVCIntrin::_InterlockedExchange_rel;
1397 case clang::AArch64::BI_InterlockedExchange8_nf:
1398 case clang::AArch64::BI_InterlockedExchange16_nf:
1399 case clang::AArch64::BI_InterlockedExchange_nf:
1400 case clang::AArch64::BI_InterlockedExchange64_nf:
1401 return MSVCIntrin::_InterlockedExchange_nf;
1402 case clang::AArch64::BI_InterlockedCompareExchange8_acq:
1403 case clang::AArch64::BI_InterlockedCompareExchange16_acq:
1404 case clang::AArch64::BI_InterlockedCompareExchange_acq:
1405 case clang::AArch64::BI_InterlockedCompareExchange64_acq:
1406 return MSVCIntrin::_InterlockedCompareExchange_acq;
1407 case clang::AArch64::BI_InterlockedCompareExchange8_rel:
1408 case clang::AArch64::BI_InterlockedCompareExchange16_rel:
1409 case clang::AArch64::BI_InterlockedCompareExchange_rel:
1410 case clang::AArch64::BI_InterlockedCompareExchange64_rel:
1411 return MSVCIntrin::_InterlockedCompareExchange_rel;
1412 case clang::AArch64::BI_InterlockedCompareExchange8_nf:
1413 case clang::AArch64::BI_InterlockedCompareExchange16_nf:
1414 case clang::AArch64::BI_InterlockedCompareExchange_nf:
1415 case clang::AArch64::BI_InterlockedCompareExchange64_nf:
1416 return MSVCIntrin::_InterlockedCompareExchange_nf;
1417 case clang::AArch64::BI_InterlockedCompareExchange128:
1418 return MSVCIntrin::_InterlockedCompareExchange128;
1419 case clang::AArch64::BI_InterlockedCompareExchange128_acq:
1420 return MSVCIntrin::_InterlockedCompareExchange128_acq;
1421 case clang::AArch64::BI_InterlockedCompareExchange128_nf:
1422 return MSVCIntrin::_InterlockedCompareExchange128_nf;
1423 case clang::AArch64::BI_InterlockedCompareExchange128_rel:
1424 return MSVCIntrin::_InterlockedCompareExchange128_rel;
1425 case clang::AArch64::BI_InterlockedOr8_acq:
1426 case clang::AArch64::BI_InterlockedOr16_acq:
1427 case clang::AArch64::BI_InterlockedOr_acq:
1428 case clang::AArch64::BI_InterlockedOr64_acq:
1429 return MSVCIntrin::_InterlockedOr_acq;
1430 case clang::AArch64::BI_InterlockedOr8_rel:
1431 case clang::AArch64::BI_InterlockedOr16_rel:
1432 case clang::AArch64::BI_InterlockedOr_rel:
1433 case clang::AArch64::BI_InterlockedOr64_rel:
1434 return MSVCIntrin::_InterlockedOr_rel;
1435 case clang::AArch64::BI_InterlockedOr8_nf:
1436 case clang::AArch64::BI_InterlockedOr16_nf:
1437 case clang::AArch64::BI_InterlockedOr_nf:
1438 case clang::AArch64::BI_InterlockedOr64_nf:
1439 return MSVCIntrin::_InterlockedOr_nf;
1440 case clang::AArch64::BI_InterlockedXor8_acq:
1441 case clang::AArch64::BI_InterlockedXor16_acq:
1442 case clang::AArch64::BI_InterlockedXor_acq:
1443 case clang::AArch64::BI_InterlockedXor64_acq:
1444 return MSVCIntrin::_InterlockedXor_acq;
1445 case clang::AArch64::BI_InterlockedXor8_rel:
1446 case clang::AArch64::BI_InterlockedXor16_rel:
1447 case clang::AArch64::BI_InterlockedXor_rel:
1448 case clang::AArch64::BI_InterlockedXor64_rel:
1449 return MSVCIntrin::_InterlockedXor_rel;
1450 case clang::AArch64::BI_InterlockedXor8_nf:
1451 case clang::AArch64::BI_InterlockedXor16_nf:
1452 case clang::AArch64::BI_InterlockedXor_nf:
1453 case clang::AArch64::BI_InterlockedXor64_nf:
1454 return MSVCIntrin::_InterlockedXor_nf;
1455 case clang::AArch64::BI_InterlockedAnd8_acq:
1456 case clang::AArch64::BI_InterlockedAnd16_acq:
1457 case clang::AArch64::BI_InterlockedAnd_acq:
1458 case clang::AArch64::BI_InterlockedAnd64_acq:
1459 return MSVCIntrin::_InterlockedAnd_acq;
1460 case clang::AArch64::BI_InterlockedAnd8_rel:
1461 case clang::AArch64::BI_InterlockedAnd16_rel:
1462 case clang::AArch64::BI_InterlockedAnd_rel:
1463 case clang::AArch64::BI_InterlockedAnd64_rel:
1464 return MSVCIntrin::_InterlockedAnd_rel;
1465 case clang::AArch64::BI_InterlockedAnd8_nf:
1466 case clang::AArch64::BI_InterlockedAnd16_nf:
1467 case clang::AArch64::BI_InterlockedAnd_nf:
1468 case clang::AArch64::BI_InterlockedAnd64_nf:
1469 return MSVCIntrin::_InterlockedAnd_nf;
1470 case clang::AArch64::BI_InterlockedIncrement16_acq:
1471 case clang::AArch64::BI_InterlockedIncrement_acq:
1472 case clang::AArch64::BI_InterlockedIncrement64_acq:
1473 return MSVCIntrin::_InterlockedIncrement_acq;
1474 case clang::AArch64::BI_InterlockedIncrement16_rel:
1475 case clang::AArch64::BI_InterlockedIncrement_rel:
1476 case clang::AArch64::BI_InterlockedIncrement64_rel:
1477 return MSVCIntrin::_InterlockedIncrement_rel;
1478 case clang::AArch64::BI_InterlockedIncrement16_nf:
1479 case clang::AArch64::BI_InterlockedIncrement_nf:
1480 case clang::AArch64::BI_InterlockedIncrement64_nf:
1481 return MSVCIntrin::_InterlockedIncrement_nf;
1482 case clang::AArch64::BI_InterlockedDecrement16_acq:
1483 case clang::AArch64::BI_InterlockedDecrement_acq:
1484 case clang::AArch64::BI_InterlockedDecrement64_acq:
1485 return MSVCIntrin::_InterlockedDecrement_acq;
1486 case clang::AArch64::BI_InterlockedDecrement16_rel:
1487 case clang::AArch64::BI_InterlockedDecrement_rel:
1488 case clang::AArch64::BI_InterlockedDecrement64_rel:
1489 return MSVCIntrin::_InterlockedDecrement_rel;
1490 case clang::AArch64::BI_InterlockedDecrement16_nf:
1491 case clang::AArch64::BI_InterlockedDecrement_nf:
1492 case clang::AArch64::BI_InterlockedDecrement64_nf:
1493 return MSVCIntrin::_InterlockedDecrement_nf;
1494 }
1495 llvm_unreachable("must return from switch")::llvm::llvm_unreachable_internal("must return from switch", "clang/lib/CodeGen/CGBuiltin.cpp"
, 1495)
;
1496}
1497
1498static std::optional<CodeGenFunction::MSVCIntrin>
1499translateX86ToMsvcIntrin(unsigned BuiltinID) {
1500 using MSVCIntrin = CodeGenFunction::MSVCIntrin;
1501 switch (BuiltinID) {
1502 default:
1503 return std::nullopt;
1504 case clang::X86::BI_BitScanForward:
1505 case clang::X86::BI_BitScanForward64:
1506 return MSVCIntrin::_BitScanForward;
1507 case clang::X86::BI_BitScanReverse:
1508 case clang::X86::BI_BitScanReverse64:
1509 return MSVCIntrin::_BitScanReverse;
1510 case clang::X86::BI_InterlockedAnd64:
1511 return MSVCIntrin::_InterlockedAnd;
1512 case clang::X86::BI_InterlockedCompareExchange128:
1513 return MSVCIntrin::_InterlockedCompareExchange128;
1514 case clang::X86::BI_InterlockedExchange64:
1515 return MSVCIntrin::_InterlockedExchange;
1516 case clang::X86::BI_InterlockedExchangeAdd64:
1517 return MSVCIntrin::_InterlockedExchangeAdd;
1518 case clang::X86::BI_InterlockedExchangeSub64:
1519 return MSVCIntrin::_InterlockedExchangeSub;
1520 case clang::X86::BI_InterlockedOr64:
1521 return MSVCIntrin::_InterlockedOr;
1522 case clang::X86::BI_InterlockedXor64:
1523 return MSVCIntrin::_InterlockedXor;
1524 case clang::X86::BI_InterlockedDecrement64:
1525 return MSVCIntrin::_InterlockedDecrement;
1526 case clang::X86::BI_InterlockedIncrement64:
1527 return MSVCIntrin::_InterlockedIncrement;
1528 }
1529 llvm_unreachable("must return from switch")::llvm::llvm_unreachable_internal("must return from switch", "clang/lib/CodeGen/CGBuiltin.cpp"
, 1529)
;
1530}
1531
1532// Emit an MSVC intrinsic. Assumes that arguments have *not* been evaluated.
1533Value *CodeGenFunction::EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID,
1534 const CallExpr *E) {
1535 switch (BuiltinID) {
1536 case MSVCIntrin::_BitScanForward:
1537 case MSVCIntrin::_BitScanReverse: {
1538 Address IndexAddress(EmitPointerWithAlignment(E->getArg(0)));
1539 Value *ArgValue = EmitScalarExpr(E->getArg(1));
1540
1541 llvm::Type *ArgType = ArgValue->getType();
1542 llvm::Type *IndexType = IndexAddress.getElementType();
1543 llvm::Type *ResultType = ConvertType(E->getType());
1544
1545 Value *ArgZero = llvm::Constant::getNullValue(ArgType);
1546 Value *ResZero = llvm::Constant::getNullValue(ResultType);
1547 Value *ResOne = llvm::ConstantInt::get(ResultType, 1);
1548
1549 BasicBlock *Begin = Builder.GetInsertBlock();
1550 BasicBlock *End = createBasicBlock("bitscan_end", this->CurFn);
1551 Builder.SetInsertPoint(End);
1552 PHINode *Result = Builder.CreatePHI(ResultType, 2, "bitscan_result");
1553
1554 Builder.SetInsertPoint(Begin);
1555 Value *IsZero = Builder.CreateICmpEQ(ArgValue, ArgZero);
1556 BasicBlock *NotZero = createBasicBlock("bitscan_not_zero", this->CurFn);
1557 Builder.CreateCondBr(IsZero, End, NotZero);
1558 Result->addIncoming(ResZero, Begin);
1559
1560 Builder.SetInsertPoint(NotZero);
1561
1562 if (BuiltinID == MSVCIntrin::_BitScanForward) {
1563 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1564 Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1565 ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1566 Builder.CreateStore(ZeroCount, IndexAddress, false);
1567 } else {
1568 unsigned ArgWidth = cast<llvm::IntegerType>(ArgType)->getBitWidth();
1569 Value *ArgTypeLastIndex = llvm::ConstantInt::get(IndexType, ArgWidth - 1);
1570
1571 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1572 Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1573 ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1574 Value *Index = Builder.CreateNSWSub(ArgTypeLastIndex, ZeroCount);
1575 Builder.CreateStore(Index, IndexAddress, false);
1576 }
1577 Builder.CreateBr(End);
1578 Result->addIncoming(ResOne, NotZero);
1579
1580 Builder.SetInsertPoint(End);
1581 return Result;
1582 }
1583 case MSVCIntrin::_InterlockedAnd:
1584 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E);
1585 case MSVCIntrin::_InterlockedExchange:
1586 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E);
1587 case MSVCIntrin::_InterlockedExchangeAdd:
1588 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E);
1589 case MSVCIntrin::_InterlockedExchangeSub:
1590 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E);
1591 case MSVCIntrin::_InterlockedOr:
1592 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E);
1593 case MSVCIntrin::_InterlockedXor:
1594 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E);
1595 case MSVCIntrin::_InterlockedExchangeAdd_acq:
1596 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1597 AtomicOrdering::Acquire);
1598 case MSVCIntrin::_InterlockedExchangeAdd_rel:
1599 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1600 AtomicOrdering::Release);
1601 case MSVCIntrin::_InterlockedExchangeAdd_nf:
1602 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1603 AtomicOrdering::Monotonic);
1604 case MSVCIntrin::_InterlockedExchange_acq:
1605 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1606 AtomicOrdering::Acquire);
1607 case MSVCIntrin::_InterlockedExchange_rel:
1608 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1609 AtomicOrdering::Release);
1610 case MSVCIntrin::_InterlockedExchange_nf:
1611 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1612 AtomicOrdering::Monotonic);
1613 case MSVCIntrin::_InterlockedCompareExchange_acq:
1614 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire);
1615 case MSVCIntrin::_InterlockedCompareExchange_rel:
1616 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release);
1617 case MSVCIntrin::_InterlockedCompareExchange_nf:
1618 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1619 case MSVCIntrin::_InterlockedCompareExchange128:
1620 return EmitAtomicCmpXchg128ForMSIntrin(
1621 *this, E, AtomicOrdering::SequentiallyConsistent);
1622 case MSVCIntrin::_InterlockedCompareExchange128_acq:
1623 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Acquire);
1624 case MSVCIntrin::_InterlockedCompareExchange128_rel:
1625 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Release);
1626 case MSVCIntrin::_InterlockedCompareExchange128_nf:
1627 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1628 case MSVCIntrin::_InterlockedOr_acq:
1629 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1630 AtomicOrdering::Acquire);
1631 case MSVCIntrin::_InterlockedOr_rel:
1632 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1633 AtomicOrdering::Release);
1634 case MSVCIntrin::_InterlockedOr_nf:
1635 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1636 AtomicOrdering::Monotonic);
1637 case MSVCIntrin::_InterlockedXor_acq:
1638 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1639 AtomicOrdering::Acquire);
1640 case MSVCIntrin::_InterlockedXor_rel:
1641 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1642 AtomicOrdering::Release);
1643 case MSVCIntrin::_InterlockedXor_nf:
1644 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1645 AtomicOrdering::Monotonic);
1646 case MSVCIntrin::_InterlockedAnd_acq:
1647 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1648 AtomicOrdering::Acquire);
1649 case MSVCIntrin::_InterlockedAnd_rel:
1650 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1651 AtomicOrdering::Release);
1652 case MSVCIntrin::_InterlockedAnd_nf:
1653 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1654 AtomicOrdering::Monotonic);
1655 case MSVCIntrin::_InterlockedIncrement_acq:
1656 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire);
1657 case MSVCIntrin::_InterlockedIncrement_rel:
1658 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release);
1659 case MSVCIntrin::_InterlockedIncrement_nf:
1660 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic);
1661 case MSVCIntrin::_InterlockedDecrement_acq:
1662 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire);
1663 case MSVCIntrin::_InterlockedDecrement_rel:
1664 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release);
1665 case MSVCIntrin::_InterlockedDecrement_nf:
1666 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic);
1667
1668 case MSVCIntrin::_InterlockedDecrement:
1669 return EmitAtomicDecrementValue(*this, E);
1670 case MSVCIntrin::_InterlockedIncrement:
1671 return EmitAtomicIncrementValue(*this, E);
1672
1673 case MSVCIntrin::__fastfail: {
1674 // Request immediate process termination from the kernel. The instruction
1675 // sequences to do this are documented on MSDN:
1676 // https://msdn.microsoft.com/en-us/library/dn774154.aspx
1677 llvm::Triple::ArchType ISA = getTarget().getTriple().getArch();
1678 StringRef Asm, Constraints;
1679 switch (ISA) {
1680 default:
1681 ErrorUnsupported(E, "__fastfail call for this architecture");
1682 break;
1683 case llvm::Triple::x86:
1684 case llvm::Triple::x86_64:
1685 Asm = "int $$0x29";
1686 Constraints = "{cx}";
1687 break;
1688 case llvm::Triple::thumb:
1689 Asm = "udf #251";
1690 Constraints = "{r0}";
1691 break;
1692 case llvm::Triple::aarch64:
1693 Asm = "brk #0xF003";
1694 Constraints = "{w0}";
1695 }
1696 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, {Int32Ty}, false);
1697 llvm::InlineAsm *IA =
1698 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1699 llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
1700 getLLVMContext(), llvm::AttributeList::FunctionIndex,
1701 llvm::Attribute::NoReturn);
1702 llvm::CallInst *CI = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0)));
1703 CI->setAttributes(NoReturnAttr);
1704 return CI;
1705 }
1706 }
1707 llvm_unreachable("Incorrect MSVC intrinsic!")::llvm::llvm_unreachable_internal("Incorrect MSVC intrinsic!"
, "clang/lib/CodeGen/CGBuiltin.cpp", 1707)
;
1708}
1709
1710namespace {
1711// ARC cleanup for __builtin_os_log_format
1712struct CallObjCArcUse final : EHScopeStack::Cleanup {
1713 CallObjCArcUse(llvm::Value *object) : object(object) {}
1714 llvm::Value *object;
1715
1716 void Emit(CodeGenFunction &CGF, Flags flags) override {
1717 CGF.EmitARCIntrinsicUse(object);
1718 }
1719};
1720}
1721
1722Value *CodeGenFunction::EmitCheckedArgForBuiltin(const Expr *E,
1723 BuiltinCheckKind Kind) {
1724 assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero)(static_cast <bool> ((Kind == BCK_CLZPassedZero || Kind
== BCK_CTZPassedZero) && "Unsupported builtin check kind"
) ? void (0) : __assert_fail ("(Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero) && \"Unsupported builtin check kind\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1725, __extension__ __PRETTY_FUNCTION__
))
1725 && "Unsupported builtin check kind")(static_cast <bool> ((Kind == BCK_CLZPassedZero || Kind
== BCK_CTZPassedZero) && "Unsupported builtin check kind"
) ? void (0) : __assert_fail ("(Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero) && \"Unsupported builtin check kind\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1725, __extension__ __PRETTY_FUNCTION__
))
;
1726
1727 Value *ArgValue = EmitScalarExpr(E);
1728 if (!SanOpts.has(SanitizerKind::Builtin) || !getTarget().isCLZForZeroUndef())
1729 return ArgValue;
1730
1731 SanitizerScope SanScope(this);
1732 Value *Cond = Builder.CreateICmpNE(
1733 ArgValue, llvm::Constant::getNullValue(ArgValue->getType()));
1734 EmitCheck(std::make_pair(Cond, SanitizerKind::Builtin),
1735 SanitizerHandler::InvalidBuiltin,
1736 {EmitCheckSourceLocation(E->getExprLoc()),
1737 llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)},
1738 std::nullopt);
1739 return ArgValue;
1740}
1741
1742/// Get the argument type for arguments to os_log_helper.
1743static CanQualType getOSLogArgType(ASTContext &C, int Size) {
1744 QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false);
1745 return C.getCanonicalType(UnsignedTy);
1746}
1747
1748llvm::Function *CodeGenFunction::generateBuiltinOSLogHelperFunction(
1749 const analyze_os_log::OSLogBufferLayout &Layout,
1750 CharUnits BufferAlignment) {
1751 ASTContext &Ctx = getContext();
1752
1753 llvm::SmallString<64> Name;
1754 {
1755 raw_svector_ostream OS(Name);
1756 OS << "__os_log_helper";
1757 OS << "_" << BufferAlignment.getQuantity();
1758 OS << "_" << int(Layout.getSummaryByte());
1759 OS << "_" << int(Layout.getNumArgsByte());
1760 for (const auto &Item : Layout.Items)
1761 OS << "_" << int(Item.getSizeByte()) << "_"
1762 << int(Item.getDescriptorByte());
1763 }
1764
1765 if (llvm::Function *F = CGM.getModule().getFunction(Name))
1766 return F;
1767
1768 llvm::SmallVector<QualType, 4> ArgTys;
1769 FunctionArgList Args;
1770 Args.push_back(ImplicitParamDecl::Create(
1771 Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer"), Ctx.VoidPtrTy,
1772 ImplicitParamDecl::Other));
1773 ArgTys.emplace_back(Ctx.VoidPtrTy);
1774
1775 for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) {
1776 char Size = Layout.Items[I].getSizeByte();
1777 if (!Size)
1778 continue;
1779
1780 QualType ArgTy = getOSLogArgType(Ctx, Size);
1781 Args.push_back(ImplicitParamDecl::Create(
1782 Ctx, nullptr, SourceLocation(),
1783 &Ctx.Idents.get(std::string("arg") + llvm::to_string(I)), ArgTy,
1784 ImplicitParamDecl::Other));
1785 ArgTys.emplace_back(ArgTy);
1786 }
1787
1788 QualType ReturnTy = Ctx.VoidTy;
1789
1790 // The helper function has linkonce_odr linkage to enable the linker to merge
1791 // identical functions. To ensure the merging always happens, 'noinline' is
1792 // attached to the function when compiling with -Oz.
1793 const CGFunctionInfo &FI =
1794 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args);
1795 llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(FI);
1796 llvm::Function *Fn = llvm::Function::Create(
1797 FuncTy, llvm::GlobalValue::LinkOnceODRLinkage, Name, &CGM.getModule());
1798 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1799 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
1800 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1801 Fn->setDoesNotThrow();
1802
1803 // Attach 'noinline' at -Oz.
1804 if (CGM.getCodeGenOpts().OptimizeSize == 2)
1805 Fn->addFnAttr(llvm::Attribute::NoInline);
1806
1807 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1808 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, Args);
1809
1810 // Create a scope with an artificial location for the body of this function.
1811 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1812
1813 CharUnits Offset;
1814 Address BufAddr =
1815 Address(Builder.CreateLoad(GetAddrOfLocalVar(Args[0]), "buf"), Int8Ty,
1816 BufferAlignment);
1817 Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()),
1818 Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
1819 Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()),
1820 Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
1821
1822 unsigned I = 1;
1823 for (const auto &Item : Layout.Items) {
1824 Builder.CreateStore(
1825 Builder.getInt8(Item.getDescriptorByte()),
1826 Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
1827 Builder.CreateStore(
1828 Builder.getInt8(Item.getSizeByte()),
1829 Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
1830
1831 CharUnits Size = Item.size();
1832 if (!Size.getQuantity())
1833 continue;
1834
1835 Address Arg = GetAddrOfLocalVar(Args[I]);
1836 Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData");
1837 Addr =
1838 Builder.CreateElementBitCast(Addr, Arg.getElementType(), "argDataCast");
1839 Builder.CreateStore(Builder.CreateLoad(Arg), Addr);
1840 Offset += Size;
1841 ++I;
1842 }
1843
1844 FinishFunction();
1845
1846 return Fn;
1847}
1848
1849RValue CodeGenFunction::emitBuiltinOSLogFormat(const CallExpr &E) {
1850 assert(E.getNumArgs() >= 2 &&(static_cast <bool> (E.getNumArgs() >= 2 && "__builtin_os_log_format takes at least 2 arguments"
) ? void (0) : __assert_fail ("E.getNumArgs() >= 2 && \"__builtin_os_log_format takes at least 2 arguments\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1851, __extension__ __PRETTY_FUNCTION__
))
1851 "__builtin_os_log_format takes at least 2 arguments")(static_cast <bool> (E.getNumArgs() >= 2 && "__builtin_os_log_format takes at least 2 arguments"
) ? void (0) : __assert_fail ("E.getNumArgs() >= 2 && \"__builtin_os_log_format takes at least 2 arguments\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1851, __extension__ __PRETTY_FUNCTION__
))
;
1852 ASTContext &Ctx = getContext();
1853 analyze_os_log::OSLogBufferLayout Layout;
1854 analyze_os_log::computeOSLogBufferLayout(Ctx, &E, Layout);
1855 Address BufAddr = EmitPointerWithAlignment(E.getArg(0));
1856 llvm::SmallVector<llvm::Value *, 4> RetainableOperands;
1857
1858 // Ignore argument 1, the format string. It is not currently used.
1859 CallArgList Args;
1860 Args.add(RValue::get(BufAddr.getPointer()), Ctx.VoidPtrTy);
1861
1862 for (const auto &Item : Layout.Items) {
1863 int Size = Item.getSizeByte();
1864 if (!Size)
1865 continue;
1866
1867 llvm::Value *ArgVal;
1868
1869 if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) {
1870 uint64_t Val = 0;
1871 for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I)
1872 Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8;
1873 ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val));
1874 } else if (const Expr *TheExpr = Item.getExpr()) {
1875 ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false);
1876
1877 // If a temporary object that requires destruction after the full
1878 // expression is passed, push a lifetime-extended cleanup to extend its
1879 // lifetime to the end of the enclosing block scope.
1880 auto LifetimeExtendObject = [&](const Expr *E) {
1881 E = E->IgnoreParenCasts();
1882 // Extend lifetimes of objects returned by function calls and message
1883 // sends.
1884
1885 // FIXME: We should do this in other cases in which temporaries are
1886 // created including arguments of non-ARC types (e.g., C++
1887 // temporaries).
1888 if (isa<CallExpr>(E) || isa<ObjCMessageExpr>(E))
1889 return true;
1890 return false;
1891 };
1892
1893 if (TheExpr->getType()->isObjCRetainableType() &&
1894 getLangOpts().ObjCAutoRefCount && LifetimeExtendObject(TheExpr)) {
1895 assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&(static_cast <bool> (getEvaluationKind(TheExpr->getType
()) == TEK_Scalar && "Only scalar can be a ObjC retainable type"
) ? void (0) : __assert_fail ("getEvaluationKind(TheExpr->getType()) == TEK_Scalar && \"Only scalar can be a ObjC retainable type\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1896, __extension__ __PRETTY_FUNCTION__
))
1896 "Only scalar can be a ObjC retainable type")(static_cast <bool> (getEvaluationKind(TheExpr->getType
()) == TEK_Scalar && "Only scalar can be a ObjC retainable type"
) ? void (0) : __assert_fail ("getEvaluationKind(TheExpr->getType()) == TEK_Scalar && \"Only scalar can be a ObjC retainable type\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1896, __extension__ __PRETTY_FUNCTION__
))
;
1897 if (!isa<Constant>(ArgVal)) {
1898 CleanupKind Cleanup = getARCCleanupKind();
1899 QualType Ty = TheExpr->getType();
1900 Address Alloca = Address::invalid();
1901 Address Addr = CreateMemTemp(Ty, "os.log.arg", &Alloca);
1902 ArgVal = EmitARCRetain(Ty, ArgVal);
1903 Builder.CreateStore(ArgVal, Addr);
1904 pushLifetimeExtendedDestroy(Cleanup, Alloca, Ty,
1905 CodeGenFunction::destroyARCStrongPrecise,
1906 Cleanup & EHCleanup);
1907
1908 // Push a clang.arc.use call to ensure ARC optimizer knows that the
1909 // argument has to be alive.
1910 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
1911 pushCleanupAfterFullExpr<CallObjCArcUse>(Cleanup, ArgVal);
1912 }
1913 }
1914 } else {
1915 ArgVal = Builder.getInt32(Item.getConstValue().getQuantity());
1916 }
1917
1918 unsigned ArgValSize =
1919 CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType());
1920 llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(),
1921 ArgValSize);
1922 ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy);
1923 CanQualType ArgTy = getOSLogArgType(Ctx, Size);
1924 // If ArgVal has type x86_fp80, zero-extend ArgVal.
1925 ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy));
1926 Args.add(RValue::get(ArgVal), ArgTy);
1927 }
1928
1929 const CGFunctionInfo &FI =
1930 CGM.getTypes().arrangeBuiltinFunctionCall(Ctx.VoidTy, Args);
1931 llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction(
1932 Layout, BufAddr.getAlignment());
1933 EmitCall(FI, CGCallee::forDirect(F), ReturnValueSlot(), Args);
1934 return RValue::get(BufAddr.getPointer());
1935}
1936
1937static bool isSpecialUnsignedMultiplySignedResult(
1938 unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info,
1939 WidthAndSignedness ResultInfo) {
1940 return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1941 Op1Info.Width == Op2Info.Width && Op2Info.Width == ResultInfo.Width &&
1942 !Op1Info.Signed && !Op2Info.Signed && ResultInfo.Signed;
1943}
1944
1945static RValue EmitCheckedUnsignedMultiplySignedResult(
1946 CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info,
1947 const clang::Expr *Op2, WidthAndSignedness Op2Info,
1948 const clang::Expr *ResultArg, QualType ResultQTy,
1949 WidthAndSignedness ResultInfo) {
1950 assert(isSpecialUnsignedMultiplySignedResult((static_cast <bool> (isSpecialUnsignedMultiplySignedResult
( Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo
) && "Cannot specialize this multiply") ? void (0) : __assert_fail
("isSpecialUnsignedMultiplySignedResult( Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && \"Cannot specialize this multiply\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1952, __extension__ __PRETTY_FUNCTION__
))
1951 Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&(static_cast <bool> (isSpecialUnsignedMultiplySignedResult
( Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo
) && "Cannot specialize this multiply") ? void (0) : __assert_fail
("isSpecialUnsignedMultiplySignedResult( Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && \"Cannot specialize this multiply\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1952, __extension__ __PRETTY_FUNCTION__
))
1952 "Cannot specialize this multiply")(static_cast <bool> (isSpecialUnsignedMultiplySignedResult
( Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo
) && "Cannot specialize this multiply") ? void (0) : __assert_fail
("isSpecialUnsignedMultiplySignedResult( Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && \"Cannot specialize this multiply\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1952, __extension__ __PRETTY_FUNCTION__
))
;
1953
1954 llvm::Value *V1 = CGF.EmitScalarExpr(Op1);
1955 llvm::Value *V2 = CGF.EmitScalarExpr(Op2);
1956
1957 llvm::Value *HasOverflow;
1958 llvm::Value *Result = EmitOverflowIntrinsic(
1959 CGF, llvm::Intrinsic::umul_with_overflow, V1, V2, HasOverflow);
1960
1961 // The intrinsic call will detect overflow when the value is > UINT_MAX,
1962 // however, since the original builtin had a signed result, we need to report
1963 // an overflow when the result is greater than INT_MAX.
1964 auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width);
1965 llvm::Value *IntMaxValue = llvm::ConstantInt::get(Result->getType(), IntMax);
1966
1967 llvm::Value *IntMaxOverflow = CGF.Builder.CreateICmpUGT(Result, IntMaxValue);
1968 HasOverflow = CGF.Builder.CreateOr(HasOverflow, IntMaxOverflow);
1969
1970 bool isVolatile =
1971 ResultArg->getType()->getPointeeType().isVolatileQualified();
1972 Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
1973 CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
1974 isVolatile);
1975 return RValue::get(HasOverflow);
1976}
1977
1978/// Determine if a binop is a checked mixed-sign multiply we can specialize.
1979static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
1980 WidthAndSignedness Op1Info,
1981 WidthAndSignedness Op2Info,
1982 WidthAndSignedness ResultInfo) {
1983 return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1984 std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width &&
1985 Op1Info.Signed != Op2Info.Signed;
1986}
1987
1988/// Emit a checked mixed-sign multiply. This is a cheaper specialization of
1989/// the generic checked-binop irgen.
1990static RValue
1991EmitCheckedMixedSignMultiply(CodeGenFunction &CGF, const clang::Expr *Op1,
1992 WidthAndSignedness Op1Info, const clang::Expr *Op2,
1993 WidthAndSignedness Op2Info,
1994 const clang::Expr *ResultArg, QualType ResultQTy,
1995 WidthAndSignedness ResultInfo) {
1996 assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,(static_cast <bool> (isSpecialMixedSignMultiply(Builtin
::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
"Not a mixed-sign multipliction we can specialize") ? void (
0) : __assert_fail ("isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && \"Not a mixed-sign multipliction we can specialize\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1998, __extension__ __PRETTY_FUNCTION__
))
1997 Op2Info, ResultInfo) &&(static_cast <bool> (isSpecialMixedSignMultiply(Builtin
::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
"Not a mixed-sign multipliction we can specialize") ? void (
0) : __assert_fail ("isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && \"Not a mixed-sign multipliction we can specialize\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1998, __extension__ __PRETTY_FUNCTION__
))
1998 "Not a mixed-sign multipliction we can specialize")(static_cast <bool> (isSpecialMixedSignMultiply(Builtin
::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
"Not a mixed-sign multipliction we can specialize") ? void (
0) : __assert_fail ("isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && \"Not a mixed-sign multipliction we can specialize\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 1998, __extension__ __PRETTY_FUNCTION__
))
;
1999
2000 // Emit the signed and unsigned operands.
2001 const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
2002 const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
2003 llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
2004 llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
2005 unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width;
2006 unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width;
2007
2008 // One of the operands may be smaller than the other. If so, [s|z]ext it.
2009 if (SignedOpWidth < UnsignedOpWidth)
2010 Signed = CGF.Builder.CreateSExt(Signed, Unsigned->getType(), "op.sext");
2011 if (UnsignedOpWidth < SignedOpWidth)
2012 Unsigned = CGF.Builder.CreateZExt(Unsigned, Signed->getType(), "op.zext");
2013
2014 llvm::Type *OpTy = Signed->getType();
2015 llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
2016 Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
2017 llvm::Type *ResTy = ResultPtr.getElementType();
2018 unsigned OpWidth = std::max(Op1Info.Width, Op2Info.Width);
2019
2020 // Take the absolute value of the signed operand.
2021 llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
2022 llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
2023 llvm::Value *AbsSigned =
2024 CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
2025
2026 // Perform a checked unsigned multiplication.
2027 llvm::Value *UnsignedOverflow;
2028 llvm::Value *UnsignedResult =
2029 EmitOverflowIntrinsic(CGF, llvm::Intrinsic::umul_with_overflow, AbsSigned,
2030 Unsigned, UnsignedOverflow);
2031
2032 llvm::Value *Overflow, *Result;
2033 if (ResultInfo.Signed) {
2034 // Signed overflow occurs if the result is greater than INT_MAX or lesser
2035 // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
2036 auto IntMax =
2037 llvm::APInt::getSignedMaxValue(ResultInfo.Width).zext(OpWidth);
2038 llvm::Value *MaxResult =
2039 CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
2040 CGF.Builder.CreateZExt(IsNegative, OpTy));
2041 llvm::Value *SignedOverflow =
2042 CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
2043 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
2044
2045 // Prepare the signed result (possibly by negating it).
2046 llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
2047 llvm::Value *SignedResult =
2048 CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
2049 Result = CGF.Builder.CreateTrunc(SignedResult, ResTy);
2050 } else {
2051 // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX.
2052 llvm::Value *Underflow = CGF.Builder.CreateAnd(
2053 IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
2054 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
2055 if (ResultInfo.Width < OpWidth) {
2056 auto IntMax =
2057 llvm::APInt::getMaxValue(ResultInfo.Width).zext(OpWidth);
2058 llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
2059 UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
2060 Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
2061 }
2062
2063 // Negate the product if it would be negative in infinite precision.
2064 Result = CGF.Builder.CreateSelect(
2065 IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
2066
2067 Result = CGF.Builder.CreateTrunc(Result, ResTy);
2068 }
2069 assert(Overflow && Result && "Missing overflow or result")(static_cast <bool> (Overflow && Result &&
"Missing overflow or result") ? void (0) : __assert_fail ("Overflow && Result && \"Missing overflow or result\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 2069, __extension__ __PRETTY_FUNCTION__
))
;
2070
2071 bool isVolatile =
2072 ResultArg->getType()->getPointeeType().isVolatileQualified();
2073 CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2074 isVolatile);
2075 return RValue::get(Overflow);
2076}
2077
2078static bool
2079TypeRequiresBuiltinLaunderImp(const ASTContext &Ctx, QualType Ty,
2080 llvm::SmallPtrSetImpl<const Decl *> &Seen) {
2081 if (const auto *Arr = Ctx.getAsArrayType(Ty))
2082 Ty = Ctx.getBaseElementType(Arr);
2083
2084 const auto *Record = Ty->getAsCXXRecordDecl();
2085 if (!Record)
2086 return false;
2087
2088 // We've already checked this type, or are in the process of checking it.
2089 if (!Seen.insert(Record).second)
2090 return false;
2091
2092 assert(Record->hasDefinition() &&(static_cast <bool> (Record->hasDefinition() &&
"Incomplete types should already be diagnosed") ? void (0) :
__assert_fail ("Record->hasDefinition() && \"Incomplete types should already be diagnosed\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 2093, __extension__ __PRETTY_FUNCTION__
))
2093 "Incomplete types should already be diagnosed")(static_cast <bool> (Record->hasDefinition() &&
"Incomplete types should already be diagnosed") ? void (0) :
__assert_fail ("Record->hasDefinition() && \"Incomplete types should already be diagnosed\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 2093, __extension__ __PRETTY_FUNCTION__
))
;
2094
2095 if (Record->isDynamicClass())
2096 return true;
2097
2098 for (FieldDecl *F : Record->fields()) {
2099 if (TypeRequiresBuiltinLaunderImp(Ctx, F->getType(), Seen))
2100 return true;
2101 }
2102 return false;
2103}
2104
2105/// Determine if the specified type requires laundering by checking if it is a
2106/// dynamic class type or contains a subobject which is a dynamic class type.
2107static bool TypeRequiresBuiltinLaunder(CodeGenModule &CGM, QualType Ty) {
2108 if (!CGM.getCodeGenOpts().StrictVTablePointers)
2109 return false;
2110 llvm::SmallPtrSet<const Decl *, 16> Seen;
2111 return TypeRequiresBuiltinLaunderImp(CGM.getContext(), Ty, Seen);
2112}
2113
2114RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) {
2115 llvm::Value *Src = EmitScalarExpr(E->getArg(0));
2116 llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1));
2117
2118 // The builtin's shift arg may have a different type than the source arg and
2119 // result, but the LLVM intrinsic uses the same type for all values.
2120 llvm::Type *Ty = Src->getType();
2121 ShiftAmt = Builder.CreateIntCast(ShiftAmt, Ty, false);
2122
2123 // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same.
2124 unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
2125 Function *F = CGM.getIntrinsic(IID, Ty);
2126 return RValue::get(Builder.CreateCall(F, { Src, Src, ShiftAmt }));
2127}
2128
2129// Map math builtins for long-double to f128 version.
2130static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID) {
2131 switch (BuiltinID) {
2132#define MUTATE_LDBL(func) \
2133 case Builtin::BI__builtin_##func##l: \
2134 return Builtin::BI__builtin_##func##f128;
2135 MUTATE_LDBL(sqrt)
2136 MUTATE_LDBL(cbrt)
2137 MUTATE_LDBL(fabs)
2138 MUTATE_LDBL(log)
2139 MUTATE_LDBL(log2)
2140 MUTATE_LDBL(log10)
2141 MUTATE_LDBL(log1p)
2142 MUTATE_LDBL(logb)
2143 MUTATE_LDBL(exp)
2144 MUTATE_LDBL(exp2)
2145 MUTATE_LDBL(expm1)
2146 MUTATE_LDBL(fdim)
2147 MUTATE_LDBL(hypot)
2148 MUTATE_LDBL(ilogb)
2149 MUTATE_LDBL(pow)
2150 MUTATE_LDBL(fmin)
2151 MUTATE_LDBL(fmax)
2152 MUTATE_LDBL(ceil)
2153 MUTATE_LDBL(trunc)
2154 MUTATE_LDBL(rint)
2155 MUTATE_LDBL(nearbyint)
2156 MUTATE_LDBL(round)
2157 MUTATE_LDBL(floor)
2158 MUTATE_LDBL(lround)
2159 MUTATE_LDBL(llround)
2160 MUTATE_LDBL(lrint)
2161 MUTATE_LDBL(llrint)
2162 MUTATE_LDBL(fmod)
2163 MUTATE_LDBL(modf)
2164 MUTATE_LDBL(nan)
2165 MUTATE_LDBL(nans)
2166 MUTATE_LDBL(inf)
2167 MUTATE_LDBL(fma)
2168 MUTATE_LDBL(sin)
2169 MUTATE_LDBL(cos)
2170 MUTATE_LDBL(tan)
2171 MUTATE_LDBL(sinh)
2172 MUTATE_LDBL(cosh)
2173 MUTATE_LDBL(tanh)
2174 MUTATE_LDBL(asin)
2175 MUTATE_LDBL(acos)
2176 MUTATE_LDBL(atan)
2177 MUTATE_LDBL(asinh)
2178 MUTATE_LDBL(acosh)
2179 MUTATE_LDBL(atanh)
2180 MUTATE_LDBL(atan2)
2181 MUTATE_LDBL(erf)
2182 MUTATE_LDBL(erfc)
2183 MUTATE_LDBL(ldexp)
2184 MUTATE_LDBL(frexp)
2185 MUTATE_LDBL(huge_val)
2186 MUTATE_LDBL(copysign)
2187 MUTATE_LDBL(nextafter)
2188 MUTATE_LDBL(nexttoward)
2189 MUTATE_LDBL(remainder)
2190 MUTATE_LDBL(remquo)
2191 MUTATE_LDBL(scalbln)
2192 MUTATE_LDBL(scalbn)
2193 MUTATE_LDBL(tgamma)
2194 MUTATE_LDBL(lgamma)
2195#undef MUTATE_LDBL
2196 default:
2197 return BuiltinID;
2198 }
2199}
2200
2201RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
2202 const CallExpr *E,
2203 ReturnValueSlot ReturnValue) {
2204 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
2205 // See if we can constant fold this builtin. If so, don't emit it at all.
2206 // TODO: Extend this handling to all builtin calls that we can constant-fold.
2207 Expr::EvalResult Result;
2208 if (E->isPRValue() && E->EvaluateAsRValue(Result, CGM.getContext()) &&
2209 !Result.hasSideEffects()) {
2210 if (Result.Val.isInt())
2211 return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
2212 Result.Val.getInt()));
2213 if (Result.Val.isFloat())
2214 return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
2215 Result.Val.getFloat()));
2216 }
2217
2218 // If current long-double semantics is IEEE 128-bit, replace math builtins
2219 // of long-double with f128 equivalent.
2220 // TODO: This mutation should also be applied to other targets other than PPC,
2221 // after backend supports IEEE 128-bit style libcalls.
2222 if (getTarget().getTriple().isPPC64() &&
2223 &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
2224 BuiltinID = mutateLongDoubleBuiltin(BuiltinID);
2225
2226 // If the builtin has been declared explicitly with an assembler label,
2227 // disable the specialized emitting below. Ideally we should communicate the
2228 // rename in IR, or at least avoid generating the intrinsic calls that are
2229 // likely to get lowered to the renamed library functions.
2230 const unsigned BuiltinIDIfNoAsmLabel =
2231 FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID;
2232
2233 // There are LLVM math intrinsics/instructions corresponding to math library
2234 // functions except the LLVM op will never set errno while the math library
2235 // might. Also, math builtins have the same semantics as their math library
2236 // twins. Thus, we can transform math library and builtin calls to their
2237 // LLVM counterparts if the call is marked 'const' (known to never set errno).
2238 // In case FP exceptions are enabled, the experimental versions of the
2239 // intrinsics model those.
2240 bool ConstWithoutErrnoAndExceptions =
2241 getContext().BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
2242 bool ConstWithoutExceptions =
2243 getContext().BuiltinInfo.isConstWithoutExceptions(BuiltinID);
2244 if (FD->hasAttr<ConstAttr>() ||
2245 ((ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
2246 (!ConstWithoutErrnoAndExceptions || (!getLangOpts().MathErrno)))) {
2247 switch (BuiltinIDIfNoAsmLabel) {
2248 case Builtin::BIceil:
2249 case Builtin::BIceilf:
2250 case Builtin::BIceill:
2251 case Builtin::BI__builtin_ceil:
2252 case Builtin::BI__builtin_ceilf:
2253 case Builtin::BI__builtin_ceilf16:
2254 case Builtin::BI__builtin_ceill:
2255 case Builtin::BI__builtin_ceilf128:
2256 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2257 Intrinsic::ceil,
2258 Intrinsic::experimental_constrained_ceil));
2259
2260 case Builtin::BIcopysign:
2261 case Builtin::BIcopysignf:
2262 case Builtin::BIcopysignl:
2263 case Builtin::BI__builtin_copysign:
2264 case Builtin::BI__builtin_copysignf:
2265 case Builtin::BI__builtin_copysignf16:
2266 case Builtin::BI__builtin_copysignl:
2267 case Builtin::BI__builtin_copysignf128:
2268 return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::copysign));
2269
2270 case Builtin::BIcos:
2271 case Builtin::BIcosf:
2272 case Builtin::BIcosl:
2273 case Builtin::BI__builtin_cos:
2274 case Builtin::BI__builtin_cosf:
2275 case Builtin::BI__builtin_cosf16:
2276 case Builtin::BI__builtin_cosl:
2277 case Builtin::BI__builtin_cosf128:
2278 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2279 Intrinsic::cos,
2280 Intrinsic::experimental_constrained_cos));
2281
2282 case Builtin::BIexp:
2283 case Builtin::BIexpf:
2284 case Builtin::BIexpl:
2285 case Builtin::BI__builtin_exp:
2286 case Builtin::BI__builtin_expf:
2287 case Builtin::BI__builtin_expf16:
2288 case Builtin::BI__builtin_expl:
2289 case Builtin::BI__builtin_expf128:
2290 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2291 Intrinsic::exp,
2292 Intrinsic::experimental_constrained_exp));
2293
2294 case Builtin::BIexp2:
2295 case Builtin::BIexp2f:
2296 case Builtin::BIexp2l:
2297 case Builtin::BI__builtin_exp2:
2298 case Builtin::BI__builtin_exp2f:
2299 case Builtin::BI__builtin_exp2f16:
2300 case Builtin::BI__builtin_exp2l:
2301 case Builtin::BI__builtin_exp2f128:
2302 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2303 Intrinsic::exp2,
2304 Intrinsic::experimental_constrained_exp2));
2305
2306 case Builtin::BIfabs:
2307 case Builtin::BIfabsf:
2308 case Builtin::BIfabsl:
2309 case Builtin::BI__builtin_fabs:
2310 case Builtin::BI__builtin_fabsf:
2311 case Builtin::BI__builtin_fabsf16:
2312 case Builtin::BI__builtin_fabsl:
2313 case Builtin::BI__builtin_fabsf128:
2314 return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::fabs));
2315
2316 case Builtin::BIfloor:
2317 case Builtin::BIfloorf:
2318 case Builtin::BIfloorl:
2319 case Builtin::BI__builtin_floor:
2320 case Builtin::BI__builtin_floorf:
2321 case Builtin::BI__builtin_floorf16:
2322 case Builtin::BI__builtin_floorl:
2323 case Builtin::BI__builtin_floorf128:
2324 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2325 Intrinsic::floor,
2326 Intrinsic::experimental_constrained_floor));
2327
2328 case Builtin::BIfma:
2329 case Builtin::BIfmaf:
2330 case Builtin::BIfmal:
2331 case Builtin::BI__builtin_fma:
2332 case Builtin::BI__builtin_fmaf:
2333 case Builtin::BI__builtin_fmaf16:
2334 case Builtin::BI__builtin_fmal:
2335 case Builtin::BI__builtin_fmaf128:
2336 return RValue::get(emitTernaryMaybeConstrainedFPBuiltin(*this, E,
2337 Intrinsic::fma,
2338 Intrinsic::experimental_constrained_fma));
2339
2340 case Builtin::BIfmax:
2341 case Builtin::BIfmaxf:
2342 case Builtin::BIfmaxl:
2343 case Builtin::BI__builtin_fmax:
2344 case Builtin::BI__builtin_fmaxf:
2345 case Builtin::BI__builtin_fmaxf16:
2346 case Builtin::BI__builtin_fmaxl:
2347 case Builtin::BI__builtin_fmaxf128:
2348 return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E,
2349 Intrinsic::maxnum,
2350 Intrinsic::experimental_constrained_maxnum));
2351
2352 case Builtin::BIfmin:
2353 case Builtin::BIfminf:
2354 case Builtin::BIfminl:
2355 case Builtin::BI__builtin_fmin:
2356 case Builtin::BI__builtin_fminf:
2357 case Builtin::BI__builtin_fminf16:
2358 case Builtin::BI__builtin_fminl:
2359 case Builtin::BI__builtin_fminf128:
2360 return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E,
2361 Intrinsic::minnum,
2362 Intrinsic::experimental_constrained_minnum));
2363
2364 // fmod() is a special-case. It maps to the frem instruction rather than an
2365 // LLVM intrinsic.
2366 case Builtin::BIfmod:
2367 case Builtin::BIfmodf:
2368 case Builtin::BIfmodl:
2369 case Builtin::BI__builtin_fmod:
2370 case Builtin::BI__builtin_fmodf:
2371 case Builtin::BI__builtin_fmodf16:
2372 case Builtin::BI__builtin_fmodl:
2373 case Builtin::BI__builtin_fmodf128: {
2374 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2375 Value *Arg1 = EmitScalarExpr(E->getArg(0));
2376 Value *Arg2 = EmitScalarExpr(E->getArg(1));
2377 return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
2378 }
2379
2380 case Builtin::BIlog:
2381 case Builtin::BIlogf:
2382 case Builtin::BIlogl:
2383 case Builtin::BI__builtin_log:
2384 case Builtin::BI__builtin_logf:
2385 case Builtin::BI__builtin_logf16:
2386 case Builtin::BI__builtin_logl:
2387 case Builtin::BI__builtin_logf128:
2388 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2389 Intrinsic::log,
2390 Intrinsic::experimental_constrained_log));
2391
2392 case Builtin::BIlog10:
2393 case Builtin::BIlog10f:
2394 case Builtin::BIlog10l:
2395 case Builtin::BI__builtin_log10:
2396 case Builtin::BI__builtin_log10f:
2397 case Builtin::BI__builtin_log10f16:
2398 case Builtin::BI__builtin_log10l:
2399 case Builtin::BI__builtin_log10f128:
2400 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2401 Intrinsic::log10,
2402 Intrinsic::experimental_constrained_log10));
2403
2404 case Builtin::BIlog2:
2405 case Builtin::BIlog2f:
2406 case Builtin::BIlog2l:
2407 case Builtin::BI__builtin_log2:
2408 case Builtin::BI__builtin_log2f:
2409 case Builtin::BI__builtin_log2f16:
2410 case Builtin::BI__builtin_log2l:
2411 case Builtin::BI__builtin_log2f128:
2412 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2413 Intrinsic::log2,
2414 Intrinsic::experimental_constrained_log2));
2415
2416 case Builtin::BInearbyint:
2417 case Builtin::BInearbyintf:
2418 case Builtin::BInearbyintl:
2419 case Builtin::BI__builtin_nearbyint:
2420 case Builtin::BI__builtin_nearbyintf:
2421 case Builtin::BI__builtin_nearbyintl:
2422 case Builtin::BI__builtin_nearbyintf128:
2423 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2424 Intrinsic::nearbyint,
2425 Intrinsic::experimental_constrained_nearbyint));
2426
2427 case Builtin::BIpow:
2428 case Builtin::BIpowf:
2429 case Builtin::BIpowl:
2430 case Builtin::BI__builtin_pow:
2431 case Builtin::BI__builtin_powf:
2432 case Builtin::BI__builtin_powf16:
2433 case Builtin::BI__builtin_powl:
2434 case Builtin::BI__builtin_powf128:
2435 return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E,
2436 Intrinsic::pow,
2437 Intrinsic::experimental_constrained_pow));
2438
2439 case Builtin::BIrint:
2440 case Builtin::BIrintf:
2441 case Builtin::BIrintl:
2442 case Builtin::BI__builtin_rint:
2443 case Builtin::BI__builtin_rintf:
2444 case Builtin::BI__builtin_rintf16:
2445 case Builtin::BI__builtin_rintl:
2446 case Builtin::BI__builtin_rintf128:
2447 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2448 Intrinsic::rint,
2449 Intrinsic::experimental_constrained_rint));
2450
2451 case Builtin::BIround:
2452 case Builtin::BIroundf:
2453 case Builtin::BIroundl:
2454 case Builtin::BI__builtin_round:
2455 case Builtin::BI__builtin_roundf:
2456 case Builtin::BI__builtin_roundf16:
2457 case Builtin::BI__builtin_roundl:
2458 case Builtin::BI__builtin_roundf128:
2459 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2460 Intrinsic::round,
2461 Intrinsic::experimental_constrained_round));
2462
2463 case Builtin::BIroundeven:
2464 case Builtin::BIroundevenf:
2465 case Builtin::BIroundevenl:
2466 case Builtin::BI__builtin_roundeven:
2467 case Builtin::BI__builtin_roundevenf:
2468 case Builtin::BI__builtin_roundevenf16:
2469 case Builtin::BI__builtin_roundevenl:
2470 case Builtin::BI__builtin_roundevenf128:
2471 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2472 Intrinsic::roundeven,
2473 Intrinsic::experimental_constrained_roundeven));
2474
2475 case Builtin::BIsin:
2476 case Builtin::BIsinf:
2477 case Builtin::BIsinl:
2478 case Builtin::BI__builtin_sin:
2479 case Builtin::BI__builtin_sinf:
2480 case Builtin::BI__builtin_sinf16:
2481 case Builtin::BI__builtin_sinl:
2482 case Builtin::BI__builtin_sinf128:
2483 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2484 Intrinsic::sin,
2485 Intrinsic::experimental_constrained_sin));
2486
2487 case Builtin::BIsqrt:
2488 case Builtin::BIsqrtf:
2489 case Builtin::BIsqrtl:
2490 case Builtin::BI__builtin_sqrt:
2491 case Builtin::BI__builtin_sqrtf:
2492 case Builtin::BI__builtin_sqrtf16:
2493 case Builtin::BI__builtin_sqrtl:
2494 case Builtin::BI__builtin_sqrtf128:
2495 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2496 Intrinsic::sqrt,
2497 Intrinsic::experimental_constrained_sqrt));
2498
2499 case Builtin::BItrunc:
2500 case Builtin::BItruncf:
2501 case Builtin::BItruncl:
2502 case Builtin::BI__builtin_trunc:
2503 case Builtin::BI__builtin_truncf:
2504 case Builtin::BI__builtin_truncf16:
2505 case Builtin::BI__builtin_truncl:
2506 case Builtin::BI__builtin_truncf128:
2507 return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2508 Intrinsic::trunc,
2509 Intrinsic::experimental_constrained_trunc));
2510
2511 case Builtin::BIlround:
2512 case Builtin::BIlroundf:
2513 case Builtin::BIlroundl:
2514 case Builtin::BI__builtin_lround:
2515 case Builtin::BI__builtin_lroundf:
2516 case Builtin::BI__builtin_lroundl:
2517 case Builtin::BI__builtin_lroundf128:
2518 return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2519 *this, E, Intrinsic::lround,
2520 Intrinsic::experimental_constrained_lround));
2521
2522 case Builtin::BIllround:
2523 case Builtin::BIllroundf:
2524 case Builtin::BIllroundl:
2525 case Builtin::BI__builtin_llround:
2526 case Builtin::BI__builtin_llroundf:
2527 case Builtin::BI__builtin_llroundl:
2528 case Builtin::BI__builtin_llroundf128:
2529 return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2530 *this, E, Intrinsic::llround,
2531 Intrinsic::experimental_constrained_llround));
2532
2533 case Builtin::BIlrint:
2534 case Builtin::BIlrintf:
2535 case Builtin::BIlrintl:
2536 case Builtin::BI__builtin_lrint:
2537 case Builtin::BI__builtin_lrintf:
2538 case Builtin::BI__builtin_lrintl:
2539 case Builtin::BI__builtin_lrintf128:
2540 return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2541 *this, E, Intrinsic::lrint,
2542 Intrinsic::experimental_constrained_lrint));
2543
2544 case Builtin::BIllrint:
2545 case Builtin::BIllrintf:
2546 case Builtin::BIllrintl:
2547 case Builtin::BI__builtin_llrint:
2548 case Builtin::BI__builtin_llrintf:
2549 case Builtin::BI__builtin_llrintl:
2550 case Builtin::BI__builtin_llrintf128:
2551 return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2552 *this, E, Intrinsic::llrint,
2553 Intrinsic::experimental_constrained_llrint));
2554
2555 default:
2556 break;
2557 }
2558 }
2559
2560 switch (BuiltinIDIfNoAsmLabel) {
2561 default: break;
2562 case Builtin::BI__builtin___CFStringMakeConstantString:
2563 case Builtin::BI__builtin___NSStringMakeConstantString:
2564 return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
2565 case Builtin::BI__builtin_stdarg_start:
2566 case Builtin::BI__builtin_va_start:
2567 case Builtin::BI__va_start:
2568 case Builtin::BI__builtin_va_end:
2569 EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
2570 ? EmitScalarExpr(E->getArg(0))
2571 : EmitVAListRef(E->getArg(0)).getPointer(),
2572 BuiltinID != Builtin::BI__builtin_va_end);
2573 return RValue::get(nullptr);
2574 case Builtin::BI__builtin_va_copy: {
2575 Value *DstPtr = EmitVAListRef(E->getArg(0)).getPointer();
2576 Value *SrcPtr = EmitVAListRef(E->getArg(1)).getPointer();
2577
2578 llvm::Type *Type = Int8PtrTy;
2579
2580 DstPtr = Builder.CreateBitCast(DstPtr, Type);
2581 SrcPtr = Builder.CreateBitCast(SrcPtr, Type);
2582 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy), {DstPtr, SrcPtr});
2583 return RValue::get(nullptr);
2584 }
2585 case Builtin::BI__builtin_abs:
2586 case Builtin::BI__builtin_labs:
2587 case Builtin::BI__builtin_llabs: {
2588 // X < 0 ? -X : X
2589 // The negation has 'nsw' because abs of INT_MIN is undefined.
2590 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2591 Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg");
2592 Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType());
2593 Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
2594 Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs");
2595 return RValue::get(Result);
2596 }
2597 case Builtin::BI__builtin_complex: {
2598 Value *Real = EmitScalarExpr(E->getArg(0));
2599 Value *Imag = EmitScalarExpr(E->getArg(1));
2600 return RValue::getComplex({Real, Imag});
2601 }
2602 case Builtin::BI__builtin_conj:
2603 case Builtin::BI__builtin_conjf:
2604 case Builtin::BI__builtin_conjl:
2605 case Builtin::BIconj:
2606 case Builtin::BIconjf:
2607 case Builtin::BIconjl: {
2608 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2609 Value *Real = ComplexVal.first;
2610 Value *Imag = ComplexVal.second;
2611 Imag = Builder.CreateFNeg(Imag, "neg");
2612 return RValue::getComplex(std::make_pair(Real, Imag));
2613 }
2614 case Builtin::BI__builtin_creal:
2615 case Builtin::BI__builtin_crealf:
2616 case Builtin::BI__builtin_creall:
2617 case Builtin::BIcreal:
2618 case Builtin::BIcrealf:
2619 case Builtin::BIcreall: {
2620 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2621 return RValue::get(ComplexVal.first);
2622 }
2623
2624 case Builtin::BI__builtin_preserve_access_index: {
2625 // Only enabled preserved access index region when debuginfo
2626 // is available as debuginfo is needed to preserve user-level
2627 // access pattern.
2628 if (!getDebugInfo()) {
2629 CGM.Error(E->getExprLoc(), "using builtin_preserve_access_index() without -g");
2630 return RValue::get(EmitScalarExpr(E->getArg(0)));
2631 }
2632
2633 // Nested builtin_preserve_access_index() not supported
2634 if (IsInPreservedAIRegion) {
2635 CGM.Error(E->getExprLoc(), "nested builtin_preserve_access_index() not supported");
2636 return RValue::get(EmitScalarExpr(E->getArg(0)));
2637 }
2638
2639 IsInPreservedAIRegion = true;
2640 Value *Res = EmitScalarExpr(E->getArg(0));
2641 IsInPreservedAIRegion = false;
2642 return RValue::get(Res);
2643 }
2644
2645 case Builtin::BI__builtin_cimag:
2646 case Builtin::BI__builtin_cimagf:
2647 case Builtin::BI__builtin_cimagl:
2648 case Builtin::BIcimag:
2649 case Builtin::BIcimagf:
2650 case Builtin::BIcimagl: {
2651 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2652 return RValue::get(ComplexVal.second);
2653 }
2654
2655 case Builtin::BI__builtin_clrsb:
2656 case Builtin::BI__builtin_clrsbl:
2657 case Builtin::BI__builtin_clrsbll: {
2658 // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or
2659 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2660
2661 llvm::Type *ArgType = ArgValue->getType();
2662 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2663
2664 llvm::Type *ResultType = ConvertType(E->getType());
2665 Value *Zero = llvm::Constant::getNullValue(ArgType);
2666 Value *IsNeg = Builder.CreateICmpSLT(ArgValue, Zero, "isneg");
2667 Value *Inverse = Builder.CreateNot(ArgValue, "not");
2668 Value *Tmp = Builder.CreateSelect(IsNeg, Inverse, ArgValue);
2669 Value *Ctlz = Builder.CreateCall(F, {Tmp, Builder.getFalse()});
2670 Value *Result = Builder.CreateSub(Ctlz, llvm::ConstantInt::get(ArgType, 1));
2671 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2672 "cast");
2673 return RValue::get(Result);
2674 }
2675 case Builtin::BI__builtin_ctzs:
2676 case Builtin::BI__builtin_ctz:
2677 case Builtin::BI__builtin_ctzl:
2678 case Builtin::BI__builtin_ctzll: {
2679 Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CTZPassedZero);
2680
2681 llvm::Type *ArgType = ArgValue->getType();
2682 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
2683
2684 llvm::Type *ResultType = ConvertType(E->getType());
2685 Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
2686 Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
2687 if (Result->getType() != ResultType)
2688 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2689 "cast");
2690 return RValue::get(Result);
2691 }
2692 case Builtin::BI__builtin_clzs:
2693 case Builtin::BI__builtin_clz:
2694 case Builtin::BI__builtin_clzl:
2695 case Builtin::BI__builtin_clzll: {
2696 Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CLZPassedZero);
2697
2698 llvm::Type *ArgType = ArgValue->getType();
2699 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2700
2701 llvm::Type *ResultType = ConvertType(E->getType());
2702 Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
2703 Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
2704 if (Result->getType() != ResultType)
2705 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2706 "cast");
2707 return RValue::get(Result);
2708 }
2709 case Builtin::BI__builtin_ffs:
2710 case Builtin::BI__builtin_ffsl:
2711 case Builtin::BI__builtin_ffsll: {
2712 // ffs(x) -> x ? cttz(x) + 1 : 0
2713 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2714
2715 llvm::Type *ArgType = ArgValue->getType();
2716 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
2717
2718 llvm::Type *ResultType = ConvertType(E->getType());
2719 Value *Tmp =
2720 Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
2721 llvm::ConstantInt::get(ArgType, 1));
2722 Value *Zero = llvm::Constant::getNullValue(ArgType);
2723 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
2724 Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
2725 if (Result->getType() != ResultType)
2726 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2727 "cast");
2728 return RValue::get(Result);
2729 }
2730 case Builtin::BI__builtin_parity:
2731 case Builtin::BI__builtin_parityl:
2732 case Builtin::BI__builtin_parityll: {
2733 // parity(x) -> ctpop(x) & 1
2734 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2735
2736 llvm::Type *ArgType = ArgValue->getType();
2737 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
2738
2739 llvm::Type *ResultType = ConvertType(E->getType());
2740 Value *Tmp = Builder.CreateCall(F, ArgValue);
2741 Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
2742 if (Result->getType() != ResultType)
2743 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2744 "cast");
2745 return RValue::get(Result);
2746 }
2747 case Builtin::BI__lzcnt16:
2748 case Builtin::BI__lzcnt:
2749 case Builtin::BI__lzcnt64: {
2750 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2751
2752 llvm::Type *ArgType = ArgValue->getType();
2753 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2754
2755 llvm::Type *ResultType = ConvertType(E->getType());
2756 Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
2757 if (Result->getType() != ResultType)
2758 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2759 "cast");
2760 return RValue::get(Result);
2761 }
2762 case Builtin::BI__popcnt16:
2763 case Builtin::BI__popcnt:
2764 case Builtin::BI__popcnt64:
2765 case Builtin::BI__builtin_popcount:
2766 case Builtin::BI__builtin_popcountl:
2767 case Builtin::BI__builtin_popcountll: {
2768 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2769
2770 llvm::Type *ArgType = ArgValue->getType();
2771 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
2772
2773 llvm::Type *ResultType = ConvertType(E->getType());
2774 Value *Result = Builder.CreateCall(F, ArgValue);
2775 if (Result->getType() != ResultType)
2776 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2777 "cast");
2778 return RValue::get(Result);
2779 }
2780 case Builtin::BI__builtin_unpredictable: {
2781 // Always return the argument of __builtin_unpredictable. LLVM does not
2782 // handle this builtin. Metadata for this builtin should be added directly
2783 // to instructions such as branches or switches that use it.
2784 return RValue::get(EmitScalarExpr(E->getArg(0)));
2785 }
2786 case Builtin::BI__builtin_expect: {
2787 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2788 llvm::Type *ArgType = ArgValue->getType();
2789
2790 Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
2791 // Don't generate llvm.expect on -O0 as the backend won't use it for
2792 // anything.
2793 // Note, we still IRGen ExpectedValue because it could have side-effects.
2794 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2795 return RValue::get(ArgValue);
2796
2797 Function *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
2798 Value *Result =
2799 Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
2800 return RValue::get(Result);
2801 }
2802 case Builtin::BI__builtin_expect_with_probability: {
2803 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2804 llvm::Type *ArgType = ArgValue->getType();
2805
2806 Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
2807 llvm::APFloat Probability(0.0);
2808 const Expr *ProbArg = E->getArg(2);
2809 bool EvalSucceed = ProbArg->EvaluateAsFloat(Probability, CGM.getContext());
2810 assert(EvalSucceed && "probability should be able to evaluate as float")(static_cast <bool> (EvalSucceed && "probability should be able to evaluate as float"
) ? void (0) : __assert_fail ("EvalSucceed && \"probability should be able to evaluate as float\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 2810, __extension__ __PRETTY_FUNCTION__
))
;
2811 (void)EvalSucceed;
2812 bool LoseInfo = false;
2813 Probability.convert(llvm::APFloat::IEEEdouble(),
2814 llvm::RoundingMode::Dynamic, &LoseInfo);
2815 llvm::Type *Ty = ConvertType(ProbArg->getType());
2816 Constant *Confidence = ConstantFP::get(Ty, Probability);
2817 // Don't generate llvm.expect.with.probability on -O0 as the backend
2818 // won't use it for anything.
2819 // Note, we still IRGen ExpectedValue because it could have side-effects.
2820 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2821 return RValue::get(ArgValue);
2822
2823 Function *FnExpect =
2824 CGM.getIntrinsic(Intrinsic::expect_with_probability, ArgType);
2825 Value *Result = Builder.CreateCall(
2826 FnExpect, {ArgValue, ExpectedValue, Confidence}, "expval");
2827 return RValue::get(Result);
2828 }
2829 case Builtin::BI__builtin_assume_aligned: {
2830 const Expr *Ptr = E->getArg(0);
2831 Value *PtrValue = EmitScalarExpr(Ptr);
2832 Value *OffsetValue =
2833 (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
2834
2835 Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
2836 ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
2837 if (AlignmentCI->getValue().ugt(llvm::Value::MaximumAlignment))
2838 AlignmentCI = ConstantInt::get(AlignmentCI->getType(),
2839 llvm::Value::MaximumAlignment);
2840
2841 emitAlignmentAssumption(PtrValue, Ptr,
2842 /*The expr loc is sufficient.*/ SourceLocation(),
2843 AlignmentCI, OffsetValue);
2844 return RValue::get(PtrValue);
2845 }
2846 case Builtin::BI__assume:
2847 case Builtin::BI__builtin_assume: {
2848 if (E->getArg(0)->HasSideEffects(getContext()))
2849 return RValue::get(nullptr);
2850
2851 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2852 Function *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
2853 Builder.CreateCall(FnAssume, ArgValue);
2854 return RValue::get(nullptr);
2855 }
2856 case Builtin::BI__builtin_assume_separate_storage: {
2857 const Expr *Arg0 = E->getArg(0);
2858 const Expr *Arg1 = E->getArg(1);
2859
2860 Value *Value0 = EmitScalarExpr(Arg0);
2861 Value *Value1 = EmitScalarExpr(Arg1);
2862
2863 Value *Values[] = {Value0, Value1};
2864 OperandBundleDefT<Value *> OBD("separate_storage", Values);
2865 Builder.CreateAssumption(ConstantInt::getTrue(getLLVMContext()), {OBD});
2866 return RValue::get(nullptr);
2867 }
2868 case Builtin::BI__arithmetic_fence: {
2869 // Create the builtin call if FastMath is selected, and the target
2870 // supports the builtin, otherwise just return the argument.
2871 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2872 llvm::FastMathFlags FMF = Builder.getFastMathFlags();
2873 bool isArithmeticFenceEnabled =
2874 FMF.allowReassoc() &&
2875 getContext().getTargetInfo().checkArithmeticFenceSupported();
2876 QualType ArgType = E->getArg(0)->getType();
2877 if (ArgType->isComplexType()) {
2878 if (isArithmeticFenceEnabled) {
2879 QualType ElementType = ArgType->castAs<ComplexType>()->getElementType();
2880 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2881 Value *Real = Builder.CreateArithmeticFence(ComplexVal.first,
2882 ConvertType(ElementType));
2883 Value *Imag = Builder.CreateArithmeticFence(ComplexVal.second,
2884 ConvertType(ElementType));
2885 return RValue::getComplex(std::make_pair(Real, Imag));
2886 }
2887 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2888 Value *Real = ComplexVal.first;
2889 Value *Imag = ComplexVal.second;
2890 return RValue::getComplex(std::make_pair(Real, Imag));
2891 }
2892 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2893 if (isArithmeticFenceEnabled)
2894 return RValue::get(
2895 Builder.CreateArithmeticFence(ArgValue, ConvertType(ArgType)));
2896 return RValue::get(ArgValue);
2897 }
2898 case Builtin::BI__builtin_bswap16:
2899 case Builtin::BI__builtin_bswap32:
2900 case Builtin::BI__builtin_bswap64:
2901 case Builtin::BI_byteswap_ushort:
2902 case Builtin::BI_byteswap_ulong:
2903 case Builtin::BI_byteswap_uint64: {
2904 return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
2905 }
2906 case Builtin::BI__builtin_bitreverse8:
2907 case Builtin::BI__builtin_bitreverse16:
2908 case Builtin::BI__builtin_bitreverse32:
2909 case Builtin::BI__builtin_bitreverse64: {
2910 return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bitreverse));
2911 }
2912 case Builtin::BI__builtin_rotateleft8:
2913 case Builtin::BI__builtin_rotateleft16:
2914 case Builtin::BI__builtin_rotateleft32:
2915 case Builtin::BI__builtin_rotateleft64:
2916 case Builtin::BI_rotl8: // Microsoft variants of rotate left
2917 case Builtin::BI_rotl16:
2918 case Builtin::BI_rotl:
2919 case Builtin::BI_lrotl:
2920 case Builtin::BI_rotl64:
2921 return emitRotate(E, false);
2922
2923 case Builtin::BI__builtin_rotateright8:
2924 case Builtin::BI__builtin_rotateright16:
2925 case Builtin::BI__builtin_rotateright32:
2926 case Builtin::BI__builtin_rotateright64:
2927 case Builtin::BI_rotr8: // Microsoft variants of rotate right
2928 case Builtin::BI_rotr16:
2929 case Builtin::BI_rotr:
2930 case Builtin::BI_lrotr:
2931 case Builtin::BI_rotr64:
2932 return emitRotate(E, true);
2933
2934 case Builtin::BI__builtin_constant_p: {
2935 llvm::Type *ResultType = ConvertType(E->getType());
2936
2937 const Expr *Arg = E->getArg(0);
2938 QualType ArgType = Arg->getType();
2939 // FIXME: The allowance for Obj-C pointers and block pointers is historical
2940 // and likely a mistake.
2941 if (!ArgType->isIntegralOrEnumerationType() && !ArgType->isFloatingType() &&
2942 !ArgType->isObjCObjectPointerType() && !ArgType->isBlockPointerType())
2943 // Per the GCC documentation, only numeric constants are recognized after
2944 // inlining.
2945 return RValue::get(ConstantInt::get(ResultType, 0));
2946
2947 if (Arg->HasSideEffects(getContext()))
2948 // The argument is unevaluated, so be conservative if it might have
2949 // side-effects.
2950 return RValue::get(ConstantInt::get(ResultType, 0));
2951
2952 Value *ArgValue = EmitScalarExpr(Arg);
2953 if (ArgType->isObjCObjectPointerType()) {
2954 // Convert Objective-C objects to id because we cannot distinguish between
2955 // LLVM types for Obj-C classes as they are opaque.
2956 ArgType = CGM.getContext().getObjCIdType();
2957 ArgValue = Builder.CreateBitCast(ArgValue, ConvertType(ArgType));
2958 }
2959 Function *F =
2960 CGM.getIntrinsic(Intrinsic::is_constant, ConvertType(ArgType));
2961 Value *Result = Builder.CreateCall(F, ArgValue);
2962 if (Result->getType() != ResultType)
2963 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/false);
2964 return RValue::get(Result);
2965 }
2966 case Builtin::BI__builtin_dynamic_object_size:
2967 case Builtin::BI__builtin_object_size: {
2968 unsigned Type =
2969 E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
2970 auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
2971
2972 // We pass this builtin onto the optimizer so that it can figure out the
2973 // object size in more complex cases.
2974 bool IsDynamic = BuiltinID == Builtin::BI__builtin_dynamic_object_size;
2975 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
2976 /*EmittedE=*/nullptr, IsDynamic));
2977 }
2978 case Builtin::BI__builtin_prefetch: {
2979 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
2980 // FIXME: Technically these constants should of type 'int', yes?
2981 RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) :
2982 llvm::ConstantInt::get(Int32Ty, 0);
2983 Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) :
2984 llvm::ConstantInt::get(Int32Ty, 3);
2985 Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
2986 Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
2987 Builder.CreateCall(F, {Address, RW, Locality, Data});
2988 return RValue::get(nullptr);
2989 }
2990 case Builtin::BI__builtin_readcyclecounter: {
2991 Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
2992 return RValue::get(Builder.CreateCall(F));
2993 }
2994 case Builtin::BI__builtin___clear_cache: {
2995 Value *Begin = EmitScalarExpr(E->getArg(0));
2996 Value *End = EmitScalarExpr(E->getArg(1));
2997 Function *F = CGM.getIntrinsic(Intrinsic::clear_cache);
2998 return RValue::get(Builder.CreateCall(F, {Begin, End}));
2999 }
3000 case Builtin::BI__builtin_trap:
3001 EmitTrapCall(Intrinsic::trap);
3002 return RValue::get(nullptr);
3003 case Builtin::BI__debugbreak:
3004 EmitTrapCall(Intrinsic::debugtrap);
3005 return RValue::get(nullptr);
3006 case Builtin::BI__builtin_unreachable: {
3007 EmitUnreachable(E->getExprLoc());
3008
3009 // We do need to preserve an insertion point.
3010 EmitBlock(createBasicBlock("unreachable.cont"));
3011
3012 return RValue::get(nullptr);
3013 }
3014
3015 case Builtin::BI__builtin_powi:
3016 case Builtin::BI__builtin_powif:
3017 case Builtin::BI__builtin_powil: {
3018 llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
3019 llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
3020
3021 if (Builder.getIsFPConstrained()) {
3022 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3023 Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_powi,
3024 Src0->getType());
3025 return RValue::get(Builder.CreateConstrainedFPCall(F, { Src0, Src1 }));
3026 }
3027
3028 Function *F = CGM.getIntrinsic(Intrinsic::powi,
3029 { Src0->getType(), Src1->getType() });
3030 return RValue::get(Builder.CreateCall(F, { Src0, Src1 }));
3031 }
3032 case Builtin::BI__builtin_isgreater:
3033 case Builtin::BI__builtin_isgreaterequal:
3034 case Builtin::BI__builtin_isless:
3035 case Builtin::BI__builtin_islessequal:
3036 case Builtin::BI__builtin_islessgreater:
3037 case Builtin::BI__builtin_isunordered: {
3038 // Ordered comparisons: we know the arguments to these are matching scalar
3039 // floating point values.
3040 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3041 Value *LHS = EmitScalarExpr(E->getArg(0));
3042 Value *RHS = EmitScalarExpr(E->getArg(1));
3043
3044 switch (BuiltinID) {
3045 default: llvm_unreachable("Unknown ordered comparison")::llvm::llvm_unreachable_internal("Unknown ordered comparison"
, "clang/lib/CodeGen/CGBuiltin.cpp", 3045)
;
3046 case Builtin::BI__builtin_isgreater:
3047 LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
3048 break;
3049 case Builtin::BI__builtin_isgreaterequal:
3050 LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
3051 break;
3052 case Builtin::BI__builtin_isless:
3053 LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
3054 break;
3055 case Builtin::BI__builtin_islessequal:
3056 LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
3057 break;
3058 case Builtin::BI__builtin_islessgreater:
3059 LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
3060 break;
3061 case Builtin::BI__builtin_isunordered:
3062 LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
3063 break;
3064 }
3065 // ZExt bool to int type.
3066 return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
3067 }
3068 case Builtin::BI__builtin_isnan: {
3069 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3070 Value *V = EmitScalarExpr(E->getArg(0));
3071 llvm::Type *Ty = V->getType();
3072 const llvm::fltSemantics &Semantics = Ty->getFltSemantics();
3073 if (!Builder.getIsFPConstrained() ||
3074 Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
3075 !Ty->isIEEE()) {
3076 V = Builder.CreateFCmpUNO(V, V, "cmp");
3077 return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3078 }
3079
3080 if (Value *Result = getTargetHooks().testFPKind(V, BuiltinID, Builder, CGM))
3081 return RValue::get(Result);
3082
3083 // NaN has all exp bits set and a non zero significand. Therefore:
3084 // isnan(V) == ((exp mask - (abs(V) & exp mask)) < 0)
3085 unsigned bitsize = Ty->getScalarSizeInBits();
3086 llvm::IntegerType *IntTy = Builder.getIntNTy(bitsize);
3087 Value *IntV = Builder.CreateBitCast(V, IntTy);
3088 APInt AndMask = APInt::getSignedMaxValue(bitsize);
3089 Value *AbsV =
3090 Builder.CreateAnd(IntV, llvm::ConstantInt::get(IntTy, AndMask));
3091 APInt ExpMask = APFloat::getInf(Semantics).bitcastToAPInt();
3092 Value *Sub =
3093 Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
3094 // V = sign bit (Sub) <=> V = (Sub < 0)
3095 V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));
3096 if (bitsize > 32)
3097 V = Builder.CreateTrunc(V, ConvertType(E->getType()));
3098 return RValue::get(V);
3099 }
3100
3101 case Builtin::BI__builtin_nondeterministic_value: {
3102 llvm::Type *Ty = ConvertType(E->getArg(0)->getType());
3103
3104 Value *Result = PoisonValue::get(Ty);
3105 Result = Builder.CreateFreeze(Result);
3106
3107 return RValue::get(Result);
3108 }
3109
3110 case Builtin::BI__builtin_elementwise_abs: {
3111 Value *Result;
3112 QualType QT = E->getArg(0)->getType();
3113
3114 if (auto *VecTy = QT->getAs<VectorType>())
3115 QT = VecTy->getElementType();
3116 if (QT->isIntegerType())
3117 Result = Builder.CreateBinaryIntrinsic(
3118 llvm::Intrinsic::abs, EmitScalarExpr(E->getArg(0)),
3119 Builder.getFalse(), nullptr, "elt.abs");
3120 else
3121 Result = emitUnaryBuiltin(*this, E, llvm::Intrinsic::fabs, "elt.abs");
3122
3123 return RValue::get(Result);
3124 }
3125
3126 case Builtin::BI__builtin_elementwise_ceil:
3127 return RValue::get(
3128 emitUnaryBuiltin(*this, E, llvm::Intrinsic::ceil, "elt.ceil"));
3129 case Builtin::BI__builtin_elementwise_exp:
3130 return RValue::get(
3131 emitUnaryBuiltin(*this, E, llvm::Intrinsic::exp, "elt.exp"));
3132 case Builtin::BI__builtin_elementwise_exp2:
3133 return RValue::get(
3134 emitUnaryBuiltin(*this, E, llvm::Intrinsic::exp2, "elt.exp2"));
3135 case Builtin::BI__builtin_elementwise_log:
3136 return RValue::get(
3137 emitUnaryBuiltin(*this, E, llvm::Intrinsic::log, "elt.log"));
3138 case Builtin::BI__builtin_elementwise_log2:
3139 return RValue::get(
3140 emitUnaryBuiltin(*this, E, llvm::Intrinsic::log2, "elt.log2"));
3141 case Builtin::BI__builtin_elementwise_log10:
3142 return RValue::get(
3143 emitUnaryBuiltin(*this, E, llvm::Intrinsic::log10, "elt.log10"));
3144 case Builtin::BI__builtin_elementwise_cos:
3145 return RValue::get(
3146 emitUnaryBuiltin(*this, E, llvm::Intrinsic::cos, "elt.cos"));
3147 case Builtin::BI__builtin_elementwise_floor:
3148 return RValue::get(
3149 emitUnaryBuiltin(*this, E, llvm::Intrinsic::floor, "elt.floor"));
3150 case Builtin::BI__builtin_elementwise_roundeven:
3151 return RValue::get(emitUnaryBuiltin(*this, E, llvm::Intrinsic::roundeven,
3152 "elt.roundeven"));
3153 case Builtin::BI__builtin_elementwise_sin:
3154 return RValue::get(
3155 emitUnaryBuiltin(*this, E, llvm::Intrinsic::sin, "elt.sin"));
3156
3157 case Builtin::BI__builtin_elementwise_trunc:
3158 return RValue::get(
3159 emitUnaryBuiltin(*this, E, llvm::Intrinsic::trunc, "elt.trunc"));
3160 case Builtin::BI__builtin_elementwise_canonicalize:
3161 return RValue::get(
3162 emitUnaryBuiltin(*this, E, llvm::Intrinsic::canonicalize, "elt.trunc"));
3163 case Builtin::BI__builtin_elementwise_copysign:
3164 return RValue::get(emitBinaryBuiltin(*this, E, llvm::Intrinsic::copysign));
3165 case Builtin::BI__builtin_elementwise_fma:
3166 return RValue::get(emitTernaryBuiltin(*this, E, llvm::Intrinsic::fma));
3167 case Builtin::BI__builtin_elementwise_add_sat:
3168 case Builtin::BI__builtin_elementwise_sub_sat: {
3169 Value *Op0 = EmitScalarExpr(E->getArg(0));
3170 Value *Op1 = EmitScalarExpr(E->getArg(1));
3171 Value *Result;
3172 assert(Op0->getType()->isIntOrIntVectorTy() && "integer type expected")(static_cast <bool> (Op0->getType()->isIntOrIntVectorTy
() && "integer type expected") ? void (0) : __assert_fail
("Op0->getType()->isIntOrIntVectorTy() && \"integer type expected\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3172, __extension__ __PRETTY_FUNCTION__
))
;
3173 QualType Ty = E->getArg(0)->getType();
3174 if (auto *VecTy = Ty->getAs<VectorType>())
3175 Ty = VecTy->getElementType();
3176 bool IsSigned = Ty->isSignedIntegerType();
3177 unsigned Opc;
3178 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_add_sat)
3179 Opc = IsSigned ? llvm::Intrinsic::sadd_sat : llvm::Intrinsic::uadd_sat;
3180 else
3181 Opc = IsSigned ? llvm::Intrinsic::ssub_sat : llvm::Intrinsic::usub_sat;
3182 Result = Builder.CreateBinaryIntrinsic(Opc, Op0, Op1, nullptr, "elt.sat");
3183 return RValue::get(Result);
3184 }
3185
3186 case Builtin::BI__builtin_elementwise_max: {
3187 Value *Op0 = EmitScalarExpr(E->getArg(0));
3188 Value *Op1 = EmitScalarExpr(E->getArg(1));
3189 Value *Result;
3190 if (Op0->getType()->isIntOrIntVectorTy()) {
3191 QualType Ty = E->getArg(0)->getType();
3192 if (auto *VecTy = Ty->getAs<VectorType>())
3193 Ty = VecTy->getElementType();
3194 Result = Builder.CreateBinaryIntrinsic(Ty->isSignedIntegerType()
3195 ? llvm::Intrinsic::smax
3196 : llvm::Intrinsic::umax,
3197 Op0, Op1, nullptr, "elt.max");
3198 } else
3199 Result = Builder.CreateMaxNum(Op0, Op1, "elt.max");
3200 return RValue::get(Result);
3201 }
3202 case Builtin::BI__builtin_elementwise_min: {
3203 Value *Op0 = EmitScalarExpr(E->getArg(0));
3204 Value *Op1 = EmitScalarExpr(E->getArg(1));
3205 Value *Result;
3206 if (Op0->getType()->isIntOrIntVectorTy()) {
3207 QualType Ty = E->getArg(0)->getType();
3208 if (auto *VecTy = Ty->getAs<VectorType>())
3209 Ty = VecTy->getElementType();
3210 Result = Builder.CreateBinaryIntrinsic(Ty->isSignedIntegerType()
3211 ? llvm::Intrinsic::smin
3212 : llvm::Intrinsic::umin,
3213 Op0, Op1, nullptr, "elt.min");
3214 } else
3215 Result = Builder.CreateMinNum(Op0, Op1, "elt.min");
3216 return RValue::get(Result);
3217 }
3218
3219 case Builtin::BI__builtin_reduce_max: {
3220 auto GetIntrinsicID = [](QualType QT) {
3221 if (auto *VecTy = QT->getAs<VectorType>())
3222 QT = VecTy->getElementType();
3223 if (QT->isSignedIntegerType())
3224 return llvm::Intrinsic::vector_reduce_smax;
3225 if (QT->isUnsignedIntegerType())
3226 return llvm::Intrinsic::vector_reduce_umax;
3227 assert(QT->isFloatingType() && "must have a float here")(static_cast <bool> (QT->isFloatingType() &&
"must have a float here") ? void (0) : __assert_fail ("QT->isFloatingType() && \"must have a float here\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3227, __extension__ __PRETTY_FUNCTION__
))
;
3228 return llvm::Intrinsic::vector_reduce_fmax;
3229 };
3230 return RValue::get(emitUnaryBuiltin(
3231 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
3232 }
3233
3234 case Builtin::BI__builtin_reduce_min: {
3235 auto GetIntrinsicID = [](QualType QT) {
3236 if (auto *VecTy = QT->getAs<VectorType>())
3237 QT = VecTy->getElementType();
3238 if (QT->isSignedIntegerType())
3239 return llvm::Intrinsic::vector_reduce_smin;
3240 if (QT->isUnsignedIntegerType())
3241 return llvm::Intrinsic::vector_reduce_umin;
3242 assert(QT->isFloatingType() && "must have a float here")(static_cast <bool> (QT->isFloatingType() &&
"must have a float here") ? void (0) : __assert_fail ("QT->isFloatingType() && \"must have a float here\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3242, __extension__ __PRETTY_FUNCTION__
))
;
3243 return llvm::Intrinsic::vector_reduce_fmin;
3244 };
3245
3246 return RValue::get(emitUnaryBuiltin(
3247 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
3248 }
3249
3250 case Builtin::BI__builtin_reduce_add:
3251 return RValue::get(emitUnaryBuiltin(
3252 *this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
3253 case Builtin::BI__builtin_reduce_mul:
3254 return RValue::get(emitUnaryBuiltin(
3255 *this, E, llvm::Intrinsic::vector_reduce_mul, "rdx.mul"));
3256 case Builtin::BI__builtin_reduce_xor:
3257 return RValue::get(emitUnaryBuiltin(
3258 *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
3259 case Builtin::BI__builtin_reduce_or:
3260 return RValue::get(emitUnaryBuiltin(
3261 *this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
3262 case Builtin::BI__builtin_reduce_and:
3263 return RValue::get(emitUnaryBuiltin(
3264 *this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
3265
3266 case Builtin::BI__builtin_matrix_transpose: {
3267 auto *MatrixTy = E->getArg(0)->getType()->castAs<ConstantMatrixType>();
3268 Value *MatValue = EmitScalarExpr(E->getArg(0));
3269 MatrixBuilder MB(Builder);
3270 Value *Result = MB.CreateMatrixTranspose(MatValue, MatrixTy->getNumRows(),
3271 MatrixTy->getNumColumns());
3272 return RValue::get(Result);
3273 }
3274
3275 case Builtin::BI__builtin_matrix_column_major_load: {
3276 MatrixBuilder MB(Builder);
3277 // Emit everything that isn't dependent on the first parameter type
3278 Value *Stride = EmitScalarExpr(E->getArg(3));
3279 const auto *ResultTy = E->getType()->getAs<ConstantMatrixType>();
3280 auto *PtrTy = E->getArg(0)->getType()->getAs<PointerType>();
3281 assert(PtrTy && "arg0 must be of pointer type")(static_cast <bool> (PtrTy && "arg0 must be of pointer type"
) ? void (0) : __assert_fail ("PtrTy && \"arg0 must be of pointer type\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3281, __extension__ __PRETTY_FUNCTION__
))
;
3282 bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
3283
3284 Address Src = EmitPointerWithAlignment(E->getArg(0));
3285 EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(0)->getType(),
3286 E->getArg(0)->getExprLoc(), FD, 0);
3287 Value *Result = MB.CreateColumnMajorLoad(
3288 Src.getElementType(), Src.getPointer(),
3289 Align(Src.getAlignment().getQuantity()), Stride, IsVolatile,
3290 ResultTy->getNumRows(), ResultTy->getNumColumns(),
3291 "matrix");
3292 return RValue::get(Result);
3293 }
3294
3295 case Builtin::BI__builtin_matrix_column_major_store: {
3296 MatrixBuilder MB(Builder);
3297 Value *Matrix = EmitScalarExpr(E->getArg(0));
3298 Address Dst = EmitPointerWithAlignment(E->getArg(1));
3299 Value *Stride = EmitScalarExpr(E->getArg(2));
3300
3301 const auto *MatrixTy = E->getArg(0)->getType()->getAs<ConstantMatrixType>();
3302 auto *PtrTy = E->getArg(1)->getType()->getAs<PointerType>();
3303 assert(PtrTy && "arg1 must be of pointer type")(static_cast <bool> (PtrTy && "arg1 must be of pointer type"
) ? void (0) : __assert_fail ("PtrTy && \"arg1 must be of pointer type\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3303, __extension__ __PRETTY_FUNCTION__
))
;
3304 bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
3305
3306 EmitNonNullArgCheck(RValue::get(Dst.getPointer()), E->getArg(1)->getType(),
3307 E->getArg(1)->getExprLoc(), FD, 0);
3308 Value *Result = MB.CreateColumnMajorStore(
3309 Matrix, Dst.getPointer(), Align(Dst.getAlignment().getQuantity()),
3310 Stride, IsVolatile, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
3311 return RValue::get(Result);
3312 }
3313
3314 case Builtin::BIfinite:
3315 case Builtin::BI__finite:
3316 case Builtin::BIfinitef:
3317 case Builtin::BI__finitef:
3318 case Builtin::BIfinitel:
3319 case Builtin::BI__finitel:
3320 case Builtin::BI__builtin_isinf:
3321 case Builtin::BI__builtin_isfinite: {
3322 // isinf(x) --> fabs(x) == infinity
3323 // isfinite(x) --> fabs(x) != infinity
3324 // x != NaN via the ordered compare in either case.
3325 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3326 Value *V = EmitScalarExpr(E->getArg(0));
3327 llvm::Type *Ty = V->getType();
3328 if (!Builder.getIsFPConstrained() ||
3329 Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
3330 !Ty->isIEEE()) {
3331 Value *Fabs = EmitFAbs(*this, V);
3332 Constant *Infinity = ConstantFP::getInfinity(V->getType());
3333 CmpInst::Predicate Pred = (BuiltinID == Builtin::BI__builtin_isinf)
3334 ? CmpInst::FCMP_OEQ
3335 : CmpInst::FCMP_ONE;
3336 Value *FCmp = Builder.CreateFCmp(Pred, Fabs, Infinity, "cmpinf");
3337 return RValue::get(Builder.CreateZExt(FCmp, ConvertType(E->getType())));
3338 }
3339
3340 if (Value *Result = getTargetHooks().testFPKind(V, BuiltinID, Builder, CGM))
3341 return RValue::get(Result);
3342
3343 // Inf values have all exp bits set and a zero significand. Therefore:
3344 // isinf(V) == ((V << 1) == ((exp mask) << 1))
3345 // isfinite(V) == ((V << 1) < ((exp mask) << 1)) using unsigned comparison
3346 unsigned bitsize = Ty->getScalarSizeInBits();
3347 llvm::IntegerType *IntTy = Builder.getIntNTy(bitsize);
3348 Value *IntV = Builder.CreateBitCast(V, IntTy);
3349 Value *Shl1 = Builder.CreateShl(IntV, 1);
3350 const llvm::fltSemantics &Semantics = Ty->getFltSemantics();
3351 APInt ExpMask = APFloat::getInf(Semantics).bitcastToAPInt();
3352 Value *ExpMaskShl1 = llvm::ConstantInt::get(IntTy, ExpMask.shl(1));
3353 if (BuiltinID == Builtin::BI__builtin_isinf)
3354 V = Builder.CreateICmpEQ(Shl1, ExpMaskShl1);
3355 else
3356 V = Builder.CreateICmpULT(Shl1, ExpMaskShl1);
3357 return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3358 }
3359
3360 case Builtin::BI__builtin_isinf_sign: {
3361 // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
3362 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3363 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3364 Value *Arg = EmitScalarExpr(E->getArg(0));
3365 Value *AbsArg = EmitFAbs(*this, Arg);
3366 Value *IsInf = Builder.CreateFCmpOEQ(
3367 AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
3368 Value *IsNeg = EmitSignBit(*this, Arg);
3369
3370 llvm::Type *IntTy = ConvertType(E->getType());
3371 Value *Zero = Constant::getNullValue(IntTy);
3372 Value *One = ConstantInt::get(IntTy, 1);
3373 Value *NegativeOne = ConstantInt::get(IntTy, -1);
3374 Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
3375 Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
3376 return RValue::get(Result);
3377 }
3378
3379 case Builtin::BI__builtin_isnormal: {
3380 // isnormal(x) --> x == x && fabsf(x) < infinity && fabsf(x) >= float_min
3381 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3382 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3383 Value *V = EmitScalarExpr(E->getArg(0));
3384 Value *Eq = Builder.CreateFCmpOEQ(V, V, "iseq");
3385
3386 Value *Abs = EmitFAbs(*this, V);
3387 Value *IsLessThanInf =
3388 Builder.CreateFCmpULT(Abs, ConstantFP::getInfinity(V->getType()),"isinf");
3389 APFloat Smallest = APFloat::getSmallestNormalized(
3390 getContext().getFloatTypeSemantics(E->getArg(0)->getType()));
3391 Value *IsNormal =
3392 Builder.CreateFCmpUGE(Abs, ConstantFP::get(V->getContext(), Smallest),
3393 "isnormal");
3394 V = Builder.CreateAnd(Eq, IsLessThanInf, "and");
3395 V = Builder.CreateAnd(V, IsNormal, "and");
3396 return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3397 }
3398
3399 case Builtin::BI__builtin_flt_rounds: {
3400 Function *F = CGM.getIntrinsic(Intrinsic::get_rounding);
3401
3402 llvm::Type *ResultType = ConvertType(E->getType());
3403 Value *Result = Builder.CreateCall(F);
3404 if (Result->getType() != ResultType)
3405 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3406 "cast");
3407 return RValue::get(Result);
3408 }
3409
3410 case Builtin::BI__builtin_set_flt_rounds: {
3411 Function *F = CGM.getIntrinsic(Intrinsic::set_rounding);
3412
3413 Value *V = EmitScalarExpr(E->getArg(0));
3414 Builder.CreateCall(F, V);
3415 return RValue::get(nullptr);
3416 }
3417
3418 case Builtin::BI__builtin_fpclassify: {
3419 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3420 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3421 Value *V = EmitScalarExpr(E->getArg(5));
3422 llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
3423
3424 // Create Result
3425 BasicBlock *Begin = Builder.GetInsertBlock();
3426 BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
3427 Builder.SetInsertPoint(End);
3428 PHINode *Result =
3429 Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
3430 "fpclassify_result");
3431
3432 // if (V==0) return FP_ZERO
3433 Builder.SetInsertPoint(Begin);
3434 Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
3435 "iszero");
3436 Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
3437 BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
3438 Builder.CreateCondBr(IsZero, End, NotZero);
3439 Result->addIncoming(ZeroLiteral, Begin);
3440
3441 // if (V != V) return FP_NAN
3442 Builder.SetInsertPoint(NotZero);
3443 Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
3444 Value *NanLiteral = EmitScalarExpr(E->getArg(0));
3445 BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
3446 Builder.CreateCondBr(IsNan, End, NotNan);
3447 Result->addIncoming(NanLiteral, NotZero);
3448
3449 // if (fabs(V) == infinity) return FP_INFINITY
3450 Builder.SetInsertPoint(NotNan);
3451 Value *VAbs = EmitFAbs(*this, V);
3452 Value *IsInf =
3453 Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
3454 "isinf");
3455 Value *InfLiteral = EmitScalarExpr(E->getArg(1));
3456 BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
3457 Builder.CreateCondBr(IsInf, End, NotInf);
3458 Result->addIncoming(InfLiteral, NotNan);
3459
3460 // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
3461 Builder.SetInsertPoint(NotInf);
3462 APFloat Smallest = APFloat::getSmallestNormalized(
3463 getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
3464 Value *IsNormal =
3465 Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
3466 "isnormal");
3467 Value *NormalResult =
3468 Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
3469 EmitScalarExpr(E->getArg(3)));
3470 Builder.CreateBr(End);
3471 Result->addIncoming(NormalResult, NotInf);
3472
3473 // return Result
3474 Builder.SetInsertPoint(End);
3475 return RValue::get(Result);
3476 }
3477
3478 case Builtin::BIalloca:
3479 case Builtin::BI_alloca:
3480 case Builtin::BI__builtin_alloca_uninitialized:
3481 case Builtin::BI__builtin_alloca: {
3482 Value *Size = EmitScalarExpr(E->getArg(0));
3483 const TargetInfo &TI = getContext().getTargetInfo();
3484 // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
3485 const Align SuitableAlignmentInBytes =
3486 CGM.getContext()
3487 .toCharUnitsFromBits(TI.getSuitableAlign())
3488 .getAsAlign();
3489 AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
3490 AI->setAlignment(SuitableAlignmentInBytes);
3491 if (BuiltinID != Builtin::BI__builtin_alloca_uninitialized)
3492 initializeAlloca(*this, AI, Size, SuitableAlignmentInBytes);
3493 return RValue::get(AI);
3494 }
3495
3496 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3497 case Builtin::BI__builtin_alloca_with_align: {
3498 Value *Size = EmitScalarExpr(E->getArg(0));
3499 Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
3500 auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
3501 unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
3502 const Align AlignmentInBytes =
3503 CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getAsAlign();
3504 AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
3505 AI->setAlignment(AlignmentInBytes);
3506 if (BuiltinID != Builtin::BI__builtin_alloca_with_align_uninitialized)
3507 initializeAlloca(*this, AI, Size, AlignmentInBytes);
3508 return RValue::get(AI);
3509 }
3510
3511 case Builtin::BIbzero:
3512 case Builtin::BI__builtin_bzero: {
3513 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3514 Value *SizeVal = EmitScalarExpr(E->getArg(1));
3515 EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3516 E->getArg(0)->getExprLoc(), FD, 0);
3517 Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
3518 return RValue::get(nullptr);
3519 }
3520 case Builtin::BImemcpy:
3521 case Builtin::BI__builtin_memcpy:
3522 case Builtin::BImempcpy:
3523 case Builtin::BI__builtin_mempcpy: {
3524 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3525 Address Src = EmitPointerWithAlignment(E->getArg(1));
3526 Value *SizeVal = EmitScalarExpr(E->getArg(2));
3527 EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3528 E->getArg(0)->getExprLoc(), FD, 0);
3529 EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3530 E->getArg(1)->getExprLoc(), FD, 1);
3531 Builder.CreateMemCpy(Dest, Src, SizeVal, false);
3532 if (BuiltinID == Builtin::BImempcpy ||
3533 BuiltinID == Builtin::BI__builtin_mempcpy)
3534 return RValue::get(Builder.CreateInBoundsGEP(Dest.getElementType(),
3535 Dest.getPointer(), SizeVal));
3536 else
3537 return RValue::get(Dest.getPointer());
3538 }
3539
3540 case Builtin::BI__builtin_memcpy_inline: {
3541 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3542 Address Src = EmitPointerWithAlignment(E->getArg(1));
3543 uint64_t Size =
3544 E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
3545 EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3546 E->getArg(0)->getExprLoc(), FD, 0);
3547 EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3548 E->getArg(1)->getExprLoc(), FD, 1);
3549 Builder.CreateMemCpyInline(Dest, Src, Size);
3550 return RValue::get(nullptr);
3551 }
3552
3553 case Builtin::BI__builtin_char_memchr:
3554 BuiltinID = Builtin::BI__builtin_memchr;
3555 break;
3556
3557 case Builtin::BI__builtin___memcpy_chk: {
3558 // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
3559 Expr::EvalResult SizeResult, DstSizeResult;
3560 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3561 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3562 break;
3563 llvm::APSInt Size = SizeResult.Val.getInt();
3564 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3565 if (Size.ugt(DstSize))
3566 break;
3567 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3568 Address Src = EmitPointerWithAlignment(E->getArg(1));
3569 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3570 Builder.CreateMemCpy(Dest, Src, SizeVal, false);
3571 return RValue::get(Dest.getPointer());
3572 }
3573
3574 case Builtin::BI__builtin_objc_memmove_collectable: {
3575 Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
3576 Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
3577 Value *SizeVal = EmitScalarExpr(E->getArg(2));
3578 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
3579 DestAddr, SrcAddr, SizeVal);
3580 return RValue::get(DestAddr.getPointer());
3581 }
3582
3583 case Builtin::BI__builtin___memmove_chk: {
3584 // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
3585 Expr::EvalResult SizeResult, DstSizeResult;
3586 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3587 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3588 break;
3589 llvm::APSInt Size = SizeResult.Val.getInt();
3590 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3591 if (Size.ugt(DstSize))
3592 break;
3593 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3594 Address Src = EmitPointerWithAlignment(E->getArg(1));
3595 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3596 Builder.CreateMemMove(Dest, Src, SizeVal, false);
3597 return RValue::get(Dest.getPointer());
3598 }
3599
3600 case Builtin::BImemmove:
3601 case Builtin::BI__builtin_memmove: {
3602 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3603 Address Src = EmitPointerWithAlignment(E->getArg(1));
3604 Value *SizeVal = EmitScalarExpr(E->getArg(2));
3605 EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3606 E->getArg(0)->getExprLoc(), FD, 0);
3607 EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3608 E->getArg(1)->getExprLoc(), FD, 1);
3609 Builder.CreateMemMove(Dest, Src, SizeVal, false);
3610 return RValue::get(Dest.getPointer());
3611 }
3612 case Builtin::BImemset:
3613 case Builtin::BI__builtin_memset: {
3614 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3615 Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
3616 Builder.getInt8Ty());
3617 Value *SizeVal = EmitScalarExpr(E->getArg(2));
3618 EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3619 E->getArg(0)->getExprLoc(), FD, 0);
3620 Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
3621 return RValue::get(Dest.getPointer());
3622 }
3623 case Builtin::BI__builtin_memset_inline: {
3624 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3625 Value *ByteVal =
3626 Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)), Builder.getInt8Ty());
3627 uint64_t Size =
3628 E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
3629 EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3630 E->getArg(0)->getExprLoc(), FD, 0);
3631 Builder.CreateMemSetInline(Dest, ByteVal, Size);
3632 return RValue::get(nullptr);
3633 }
3634 case Builtin::BI__builtin___memset_chk: {
3635 // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
3636 Expr::EvalResult SizeResult, DstSizeResult;
3637 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3638 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3639 break;
3640 llvm::APSInt Size = SizeResult.Val.getInt();
3641 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3642 if (Size.ugt(DstSize))
3643 break;
3644 Address Dest = EmitPointerWithAlignment(E->getArg(0));
3645 Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
3646 Builder.getInt8Ty());
3647 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3648 Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
3649 return RValue::get(Dest.getPointer());
3650 }
3651 case Builtin::BI__builtin_wmemchr: {
3652 // The MSVC runtime library does not provide a definition of wmemchr, so we
3653 // need an inline implementation.
3654 if (!getTarget().getTriple().isOSMSVCRT())
3655 break;
3656
3657 llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
3658 Value *Str = EmitScalarExpr(E->getArg(0));
3659 Value *Chr = EmitScalarExpr(E->getArg(1));
3660 Value *Size = EmitScalarExpr(E->getArg(2));
3661
3662 BasicBlock *Entry = Builder.GetInsertBlock();
3663 BasicBlock *CmpEq = createBasicBlock("wmemchr.eq");
3664 BasicBlock *Next = createBasicBlock("wmemchr.next");
3665 BasicBlock *Exit = createBasicBlock("wmemchr.exit");
3666 Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
3667 Builder.CreateCondBr(SizeEq0, Exit, CmpEq);
3668
3669 EmitBlock(CmpEq);
3670 PHINode *StrPhi = Builder.CreatePHI(Str->getType(), 2);
3671 StrPhi->addIncoming(Str, Entry);
3672 PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
3673 SizePhi->addIncoming(Size, Entry);
3674 CharUnits WCharAlign =
3675 getContext().getTypeAlignInChars(getContext().WCharTy);
3676 Value *StrCh = Builder.CreateAlignedLoad(WCharTy, StrPhi, WCharAlign);
3677 Value *FoundChr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 0);
3678 Value *StrEqChr = Builder.CreateICmpEQ(StrCh, Chr);
3679 Builder.CreateCondBr(StrEqChr, Exit, Next);
3680
3681 EmitBlock(Next);
3682 Value *NextStr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 1);
3683 Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
3684 Value *NextSizeEq0 =
3685 Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
3686 Builder.CreateCondBr(NextSizeEq0, Exit, CmpEq);
3687 StrPhi->addIncoming(NextStr, Next);
3688 SizePhi->addIncoming(NextSize, Next);
3689
3690 EmitBlock(Exit);
3691 PHINode *Ret = Builder.CreatePHI(Str->getType(), 3);
3692 Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Entry);
3693 Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Next);
3694 Ret->addIncoming(FoundChr, CmpEq);
3695 return RValue::get(Ret);
3696 }
3697 case Builtin::BI__builtin_wmemcmp: {
3698 // The MSVC runtime library does not provide a definition of wmemcmp, so we
3699 // need an inline implementation.
3700 if (!getTarget().getTriple().isOSMSVCRT())
3701 break;
3702
3703 llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
3704
3705 Value *Dst = EmitScalarExpr(E->getArg(0));
3706 Value *Src = EmitScalarExpr(E->getArg(1));
3707 Value *Size = EmitScalarExpr(E->getArg(2));
3708
3709 BasicBlock *Entry = Builder.GetInsertBlock();
3710 BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
3711 BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
3712 BasicBlock *Next = createBasicBlock("wmemcmp.next");
3713 BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
3714 Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
3715 Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
3716
3717 EmitBlock(CmpGT);
3718 PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
3719 DstPhi->addIncoming(Dst, Entry);
3720 PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
3721 SrcPhi->addIncoming(Src, Entry);
3722 PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
3723 SizePhi->addIncoming(Size, Entry);
3724 CharUnits WCharAlign =
3725 getContext().getTypeAlignInChars(getContext().WCharTy);
3726 Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
3727 Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
3728 Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
3729 Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
3730
3731 EmitBlock(CmpLT);
3732 Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
3733 Builder.CreateCondBr(DstLtSrc, Exit, Next);
3734
3735 EmitBlock(Next);
3736 Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
3737 Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
3738 Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
3739 Value *NextSizeEq0 =
3740 Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
3741 Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
3742 DstPhi->addIncoming(NextDst, Next);
3743 SrcPhi->addIncoming(NextSrc, Next);
3744 SizePhi->addIncoming(NextSize, Next);
3745
3746 EmitBlock(Exit);
3747 PHINode *Ret = Builder.CreatePHI(IntTy, 4);
3748 Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
3749 Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
3750 Ret->addIncoming(ConstantInt::get(IntTy, -1), CmpLT);
3751 Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
3752 return RValue::get(Ret);
3753 }
3754 case Builtin::BI__builtin_dwarf_cfa: {
3755 // The offset in bytes from the first argument to the CFA.
3756 //
3757 // Why on earth is this in the frontend? Is there any reason at
3758 // all that the backend can't reasonably determine this while
3759 // lowering llvm.eh.dwarf.cfa()?
3760 //
3761 // TODO: If there's a satisfactory reason, add a target hook for
3762 // this instead of hard-coding 0, which is correct for most targets.
3763 int32_t Offset = 0;
3764
3765 Function *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
3766 return RValue::get(Builder.CreateCall(F,
3767 llvm::ConstantInt::get(Int32Ty, Offset)));
3768 }
3769 case Builtin::BI__builtin_return_address: {
3770 Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
3771 getContext().UnsignedIntTy);
3772 Function *F = CGM.getIntrinsic(Intrinsic::returnaddress);
3773 return RValue::get(Builder.CreateCall(F, Depth));
3774 }
3775 case Builtin::BI_ReturnAddress: {
3776 Function *F = CGM.getIntrinsic(Intrinsic::returnaddress);
3777 return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
3778 }
3779 case Builtin::BI__builtin_frame_address: {
3780 Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
3781 getContext().UnsignedIntTy);
3782 Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
3783 return RValue::get(Builder.CreateCall(F, Depth));
3784 }
3785 case Builtin::BI__builtin_extract_return_addr: {
3786 Value *Address = EmitScalarExpr(E->getArg(0));
3787 Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
3788 return RValue::get(Result);
3789 }
3790 case Builtin::BI__builtin_frob_return_addr: {
3791 Value *Address = EmitScalarExpr(E->getArg(0));
3792 Value *Result = getTargetHooks().encodeReturnAddress(*this, Address);
3793 return RValue::get(Result);
3794 }
3795 case Builtin::BI__builtin_dwarf_sp_column: {
3796 llvm::IntegerType *Ty
3797 = cast<llvm::IntegerType>(ConvertType(E->getType()));
3798 int Column = getTargetHooks().getDwarfEHStackPointer(CGM);
3799 if (Column == -1) {
3800 CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
3801 return RValue::get(llvm::UndefValue::get(Ty));
3802 }
3803 return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
3804 }
3805 case Builtin::BI__builtin_init_dwarf_reg_size_table: {
3806 Value *Address = EmitScalarExpr(E->getArg(0));
3807 if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
3808 CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
3809 return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
3810 }
3811 case Builtin::BI__builtin_eh_return: {
3812 Value *Int = EmitScalarExpr(E->getArg(0));
3813 Value *Ptr = EmitScalarExpr(E->getArg(1));
3814
3815 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
3816 assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&(static_cast <bool> ((IntTy->getBitWidth() == 32 || IntTy
->getBitWidth() == 64) && "LLVM's __builtin_eh_return only supports 32- and 64-bit variants"
) ? void (0) : __assert_fail ("(IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) && \"LLVM's __builtin_eh_return only supports 32- and 64-bit variants\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3817, __extension__ __PRETTY_FUNCTION__
))
3817 "LLVM's __builtin_eh_return only supports 32- and 64-bit variants")(static_cast <bool> ((IntTy->getBitWidth() == 32 || IntTy
->getBitWidth() == 64) && "LLVM's __builtin_eh_return only supports 32- and 64-bit variants"
) ? void (0) : __assert_fail ("(IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) && \"LLVM's __builtin_eh_return only supports 32- and 64-bit variants\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 3817, __extension__ __PRETTY_FUNCTION__
))
;
3818 Function *F =
3819 CGM.getIntrinsic(IntTy->getBitWidth() == 32 ? Intrinsic::eh_return_i32
3820 : Intrinsic::eh_return_i64);
3821 Builder.CreateCall(F, {Int, Ptr});
3822 Builder.CreateUnreachable();
3823
3824 // We do need to preserve an insertion point.
3825 EmitBlock(createBasicBlock("builtin_eh_return.cont"));
3826
3827 return RValue::get(nullptr);
3828 }
3829 case Builtin::BI__builtin_unwind_init: {
3830 Function *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
3831 Builder.CreateCall(F);
3832 return RValue::get(nullptr);
3833 }
3834 case Builtin::BI__builtin_extend_pointer: {
3835 // Extends a pointer to the size of an _Unwind_Word, which is
3836 // uint64_t on all platforms. Generally this gets poked into a
3837 // register and eventually used as an address, so if the
3838 // addressing registers are wider than pointers and the platform
3839 // doesn't implicitly ignore high-order bits when doing
3840 // addressing, we need to make sure we zext / sext based on
3841 // the platform's expectations.
3842 //
3843 // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
3844
3845 // Cast the pointer to intptr_t.
3846 Value *Ptr = EmitScalarExpr(E->getArg(0));
3847 Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
3848
3849 // If that's 64 bits, we're done.
3850 if (IntPtrTy->getBitWidth() == 64)
3851 return RValue::get(Result);
3852
3853 // Otherwise, ask the codegen data what to do.
3854 if (getTargetHooks().extendPointerWithSExt())
3855 return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
3856 else
3857 return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
3858 }
3859 case Builtin::BI__builtin_setjmp: {
3860 // Buffer is a void**.
3861 Address Buf = EmitPointerWithAlignment(E->getArg(0));
3862
3863 // Store the frame pointer to the setjmp buffer.
3864 Value *FrameAddr = Builder.CreateCall(
3865 CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy),
3866 ConstantInt::get(Int32Ty, 0));
3867 Builder.CreateStore(FrameAddr, Buf);
3868
3869 // Store the stack pointer to the setjmp buffer.
3870 Value *StackAddr =
3871 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::stacksave));
3872 Address StackSaveSlot = Builder.CreateConstInBoundsGEP(Buf, 2);
3873 Builder.CreateStore(StackAddr, StackSaveSlot);
3874
3875 // Call LLVM's EH setjmp, which is lightweight.
3876 Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
3877 Buf = Builder.CreateElementBitCast(Buf, Int8Ty);
3878 return RValue::get(Builder.CreateCall(F, Buf.getPointer()));
3879 }
3880 case Builtin::BI__builtin_longjmp: {
3881 Value *Buf = EmitScalarExpr(E->getArg(0));
3882 Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
3883
3884 // Call LLVM's EH longjmp, which is lightweight.
3885 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
3886
3887 // longjmp doesn't return; mark this as unreachable.
3888 Builder.CreateUnreachable();
3889
3890 // We do need to preserve an insertion point.
3891 EmitBlock(createBasicBlock("longjmp.cont"));
3892
3893 return RValue::get(nullptr);
3894 }
3895 case Builtin::BI__builtin_launder: {
3896 const Expr *Arg = E->getArg(0);
3897 QualType ArgTy = Arg->getType()->getPointeeType();
3898 Value *Ptr = EmitScalarExpr(Arg);
3899 if (TypeRequiresBuiltinLaunder(CGM, ArgTy))
3900 Ptr = Builder.CreateLaunderInvariantGroup(Ptr);
3901
3902 return RValue::get(Ptr);
3903 }
3904 case Builtin::BI__sync_fetch_and_add:
3905 case Builtin::BI__sync_fetch_and_sub:
3906 case Builtin::BI__sync_fetch_and_or:
3907 case Builtin::BI__sync_fetch_and_and:
3908 case Builtin::BI__sync_fetch_and_xor:
3909 case Builtin::BI__sync_fetch_and_nand:
3910 case Builtin::BI__sync_add_and_fetch:
3911 case Builtin::BI__sync_sub_and_fetch:
3912 case Builtin::BI__sync_and_and_fetch:
3913 case Builtin::BI__sync_or_and_fetch:
3914 case Builtin::BI__sync_xor_and_fetch:
3915 case Builtin::BI__sync_nand_and_fetch:
3916 case Builtin::BI__sync_val_compare_and_swap:
3917 case Builtin::BI__sync_bool_compare_and_swap:
3918 case Builtin::BI__sync_lock_test_and_set:
3919 case Builtin::BI__sync_lock_release:
3920 case Builtin::BI__sync_swap:
3921 llvm_unreachable("Shouldn't make it through sema")::llvm::llvm_unreachable_internal("Shouldn't make it through sema"
, "clang/lib/CodeGen/CGBuiltin.cpp", 3921)
;
3922 case Builtin::BI__sync_fetch_and_add_1:
3923 case Builtin::BI__sync_fetch_and_add_2:
3924 case Builtin::BI__sync_fetch_and_add_4:
3925 case Builtin::BI__sync_fetch_and_add_8:
3926 case Builtin::BI__sync_fetch_and_add_16:
3927 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
3928 case Builtin::BI__sync_fetch_and_sub_1:
3929 case Builtin::BI__sync_fetch_and_sub_2:
3930 case Builtin::BI__sync_fetch_and_sub_4:
3931 case Builtin::BI__sync_fetch_and_sub_8:
3932 case Builtin::BI__sync_fetch_and_sub_16:
3933 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
3934 case Builtin::BI__sync_fetch_and_or_1:
3935 case Builtin::BI__sync_fetch_and_or_2:
3936 case Builtin::BI__sync_fetch_and_or_4:
3937 case Builtin::BI__sync_fetch_and_or_8:
3938 case Builtin::BI__sync_fetch_and_or_16:
3939 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
3940 case Builtin::BI__sync_fetch_and_and_1:
3941 case Builtin::BI__sync_fetch_and_and_2:
3942 case Builtin::BI__sync_fetch_and_and_4:
3943 case Builtin::BI__sync_fetch_and_and_8:
3944 case Builtin::BI__sync_fetch_and_and_16:
3945 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
3946 case Builtin::BI__sync_fetch_and_xor_1:
3947 case Builtin::BI__sync_fetch_and_xor_2:
3948 case Builtin::BI__sync_fetch_and_xor_4:
3949 case Builtin::BI__sync_fetch_and_xor_8:
3950 case Builtin::BI__sync_fetch_and_xor_16:
3951 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
3952 case Builtin::BI__sync_fetch_and_nand_1:
3953 case Builtin::BI__sync_fetch_and_nand_2:
3954 case Builtin::BI__sync_fetch_and_nand_4:
3955 case Builtin::BI__sync_fetch_and_nand_8:
3956 case Builtin::BI__sync_fetch_and_nand_16:
3957 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
3958
3959 // Clang extensions: not overloaded yet.
3960 case Builtin::BI__sync_fetch_and_min:
3961 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
3962 case Builtin::BI__sync_fetch_and_max:
3963 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
3964 case Builtin::BI__sync_fetch_and_umin:
3965 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
3966 case Builtin::BI__sync_fetch_and_umax:
3967 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
3968
3969 case Builtin::BI__sync_add_and_fetch_1:
3970 case Builtin::BI__sync_add_and_fetch_2:
3971 case Builtin::BI__sync_add_and_fetch_4:
3972 case Builtin::BI__sync_add_and_fetch_8:
3973 case Builtin::BI__sync_add_and_fetch_16:
3974 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Add, E,
3975 llvm::Instruction::Add);
3976 case Builtin::BI__sync_sub_and_fetch_1:
3977 case Builtin::BI__sync_sub_and_fetch_2:
3978 case Builtin::BI__sync_sub_and_fetch_4:
3979 case Builtin::BI__sync_sub_and_fetch_8:
3980 case Builtin::BI__sync_sub_and_fetch_16:
3981 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Sub, E,
3982 llvm::Instruction::Sub);
3983 case Builtin::BI__sync_and_and_fetch_1:
3984 case Builtin::BI__sync_and_and_fetch_2:
3985 case Builtin::BI__sync_and_and_fetch_4:
3986 case Builtin::BI__sync_and_and_fetch_8:
3987 case Builtin::BI__sync_and_and_fetch_16:
3988 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::And, E,
3989 llvm::Instruction::And);
3990 case Builtin::BI__sync_or_and_fetch_1:
3991 case Builtin::BI__sync_or_and_fetch_2:
3992 case Builtin::BI__sync_or_and_fetch_4:
3993 case Builtin::BI__sync_or_and_fetch_8:
3994 case Builtin::BI__sync_or_and_fetch_16:
3995 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
3996 llvm::Instruction::Or);
3997 case Builtin::BI__sync_xor_and_fetch_1:
3998 case Builtin::BI__sync_xor_and_fetch_2:
3999 case Builtin::BI__sync_xor_and_fetch_4:
4000 case Builtin::BI__sync_xor_and_fetch_8:
4001 case Builtin::BI__sync_xor_and_fetch_16:
4002 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
4003 llvm::Instruction::Xor);
4004 case Builtin::BI__sync_nand_and_fetch_1:
4005 case Builtin::BI__sync_nand_and_fetch_2:
4006 case Builtin::BI__sync_nand_and_fetch_4:
4007 case Builtin::BI__sync_nand_and_fetch_8:
4008 case Builtin::BI__sync_nand_and_fetch_16:
4009 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
4010 llvm::Instruction::And, true);
4011
4012 case Builtin::BI__sync_val_compare_and_swap_1:
4013 case Builtin::BI__sync_val_compare_and_swap_2:
4014 case Builtin::BI__sync_val_compare_and_swap_4:
4015 case Builtin::BI__sync_val_compare_and_swap_8:
4016 case Builtin::BI__sync_val_compare_and_swap_16:
4017 return RValue::get(MakeAtomicCmpXchgValue(*this, E, false));
4018
4019 case Builtin::BI__sync_bool_compare_and_swap_1:
4020 case Builtin::BI__sync_bool_compare_and_swap_2:
4021 case Builtin::BI__sync_bool_compare_and_swap_4:
4022 case Builtin::BI__sync_bool_compare_and_swap_8:
4023 case Builtin::BI__sync_bool_compare_and_swap_16:
4024 return RValue::get(MakeAtomicCmpXchgValue(*this, E, true));
4025
4026 case Builtin::BI__sync_swap_1:
4027 case Builtin::BI__sync_swap_2:
4028 case Builtin::BI__sync_swap_4:
4029 case Builtin::BI__sync_swap_8:
4030 case Builtin::BI__sync_swap_16:
4031 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
4032
4033 case Builtin::BI__sync_lock_test_and_set_1:
4034 case Builtin::BI__sync_lock_test_and_set_2:
4035 case Builtin::BI__sync_lock_test_and_set_4:
4036 case Builtin::BI__sync_lock_test_and_set_8:
4037 case Builtin::BI__sync_lock_test_and_set_16:
4038 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
4039
4040 case Builtin::BI__sync_lock_release_1:
4041 case Builtin::BI__sync_lock_release_2:
4042 case Builtin::BI__sync_lock_release_4:
4043 case Builtin::BI__sync_lock_release_8:
4044 case Builtin::BI__sync_lock_release_16: {
4045 Value *Ptr = CheckAtomicAlignment(*this, E);
4046 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
4047 CharUnits StoreSize = getContext().getTypeSizeInChars(ElTy);
4048 llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
4049 StoreSize.getQuantity() * 8);
4050 Ptr = Builder.CreateBitCast(Ptr, ITy->getPointerTo());
4051 llvm::StoreInst *Store =
4052 Builder.CreateAlignedStore(llvm::Constant::getNullValue(ITy), Ptr,
4053 StoreSize);
4054 Store->setAtomic(llvm::AtomicOrdering::Release);
4055 return RValue::get(nullptr);
4056 }
4057
4058 case Builtin::BI__sync_synchronize: {
4059 // We assume this is supposed to correspond to a C++0x-style
4060 // sequentially-consistent fence (i.e. this is only usable for
4061 // synchronization, not device I/O or anything like that). This intrinsic
4062 // is really badly designed in the sense that in theory, there isn't
4063 // any way to safely use it... but in practice, it mostly works
4064 // to use it with non-atomic loads and stores to get acquire/release
4065 // semantics.
4066 Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
4067 return RValue::get(nullptr);
4068 }
4069
4070 case Builtin::BI__builtin_nontemporal_load:
4071 return RValue::get(EmitNontemporalLoad(*this, E));
4072 case Builtin::BI__builtin_nontemporal_store:
4073 return RValue::get(EmitNontemporalStore(*this, E));
4074 case Builtin::BI__c11_atomic_is_lock_free:
4075 case Builtin::BI__atomic_is_lock_free: {
4076 // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
4077 // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
4078 // _Atomic(T) is always properly-aligned.
4079 const char *LibCallName = "__atomic_is_lock_free";
4080 CallArgList Args;
4081 Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
4082 getContext().getSizeType());
4083 if (BuiltinID == Builtin::BI__atomic_is_lock_free)
4084 Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
4085 getContext().VoidPtrTy);
4086 else
4087 Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
4088 getContext().VoidPtrTy);
4089 const CGFunctionInfo &FuncInfo =
4090 CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
4091 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
4092 llvm::FunctionCallee Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
4093 return EmitCall(FuncInfo, CGCallee::forDirect(Func),
4094 ReturnValueSlot(), Args);
4095 }
4096
4097 case Builtin::BI__atomic_test_and_set: {
4098 // Look at the argument type to determine whether this is a volatile
4099 // operation. The parameter type is always volatile.
4100 QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
4101 bool Volatile =
4102 PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
4103
4104 Value *Ptr = EmitScalarExpr(E->getArg(0));
4105 unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
4106 Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
4107 Value *NewVal = Builder.getInt8(1);
4108 Value *Order = EmitScalarExpr(E->getArg(1));
4109 if (isa<llvm::ConstantInt>(Order)) {
4110 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4111 AtomicRMWInst *Result = nullptr;
4112 switch (ord) {
4113 case 0: // memory_order_relaxed
4114 default: // invalid order
4115 Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4116 llvm::AtomicOrdering::Monotonic);
4117 break;
4118 case 1: // memory_order_consume
4119 case 2: // memory_order_acquire
4120 Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4121 llvm::AtomicOrdering::Acquire);
4122 break;
4123 case 3: // memory_order_release
4124 Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4125 llvm::AtomicOrdering::Release);
4126 break;
4127 case 4: // memory_order_acq_rel
4128
4129 Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4130 llvm::AtomicOrdering::AcquireRelease);
4131 break;
4132 case 5: // memory_order_seq_cst
4133 Result = Builder.CreateAtomicRMW(
4134 llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4135 llvm::AtomicOrdering::SequentiallyConsistent);
4136 break;
4137 }
4138 Result->setVolatile(Volatile);
4139 return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
4140 }
4141
4142 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4143
4144 llvm::BasicBlock *BBs[5] = {
4145 createBasicBlock("monotonic", CurFn),
4146 createBasicBlock("acquire", CurFn),
4147 createBasicBlock("release", CurFn),
4148 createBasicBlock("acqrel", CurFn),
4149 createBasicBlock("seqcst", CurFn)
4150 };
4151 llvm::AtomicOrdering Orders[5] = {
4152 llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Acquire,
4153 llvm::AtomicOrdering::Release, llvm::AtomicOrdering::AcquireRelease,
4154 llvm::AtomicOrdering::SequentiallyConsistent};
4155
4156 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4157 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
4158
4159 Builder.SetInsertPoint(ContBB);
4160 PHINode *Result = Builder.CreatePHI(Int8Ty, 5, "was_set");
4161
4162 for (unsigned i = 0; i < 5; ++i) {
4163 Builder.SetInsertPoint(BBs[i]);
4164 AtomicRMWInst *RMW = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
4165 Ptr, NewVal, Orders[i]);
4166 RMW->setVolatile(Volatile);
4167 Result->addIncoming(RMW, BBs[i]);
4168 Builder.CreateBr(ContBB);
4169 }
4170
4171 SI->addCase(Builder.getInt32(0), BBs[0]);
4172 SI->addCase(Builder.getInt32(1), BBs[1]);
4173 SI->addCase(Builder.getInt32(2), BBs[1]);
4174 SI->addCase(Builder.getInt32(3), BBs[2]);
4175 SI->addCase(Builder.getInt32(4), BBs[3]);
4176 SI->addCase(Builder.getInt32(5), BBs[4]);
4177
4178 Builder.SetInsertPoint(ContBB);
4179 return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
4180 }
4181
4182 case Builtin::BI__atomic_clear: {
4183 QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
4184 bool Volatile =
4185 PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
4186
4187 Address Ptr = EmitPointerWithAlignment(E->getArg(0));
4188 Ptr = Builder.CreateElementBitCast(Ptr, Int8Ty);
4189 Value *NewVal = Builder.getInt8(0);
4190 Value *Order = EmitScalarExpr(E->getArg(1));
4191 if (isa<llvm::ConstantInt>(Order)) {
4192 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4193 StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
4194 switch (ord) {
4195 case 0: // memory_order_relaxed
4196 default: // invalid order
4197 Store->setOrdering(llvm::AtomicOrdering::Monotonic);
4198 break;
4199 case 3: // memory_order_release
4200 Store->setOrdering(llvm::AtomicOrdering::Release);
4201 break;
4202 case 5: // memory_order_seq_cst
4203 Store->setOrdering(llvm::AtomicOrdering::SequentiallyConsistent);
4204 break;
4205 }
4206 return RValue::get(nullptr);
4207 }
4208
4209 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4210
4211 llvm::BasicBlock *BBs[3] = {
4212 createBasicBlock("monotonic", CurFn),
4213 createBasicBlock("release", CurFn),
4214 createBasicBlock("seqcst", CurFn)
4215 };
4216 llvm::AtomicOrdering Orders[3] = {
4217 llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Release,
4218 llvm::AtomicOrdering::SequentiallyConsistent};
4219
4220 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4221 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
4222
4223 for (unsigned i = 0; i < 3; ++i) {
4224 Builder.SetInsertPoint(BBs[i]);
4225 StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
4226 Store->setOrdering(Orders[i]);
4227 Builder.CreateBr(ContBB);
4228 }
4229
4230 SI->addCase(Builder.getInt32(0), BBs[0]);
4231 SI->addCase(Builder.getInt32(3), BBs[1]);
4232 SI->addCase(Builder.getInt32(5), BBs[2]);
4233
4234 Builder.SetInsertPoint(ContBB);
4235 return RValue::get(nullptr);
4236 }
4237
4238 case Builtin::BI__atomic_thread_fence:
4239 case Builtin::BI__atomic_signal_fence:
4240 case Builtin::BI__c11_atomic_thread_fence:
4241 case Builtin::BI__c11_atomic_signal_fence: {
4242 llvm::SyncScope::ID SSID;
4243 if (BuiltinID == Builtin::BI__atomic_signal_fence ||
4244 BuiltinID == Builtin::BI__c11_atomic_signal_fence)
4245 SSID = llvm::SyncScope::SingleThread;
4246 else
4247 SSID = llvm::SyncScope::System;
4248 Value *Order = EmitScalarExpr(E->getArg(0));
4249 if (isa<llvm::ConstantInt>(Order)) {
4250 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4251 switch (ord) {
4252 case 0: // memory_order_relaxed
4253 default: // invalid order
4254 break;
4255 case 1: // memory_order_consume
4256 case 2: // memory_order_acquire
4257 Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
4258 break;
4259 case 3: // memory_order_release
4260 Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
4261 break;
4262 case 4: // memory_order_acq_rel
4263 Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
4264 break;
4265 case 5: // memory_order_seq_cst
4266 Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
4267 break;
4268 }
4269 return RValue::get(nullptr);
4270 }
4271
4272 llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
4273 AcquireBB = createBasicBlock("acquire", CurFn);
4274 ReleaseBB = createBasicBlock("release", CurFn);
4275 AcqRelBB = createBasicBlock("acqrel", CurFn);
4276 SeqCstBB = createBasicBlock("seqcst", CurFn);
4277 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4278
4279 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4280 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
4281
4282 Builder.SetInsertPoint(AcquireBB);
4283 Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
4284 Builder.CreateBr(ContBB);
4285 SI->addCase(Builder.getInt32(1), AcquireBB);
4286 SI->addCase(Builder.getInt32(2), AcquireBB);
4287
4288 Builder.SetInsertPoint(ReleaseBB);
4289 Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
4290 Builder.CreateBr(ContBB);
4291 SI->addCase(Builder.getInt32(3), ReleaseBB);
4292
4293 Builder.SetInsertPoint(AcqRelBB);
4294 Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
4295 Builder.CreateBr(ContBB);
4296 SI->addCase(Builder.getInt32(4), AcqRelBB);
4297
4298 Builder.SetInsertPoint(SeqCstBB);
4299 Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
4300 Builder.CreateBr(ContBB);
4301 SI->addCase(Builder.getInt32(5), SeqCstBB);
4302
4303 Builder.SetInsertPoint(ContBB);
4304 return RValue::get(nullptr);
4305 }
4306
4307 case Builtin::BI__builtin_signbit:
4308 case Builtin::BI__builtin_signbitf:
4309 case Builtin::BI__builtin_signbitl: {
4310 return RValue::get(
4311 Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
4312 ConvertType(E->getType())));
4313 }
4314 case Builtin::BI__warn_memset_zero_len:
4315 return RValue::getIgnored();
4316 case Builtin::BI__annotation: {
4317 // Re-encode each wide string to UTF8 and make an MDString.
4318 SmallVector<Metadata *, 1> Strings;
4319 for (const Expr *Arg : E->arguments()) {
4320 const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
4321 assert(Str->getCharByteWidth() == 2)(static_cast <bool> (Str->getCharByteWidth() == 2) ?
void (0) : __assert_fail ("Str->getCharByteWidth() == 2",
"clang/lib/CodeGen/CGBuiltin.cpp", 4321, __extension__ __PRETTY_FUNCTION__
))
;
4322 StringRef WideBytes = Str->getBytes();
4323 std::string StrUtf8;
4324 if (!convertUTF16ToUTF8String(
4325 ArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)) {
4326 CGM.ErrorUnsupported(E, "non-UTF16 __annotation argument");
4327 continue;
4328 }
4329 Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
4330 }
4331
4332 // Build and MDTuple of MDStrings and emit the intrinsic call.
4333 llvm::Function *F =
4334 CGM.getIntrinsic(llvm::Intrinsic::codeview_annotation, {});
4335 MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
4336 Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
4337 return RValue::getIgnored();
4338 }
4339 case Builtin::BI__builtin_annotation: {
4340 llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
4341 llvm::Function *F =
4342 CGM.getIntrinsic(llvm::Intrinsic::annotation,
4343 {AnnVal->getType(), CGM.ConstGlobalsPtrTy});
4344
4345 // Get the annotation string, go through casts. Sema requires this to be a
4346 // non-wide string literal, potentially casted, so the cast<> is safe.
4347 const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
4348 StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
4349 return RValue::get(
4350 EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc(), nullptr));
4351 }
4352 case Builtin::BI__builtin_addcb:
4353 case Builtin::BI__builtin_addcs:
4354 case Builtin::BI__builtin_addc:
4355 case Builtin::BI__builtin_addcl:
4356 case Builtin::BI__builtin_addcll:
4357 case Builtin::BI__builtin_subcb:
4358 case Builtin::BI__builtin_subcs:
4359 case Builtin::BI__builtin_subc:
4360 case Builtin::BI__builtin_subcl:
4361 case Builtin::BI__builtin_subcll: {
4362
4363 // We translate all of these builtins from expressions of the form:
4364 // int x = ..., y = ..., carryin = ..., carryout, result;
4365 // result = __builtin_addc(x, y, carryin, &carryout);
4366 //
4367 // to LLVM IR of the form:
4368 //
4369 // %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
4370 // %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
4371 // %carry1 = extractvalue {i32, i1} %tmp1, 1
4372 // %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
4373 // i32 %carryin)
4374 // %result = extractvalue {i32, i1} %tmp2, 0
4375 // %carry2 = extractvalue {i32, i1} %tmp2, 1
4376 // %tmp3 = or i1 %carry1, %carry2
4377 // %tmp4 = zext i1 %tmp3 to i32
4378 // store i32 %tmp4, i32* %carryout
4379
4380 // Scalarize our inputs.
4381 llvm::Value *X = EmitScalarExpr(E->getArg(0));
4382 llvm::Value *Y = EmitScalarExpr(E->getArg(1));
4383 llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
4384 Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
4385
4386 // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
4387 llvm::Intrinsic::ID IntrinsicId;
4388 switch (BuiltinID) {
4389 default: llvm_unreachable("Unknown multiprecision builtin id.")::llvm::llvm_unreachable_internal("Unknown multiprecision builtin id."
, "clang/lib/CodeGen/CGBuiltin.cpp", 4389)
;
4390 case Builtin::BI__builtin_addcb:
4391 case Builtin::BI__builtin_addcs:
4392 case Builtin::BI__builtin_addc:
4393 case Builtin::BI__builtin_addcl:
4394 case Builtin::BI__builtin_addcll:
4395 IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
4396 break;
4397 case Builtin::BI__builtin_subcb:
4398 case Builtin::BI__builtin_subcs:
4399 case Builtin::BI__builtin_subc:
4400 case Builtin::BI__builtin_subcl:
4401 case Builtin::BI__builtin_subcll:
4402 IntrinsicId = llvm::Intrinsic::usub_with_overflow;
4403 break;
4404 }
4405
4406 // Construct our resulting LLVM IR expression.
4407 llvm::Value *Carry1;
4408 llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
4409 X, Y, Carry1);
4410 llvm::Value *Carry2;
4411 llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
4412 Sum1, Carryin, Carry2);
4413 llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
4414 X->getType());
4415 Builder.CreateStore(CarryOut, CarryOutPtr);
4416 return RValue::get(Sum2);
4417 }
4418
4419 case Builtin::BI__builtin_add_overflow:
4420 case Builtin::BI__builtin_sub_overflow:
4421 case Builtin::BI__builtin_mul_overflow: {
4422 const clang::Expr *LeftArg = E->getArg(0);
4423 const clang::Expr *RightArg = E->getArg(1);
4424 const clang::Expr *ResultArg = E->getArg(2);
4425
4426 clang::QualType ResultQTy =
4427 ResultArg->getType()->castAs<PointerType>()->getPointeeType();
4428
4429 WidthAndSignedness LeftInfo =
4430 getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
4431 WidthAndSignedness RightInfo =
4432 getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
4433 WidthAndSignedness ResultInfo =
4434 getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
4435
4436 // Handle mixed-sign multiplication as a special case, because adding
4437 // runtime or backend support for our generic irgen would be too expensive.
4438 if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
4439 return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
4440 RightInfo, ResultArg, ResultQTy,
4441 ResultInfo);
4442
4443 if (isSpecialUnsignedMultiplySignedResult(BuiltinID, LeftInfo, RightInfo,
4444 ResultInfo))
4445 return EmitCheckedUnsignedMultiplySignedResult(
4446 *this, LeftArg, LeftInfo, RightArg, RightInfo, ResultArg, ResultQTy,
4447 ResultInfo);
4448
4449 WidthAndSignedness EncompassingInfo =
4450 EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
4451
4452 llvm::Type *EncompassingLLVMTy =
4453 llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
4454
4455 llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
4456
4457 llvm::Intrinsic::ID IntrinsicId;
4458 switch (BuiltinID) {
4459 default:
4460 llvm_unreachable("Unknown overflow builtin id.")::llvm::llvm_unreachable_internal("Unknown overflow builtin id."
, "clang/lib/CodeGen/CGBuiltin.cpp", 4460)
;
4461 case Builtin::BI__builtin_add_overflow:
4462 IntrinsicId = EncompassingInfo.Signed
4463 ? llvm::Intrinsic::sadd_with_overflow
4464 : llvm::Intrinsic::uadd_with_overflow;
4465 break;
4466 case Builtin::BI__builtin_sub_overflow:
4467 IntrinsicId = EncompassingInfo.Signed
4468 ? llvm::Intrinsic::ssub_with_overflow
4469 : llvm::Intrinsic::usub_with_overflow;
4470 break;
4471 case Builtin::BI__builtin_mul_overflow:
4472 IntrinsicId = EncompassingInfo.Signed
4473 ? llvm::Intrinsic::smul_with_overflow
4474 : llvm::Intrinsic::umul_with_overflow;
4475 break;
4476 }
4477
4478 llvm::Value *Left = EmitScalarExpr(LeftArg);
4479 llvm::Value *Right = EmitScalarExpr(RightArg);
4480 Address ResultPtr = EmitPointerWithAlignment(ResultArg);
4481
4482 // Extend each operand to the encompassing type.
4483 Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
4484 Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
4485
4486 // Perform the operation on the extended values.
4487 llvm::Value *Overflow, *Result;
4488 Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
4489
4490 if (EncompassingInfo.Width > ResultInfo.Width) {
4491 // The encompassing type is wider than the result type, so we need to
4492 // truncate it.
4493 llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
4494
4495 // To see if the truncation caused an overflow, we will extend
4496 // the result and then compare it to the original result.
4497 llvm::Value *ResultTruncExt = Builder.CreateIntCast(
4498 ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
4499 llvm::Value *TruncationOverflow =
4500 Builder.CreateICmpNE(Result, ResultTruncExt);
4501
4502 Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
4503 Result = ResultTrunc;
4504 }
4505
4506 // Finally, store the result using the pointer.
4507 bool isVolatile =
4508 ResultArg->getType()->getPointeeType().isVolatileQualified();
4509 Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
4510
4511 return RValue::get(Overflow);
4512 }
4513
4514 case Builtin::BI__builtin_uadd_overflow:
4515 case Builtin::BI__builtin_uaddl_overflow:
4516 case Builtin::BI__builtin_uaddll_overflow:
4517 case Builtin::BI__builtin_usub_overflow:
4518 case Builtin::BI__builtin_usubl_overflow:
4519 case Builtin::BI__builtin_usubll_overflow:
4520 case Builtin::BI__builtin_umul_overflow:
4521 case Builtin::BI__builtin_umull_overflow:
4522 case Builtin::BI__builtin_umulll_overflow:
4523 case Builtin::BI__builtin_sadd_overflow:
4524 case Builtin::BI__builtin_saddl_overflow:
4525 case Builtin::BI__builtin_saddll_overflow:
4526 case Builtin::BI__builtin_ssub_overflow:
4527 case Builtin::BI__builtin_ssubl_overflow:
4528 case Builtin::BI__builtin_ssubll_overflow:
4529 case Builtin::BI__builtin_smul_overflow:
4530 case Builtin::BI__builtin_smull_overflow:
4531 case Builtin::BI__builtin_smulll_overflow: {
4532
4533 // We translate all of these builtins directly to the relevant llvm IR node.
4534
4535 // Scalarize our inputs.
4536 llvm::Value *X = EmitScalarExpr(E->getArg(0));
4537 llvm::Value *Y = EmitScalarExpr(E->getArg(1));
4538 Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
4539
4540 // Decide which of the overflow intrinsics we are lowering to:
4541 llvm::Intrinsic::ID IntrinsicId;
4542 switch (BuiltinID) {
4543 default: llvm_unreachable("Unknown overflow builtin id.")::llvm::llvm_unreachable_internal("Unknown overflow builtin id."
, "clang/lib/CodeGen/CGBuiltin.cpp", 4543)
;
4544 case Builtin::BI__builtin_uadd_overflow:
4545 case Builtin::BI__builtin_uaddl_overflow:
4546 case Builtin::BI__builtin_uaddll_overflow:
4547 IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
4548 break;
4549 case Builtin::BI__builtin_usub_overflow:
4550 case Builtin::BI__builtin_usubl_overflow:
4551 case Builtin::BI__builtin_usubll_overflow:
4552 IntrinsicId = llvm::Intrinsic::usub_with_overflow;
4553 break;
4554 case Builtin::BI__builtin_umul_overflow:
4555 case Builtin::BI__builtin_umull_overflow:
4556 case Builtin::BI__builtin_umulll_overflow:
4557 IntrinsicId = llvm::Intrinsic::umul_with_overflow;
4558 break;
4559 case Builtin::BI__builtin_sadd_overflow:
4560 case Builtin::BI__builtin_saddl_overflow:
4561 case Builtin::BI__builtin_saddll_overflow:
4562 IntrinsicId = llvm::Intrinsic::sadd_with_overflow;
4563 break;
4564 case Builtin::BI__builtin_ssub_overflow:
4565 case Builtin::BI__builtin_ssubl_overflow:
4566 case Builtin::BI__builtin_ssubll_overflow:
4567 IntrinsicId = llvm::Intrinsic::ssub_with_overflow;
4568 break;
4569 case Builtin::BI__builtin_smul_overflow:
4570 case Builtin::BI__builtin_smull_overflow:
4571 case Builtin::BI__builtin_smulll_overflow:
4572 IntrinsicId = llvm::Intrinsic::smul_with_overflow;
4573 break;
4574 }
4575
4576
4577 llvm::Value *Carry;
4578 llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
4579 Builder.CreateStore(Sum, SumOutPtr);
4580
4581 return RValue::get(Carry);
4582 }
4583 case Builtin::BIaddressof:
4584 case Builtin::BI__addressof:
4585 case Builtin::BI__builtin_addressof:
4586 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
4587 case Builtin::BI__builtin_function_start:
4588 return RValue::get(CGM.GetFunctionStart(
4589 E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext())));
4590 case Builtin::BI__builtin_operator_new:
4591 return EmitBuiltinNewDeleteCall(
4592 E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
4593 case Builtin::BI__builtin_operator_delete:
4594 EmitBuiltinNewDeleteCall(
4595 E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
4596 return RValue::get(nullptr);
4597
4598 case Builtin::BI__builtin_is_aligned:
4599 return EmitBuiltinIsAligned(E);
4600 case Builtin::BI__builtin_align_up:
4601 return EmitBuiltinAlignTo(E, true);
4602 case Builtin::BI__builtin_align_down:
4603 return EmitBuiltinAlignTo(E, false);
4604
4605 case Builtin::BI__noop:
4606 // __noop always evaluates to an integer literal zero.
4607 return RValue::get(ConstantInt::get(IntTy, 0));
4608 case Builtin::BI__builtin_call_with_static_chain: {
4609 const CallExpr *Call = cast<CallExpr>(E->getArg(0));
4610 const Expr *Chain = E->getArg(1);
4611 return EmitCall(Call->getCallee()->getType(),
4612 EmitCallee(Call->getCallee()), Call, ReturnValue,
4613 EmitScalarExpr(Chain));
4614 }
4615 case Builtin::BI_InterlockedExchange8:
4616 case Builtin::BI_InterlockedExchange16:
4617 case Builtin::BI_InterlockedExchange:
4618 case Builtin::BI_InterlockedExchangePointer:
4619 return RValue::get(
4620 EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchange, E));
4621 case Builtin::BI_InterlockedCompareExchangePointer:
4622 case Builtin::BI_InterlockedCompareExchangePointer_nf: {
4623 llvm::Type *RTy;
4624 llvm::IntegerType *IntType =
4625 IntegerType::get(getLLVMContext(),
4626 getContext().getTypeSize(E->getType()));
4627 llvm::Type *IntPtrType = IntType->getPointerTo();
4628
4629 llvm::Value *Destination =
4630 Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), IntPtrType);
4631
4632 llvm::Value *Exchange = EmitScalarExpr(E->getArg(1));
4633 RTy = Exchange->getType();
4634 Exchange = Builder.CreatePtrToInt(Exchange, IntType);
4635
4636 llvm::Value *Comparand =
4637 Builder.CreatePtrToInt(EmitScalarExpr(E->getArg(2)), IntType);
4638
4639 auto Ordering =
4640 BuiltinID == Builtin::BI_InterlockedCompareExchangePointer_nf ?
4641 AtomicOrdering::Monotonic : AtomicOrdering::SequentiallyConsistent;
4642
4643 auto Result = Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
4644 Ordering, Ordering);
4645 Result->setVolatile(true);
4646
4647 return RValue::get(Builder.CreateIntToPtr(Builder.CreateExtractValue(Result,
4648 0),
4649 RTy));
4650 }
4651 case Builtin::BI_InterlockedCompareExchange8:
4652 case Builtin::BI_InterlockedCompareExchange16:
4653 case Builtin::BI_InterlockedCompareExchange:
4654 case Builtin::BI_InterlockedCompareExchange64:
4655 return RValue::get(EmitAtomicCmpXchgForMSIntrin(*this, E));
4656 case Builtin::BI_InterlockedIncrement16:
4657 case Builtin::BI_InterlockedIncrement:
4658 return RValue::get(
4659 EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedIncrement, E));
4660 case Builtin::BI_InterlockedDecrement16:
4661 case Builtin::BI_InterlockedDecrement:
4662 return RValue::get(
4663 EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedDecrement, E));
4664 case Builtin::BI_InterlockedAnd8:
4665 case Builtin::BI_InterlockedAnd16:
4666 case Builtin::BI_InterlockedAnd:
4667 return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedAnd, E));
4668 case Builtin::BI_InterlockedExchangeAdd8:
4669 case Builtin::BI_InterlockedExchangeAdd16:
4670 case Builtin::BI_InterlockedExchangeAdd:
4671 return RValue::get(
4672 EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeAdd, E));
4673 case Builtin::BI_InterlockedExchangeSub8:
4674 case Builtin::BI_InterlockedExchangeSub16:
4675 case Builtin::BI_InterlockedExchangeSub:
4676 return RValue::get(
4677 EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeSub, E));
4678 case Builtin::BI_InterlockedOr8:
4679 case Builtin::BI_InterlockedOr16:
4680 case Builtin::BI_InterlockedOr:
4681 return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedOr, E));
4682 case Builtin::BI_InterlockedXor8:
4683 case Builtin::BI_InterlockedXor16:
4684 case Builtin::BI_InterlockedXor:
4685 return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedXor, E));
4686
4687 case Builtin::BI_bittest64:
4688 case Builtin::BI_bittest:
4689 case Builtin::BI_bittestandcomplement64:
4690 case Builtin::BI_bittestandcomplement:
4691 case Builtin::BI_bittestandreset64:
4692 case Builtin::BI_bittestandreset:
4693 case Builtin::BI_bittestandset64:
4694 case Builtin::BI_bittestandset:
4695 case Builtin::BI_interlockedbittestandreset:
4696 case Builtin::BI_interlockedbittestandreset64:
4697 case Builtin::BI_interlockedbittestandset64:
4698 case Builtin::BI_interlockedbittestandset:
4699 case Builtin::BI_interlockedbittestandset_acq:
4700 case Builtin::BI_interlockedbittestandset_rel:
4701 case Builtin::BI_interlockedbittestandset_nf:
4702 case Builtin::BI_interlockedbittestandreset_acq:
4703 case Builtin::BI_interlockedbittestandreset_rel:
4704 case Builtin::BI_interlockedbittestandreset_nf:
4705 return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
4706
4707 // These builtins exist to emit regular volatile loads and stores not
4708 // affected by the -fms-volatile setting.
4709 case Builtin::BI__iso_volatile_load8:
4710 case Builtin::BI__iso_volatile_load16:
4711 case Builtin::BI__iso_volatile_load32:
4712 case Builtin::BI__iso_volatile_load64:
4713 return RValue::get(EmitISOVolatileLoad(*this, E));
4714 case Builtin::BI__iso_volatile_store8:
4715 case Builtin::BI__iso_volatile_store16:
4716 case Builtin::BI__iso_volatile_store32:
4717 case Builtin::BI__iso_volatile_store64:
4718 return RValue::get(EmitISOVolatileStore(*this, E));
4719
4720 case Builtin::BI__exception_code:
4721 case Builtin::BI_exception_code:
4722 return RValue::get(EmitSEHExceptionCode());
4723 case Builtin::BI__exception_info:
4724 case Builtin::BI_exception_info:
4725 return RValue::get(EmitSEHExceptionInfo());
4726 case Builtin::BI__abnormal_termination:
4727 case Builtin::BI_abnormal_termination:
4728 return RValue::get(EmitSEHAbnormalTermination());
4729 case Builtin::BI_setjmpex:
4730 if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
4731 E->getArg(0)->getType()->isPointerType())
4732 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
4733 break;
4734 case Builtin::BI_setjmp:
4735 if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
4736 E->getArg(0)->getType()->isPointerType()) {
4737 if (getTarget().getTriple().getArch() == llvm::Triple::x86)
4738 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
4739 else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
4740 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
4741 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
4742 }
4743 break;
4744
4745 // C++ std:: builtins.
4746 case Builtin::BImove:
4747 case Builtin::BImove_if_noexcept:
4748 case Builtin::BIforward:
4749 case Builtin::BIforward_like:
4750 case Builtin::BIas_const:
4751 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
4752 case Builtin::BI__GetExceptionInfo: {
4753 if (llvm::GlobalVariable *GV =
4754 CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
4755 return RValue::get(llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy));
4756 break;
4757 }
4758
4759 case Builtin::BI__fastfail:
4760 return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::__fastfail, E));
4761
4762 case Builtin::BI__builtin_coro_id:
4763 return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
4764 case Builtin::BI__builtin_coro_promise:
4765 return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
4766 case Builtin::BI__builtin_coro_resume:
4767 EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
4768 return RValue::get(nullptr);
4769 case Builtin::BI__builtin_coro_frame:
4770 return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
4771 case Builtin::BI__builtin_coro_noop:
4772 return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
4773 case Builtin::BI__builtin_coro_free:
4774 return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
4775 case Builtin::BI__builtin_coro_destroy:
4776 EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
4777 return RValue::get(nullptr);
4778 case Builtin::BI__builtin_coro_done:
4779 return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
4780 case Builtin::BI__builtin_coro_alloc:
4781 return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
4782 case Builtin::BI__builtin_coro_begin:
4783 return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
4784 case Builtin::BI__builtin_coro_end:
4785 return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
4786 case Builtin::BI__builtin_coro_suspend:
4787 return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
4788 case Builtin::BI__builtin_coro_size:
4789 return EmitCoroutineIntrinsic(E, Intrinsic::coro_size);
4790 case Builtin::BI__builtin_coro_align:
4791 return EmitCoroutineIntrinsic(E, Intrinsic::coro_align);
4792
4793 // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
4794 case Builtin::BIread_pipe:
4795 case Builtin::BIwrite_pipe: {
4796 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4797 *Arg1 = EmitScalarExpr(E->getArg(1));
4798 CGOpenCLRuntime OpenCLRT(CGM);
4799 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4800 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4801
4802 // Type of the generic packet parameter.
4803 unsigned GenericAS =
4804 getContext().getTargetAddressSpace(LangAS::opencl_generic);
4805 llvm::Type *I8PTy = llvm::PointerType::get(
4806 llvm::Type::getInt8Ty(getLLVMContext()), GenericAS);
4807
4808 // Testing which overloaded version we should generate the call for.
4809 if (2U == E->getNumArgs()) {
4810 const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
4811 : "__write_pipe_2";
4812 // Creating a generic function type to be able to call with any builtin or
4813 // user defined type.
4814 llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
4815 llvm::FunctionType *FTy = llvm::FunctionType::get(
4816 Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4817 Value *BCast = Builder.CreatePointerCast(Arg1, I8PTy);
4818 return RValue::get(
4819 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4820 {Arg0, BCast, PacketSize, PacketAlign}));
4821 } else {
4822 assert(4 == E->getNumArgs() &&(static_cast <bool> (4 == E->getNumArgs() &&
"Illegal number of parameters to pipe function") ? void (0) :
__assert_fail ("4 == E->getNumArgs() && \"Illegal number of parameters to pipe function\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 4823, __extension__ __PRETTY_FUNCTION__
))
4823 "Illegal number of parameters to pipe function")(static_cast <bool> (4 == E->getNumArgs() &&
"Illegal number of parameters to pipe function") ? void (0) :
__assert_fail ("4 == E->getNumArgs() && \"Illegal number of parameters to pipe function\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 4823, __extension__ __PRETTY_FUNCTION__
))
;
4824 const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
4825 : "__write_pipe_4";
4826
4827 llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
4828 Int32Ty, Int32Ty};
4829 Value *Arg2 = EmitScalarExpr(E->getArg(2)),
4830 *Arg3 = EmitScalarExpr(E->getArg(3));
4831 llvm::FunctionType *FTy = llvm::FunctionType::get(
4832 Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4833 Value *BCast = Builder.CreatePointerCast(Arg3, I8PTy);
4834 // We know the third argument is an integer type, but we may need to cast
4835 // it to i32.
4836 if (Arg2->getType() != Int32Ty)
4837 Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
4838 return RValue::get(
4839 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4840 {Arg0, Arg1, Arg2, BCast, PacketSize, PacketAlign}));
4841 }
4842 }
4843 // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
4844 // functions
4845 case Builtin::BIreserve_read_pipe:
4846 case Builtin::BIreserve_write_pipe:
4847 case Builtin::BIwork_group_reserve_read_pipe:
4848 case Builtin::BIwork_group_reserve_write_pipe:
4849 case Builtin::BIsub_group_reserve_read_pipe:
4850 case Builtin::BIsub_group_reserve_write_pipe: {
4851 // Composing the mangled name for the function.
4852 const char *Name;
4853 if (BuiltinID == Builtin::BIreserve_read_pipe)
4854 Name = "__reserve_read_pipe";
4855 else if (BuiltinID == Builtin::BIreserve_write_pipe)
4856 Name = "__reserve_write_pipe";
4857 else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
4858 Name = "__work_group_reserve_read_pipe";
4859 else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
4860 Name = "__work_group_reserve_write_pipe";
4861 else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
4862 Name = "__sub_group_reserve_read_pipe";
4863 else
4864 Name = "__sub_group_reserve_write_pipe";
4865
4866 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4867 *Arg1 = EmitScalarExpr(E->getArg(1));
4868 llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
4869 CGOpenCLRuntime OpenCLRT(CGM);
4870 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4871 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4872
4873 // Building the generic function prototype.
4874 llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
4875 llvm::FunctionType *FTy = llvm::FunctionType::get(
4876 ReservedIDTy, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4877 // We know the second argument is an integer type, but we may need to cast
4878 // it to i32.
4879 if (Arg1->getType() != Int32Ty)
4880 Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
4881 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4882 {Arg0, Arg1, PacketSize, PacketAlign}));
4883 }
4884 // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
4885 // functions
4886 case Builtin::BIcommit_read_pipe:
4887 case Builtin::BIcommit_write_pipe:
4888 case Builtin::BIwork_group_commit_read_pipe:
4889 case Builtin::BIwork_group_commit_write_pipe:
4890 case Builtin::BIsub_group_commit_read_pipe:
4891 case Builtin::BIsub_group_commit_write_pipe: {
4892 const char *Name;
4893 if (BuiltinID == Builtin::BIcommit_read_pipe)
4894 Name = "__commit_read_pipe";
4895 else if (BuiltinID == Builtin::BIcommit_write_pipe)
4896 Name = "__commit_write_pipe";
4897 else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
4898 Name = "__work_group_commit_read_pipe";
4899 else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
4900 Name = "__work_group_commit_write_pipe";
4901 else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
4902 Name = "__sub_group_commit_read_pipe";
4903 else
4904 Name = "__sub_group_commit_write_pipe";
4905
4906 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4907 *Arg1 = EmitScalarExpr(E->getArg(1));
4908 CGOpenCLRuntime OpenCLRT(CGM);
4909 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4910 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4911
4912 // Building the generic function prototype.
4913 llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
4914 llvm::FunctionType *FTy =
4915 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
4916 llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4917
4918 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4919 {Arg0, Arg1, PacketSize, PacketAlign}));
4920 }
4921 // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
4922 case Builtin::BIget_pipe_num_packets:
4923 case Builtin::BIget_pipe_max_packets: {
4924 const char *BaseName;
4925 const auto *PipeTy = E->getArg(0)->getType()->castAs<PipeType>();
4926 if (BuiltinID == Builtin::BIget_pipe_num_packets)
4927 BaseName = "__get_pipe_num_packets";
4928 else
4929 BaseName = "__get_pipe_max_packets";
4930 std::string Name = std::string(BaseName) +
4931 std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
4932
4933 // Building the generic function prototype.
4934 Value *Arg0 = EmitScalarExpr(E->getArg(0));
4935 CGOpenCLRuntime OpenCLRT(CGM);
4936 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4937 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4938 llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
4939 llvm::FunctionType *FTy = llvm::FunctionType::get(
4940 Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4941
4942 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4943 {Arg0, PacketSize, PacketAlign}));
4944 }
4945
4946 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
4947 case Builtin::BIto_global:
4948 case Builtin::BIto_local:
4949 case Builtin::BIto_private: {
4950 auto Arg0 = EmitScalarExpr(E->getArg(0));
4951 auto NewArgT = llvm::PointerType::get(Int8Ty,
4952 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
4953 auto NewRetT = llvm::PointerType::get(Int8Ty,
4954 CGM.getContext().getTargetAddressSpace(
4955 E->getType()->getPointeeType().getAddressSpace()));
4956 auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
4957 llvm::Value *NewArg;
4958 if (Arg0->getType()->getPointerAddressSpace() !=
4959 NewArgT->getPointerAddressSpace())
4960 NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
4961 else
4962 NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
4963 auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
4964 auto NewCall =
4965 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
4966 return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
4967 ConvertType(E->getType())));
4968 }
4969
4970 // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
4971 // It contains four different overload formats specified in Table 6.13.17.1.
4972 case Builtin::BIenqueue_kernel: {
4973 StringRef Name; // Generated function call name
4974 unsigned NumArgs = E->getNumArgs();
4975
4976 llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
4977 llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
4978 getContext().getTargetAddressSpace(LangAS::opencl_generic));
4979
4980 llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
4981 llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
4982 LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
4983 llvm::Value *Range = NDRangeL.getAddress(*this).getPointer();
4984 llvm::Type *RangeTy = NDRangeL.getAddress(*this).getType();
4985
4986 if (NumArgs == 4) {
4987 // The most basic form of the call with parameters:
4988 // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
4989 Name = "__enqueue_kernel_basic";
4990 llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangeTy, GenericVoidPtrTy,
4991 GenericVoidPtrTy};
4992 llvm::FunctionType *FTy = llvm::FunctionType::get(
4993 Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4994
4995 auto Info =
4996 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
4997 llvm::Value *Kernel =
4998 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
4999 llvm::Value *Block =
5000 Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5001
5002 AttrBuilder B(Builder.getContext());
5003 B.addByValAttr(NDRangeL.getAddress(*this).getElementType());
5004 llvm::AttributeList ByValAttrSet =
5005 llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);
5006
5007 auto RTCall =
5008 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name, ByValAttrSet),
5009 {Queue, Flags, Range, Kernel, Block});
5010 RTCall->setAttributes(ByValAttrSet);
5011 return RValue::get(RTCall);
5012 }
5013 assert(NumArgs >= 5 && "Invalid enqueue_kernel signature")(static_cast <bool> (NumArgs >= 5 && "Invalid enqueue_kernel signature"
) ? void (0) : __assert_fail ("NumArgs >= 5 && \"Invalid enqueue_kernel signature\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5013, __extension__ __PRETTY_FUNCTION__
))
;
5014
5015 // Create a temporary array to hold the sizes of local pointer arguments
5016 // for the block. \p First is the position of the first size argument.
5017 auto CreateArrayForSizeVar = [=](unsigned First)
5018 -> std::tuple<llvm::Value *, llvm::Value *, llvm::Value *> {
5019 llvm::APInt ArraySize(32, NumArgs - First);
5020 QualType SizeArrayTy = getContext().getConstantArrayType(
5021 getContext().getSizeType(), ArraySize, nullptr, ArrayType::Normal,
5022 /*IndexTypeQuals=*/0);
5023 auto Tmp = CreateMemTemp(SizeArrayTy, "block_sizes");
5024 llvm::Value *TmpPtr = Tmp.getPointer();
5025 llvm::Value *TmpSize = EmitLifetimeStart(
5026 CGM.getDataLayout().getTypeAllocSize(Tmp.getElementType()), TmpPtr);
5027 llvm::Value *ElemPtr;
5028 // Each of the following arguments specifies the size of the corresponding
5029 // argument passed to the enqueued block.
5030 auto *Zero = llvm::ConstantInt::get(IntTy, 0);
5031 for (unsigned I = First; I < NumArgs; ++I) {
5032 auto *Index = llvm::ConstantInt::get(IntTy, I - First);
5033 auto *GEP = Builder.CreateGEP(Tmp.getElementType(), TmpPtr,
5034 {Zero, Index});
5035 if (I == First)
5036 ElemPtr = GEP;
5037 auto *V =
5038 Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
5039 Builder.CreateAlignedStore(
5040 V, GEP, CGM.getDataLayout().getPrefTypeAlign(SizeTy));
5041 }
5042 return std::tie(ElemPtr, TmpSize, TmpPtr);
5043 };
5044
5045 // Could have events and/or varargs.
5046 if (E->getArg(3)->getType()->isBlockPointerType()) {
5047 // No events passed, but has variadic arguments.
5048 Name = "__enqueue_kernel_varargs";
5049 auto Info =
5050 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
5051 llvm::Value *Kernel =
5052 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
5053 auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5054 llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
5055 std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(4);
5056
5057 // Create a vector of the arguments, as well as a constant value to
5058 // express to the runtime the number of variadic arguments.
5059 llvm::Value *const Args[] = {Queue, Flags,
5060 Range, Kernel,
5061 Block, ConstantInt::get(IntTy, NumArgs - 4),
5062 ElemPtr};
5063 llvm::Type *const ArgTys[] = {
5064 QueueTy, IntTy, RangeTy, GenericVoidPtrTy,
5065 GenericVoidPtrTy, IntTy, ElemPtr->getType()};
5066
5067 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
5068 auto Call = RValue::get(
5069 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
5070 if (TmpSize)
5071 EmitLifetimeEnd(TmpSize, TmpPtr);
5072 return Call;
5073 }
5074 // Any calls now have event arguments passed.
5075 if (NumArgs >= 7) {
5076 llvm::Type *EventTy = ConvertType(getContext().OCLClkEventTy);
5077 llvm::PointerType *EventPtrTy = EventTy->getPointerTo(
5078 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
5079
5080 llvm::Value *NumEvents =
5081 Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
5082
5083 // Since SemaOpenCLBuiltinEnqueueKernel allows fifth and sixth arguments
5084 // to be a null pointer constant (including `0` literal), we can take it
5085 // into account and emit null pointer directly.
5086 llvm::Value *EventWaitList = nullptr;
5087 if (E->getArg(4)->isNullPointerConstant(
5088 getContext(), Expr::NPC_ValueDependentIsNotNull)) {
5089 EventWaitList = llvm::ConstantPointerNull::get(EventPtrTy);
5090 } else {
5091 EventWaitList = E->getArg(4)->getType()->isArrayType()
5092 ? EmitArrayToPointerDecay(E->getArg(4)).getPointer()
5093 : EmitScalarExpr(E->getArg(4));
5094 // Convert to generic address space.
5095 EventWaitList = Builder.CreatePointerCast(EventWaitList, EventPtrTy);
5096 }
5097 llvm::Value *EventRet = nullptr;
5098 if (E->getArg(5)->isNullPointerConstant(
5099 getContext(), Expr::NPC_ValueDependentIsNotNull)) {
5100 EventRet = llvm::ConstantPointerNull::get(EventPtrTy);
5101 } else {
5102 EventRet =
5103 Builder.CreatePointerCast(EmitScalarExpr(E->getArg(5)), EventPtrTy);
5104 }
5105
5106 auto Info =
5107 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
5108 llvm::Value *Kernel =
5109 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
5110 llvm::Value *Block =
5111 Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5112
5113 std::vector<llvm::Type *> ArgTys = {
5114 QueueTy, Int32Ty, RangeTy, Int32Ty,
5115 EventPtrTy, EventPtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
5116
5117 std::vector<llvm::Value *> Args = {Queue, Flags, Range,
5118 NumEvents, EventWaitList, EventRet,
5119 Kernel, Block};
5120
5121 if (NumArgs == 7) {
5122 // Has events but no variadics.
5123 Name = "__enqueue_kernel_basic_events";
5124 llvm::FunctionType *FTy = llvm::FunctionType::get(
5125 Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
5126 return RValue::get(
5127 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
5128 llvm::ArrayRef<llvm::Value *>(Args)));
5129 }
5130 // Has event info and variadics
5131 // Pass the number of variadics to the runtime function too.
5132 Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
5133 ArgTys.push_back(Int32Ty);
5134 Name = "__enqueue_kernel_events_varargs";
5135
5136 llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
5137 std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(7);
5138 Args.push_back(ElemPtr);
5139 ArgTys.push_back(ElemPtr->getType());
5140
5141 llvm::FunctionType *FTy = llvm::FunctionType::get(
5142 Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
5143 auto Call =
5144 RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
5145 llvm::ArrayRef<llvm::Value *>(Args)));
5146 if (TmpSize)
5147 EmitLifetimeEnd(TmpSize, TmpPtr);
5148 return Call;
5149 }
5150 [[fallthrough]];
5151 }
5152 // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
5153 // parameter.
5154 case Builtin::BIget_kernel_work_group_size: {
5155 llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5156 getContext().getTargetAddressSpace(LangAS::opencl_generic));
5157 auto Info =
5158 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
5159 Value *Kernel =
5160 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
5161 Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5162 return RValue::get(EmitRuntimeCall(
5163 CGM.CreateRuntimeFunction(
5164 llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
5165 false),
5166 "__get_kernel_work_group_size_impl"),
5167 {Kernel, Arg}));
5168 }
5169 case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
5170 llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5171 getContext().getTargetAddressSpace(LangAS::opencl_generic));
5172 auto Info =
5173 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
5174 Value *Kernel =
5175 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
5176 Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5177 return RValue::get(EmitRuntimeCall(
5178 CGM.CreateRuntimeFunction(
5179 llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
5180 false),
5181 "__get_kernel_preferred_work_group_size_multiple_impl"),
5182 {Kernel, Arg}));
5183 }
5184 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
5185 case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
5186 llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5187 getContext().getTargetAddressSpace(LangAS::opencl_generic));
5188 LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
5189 llvm::Value *NDRange = NDRangeL.getAddress(*this).getPointer();
5190 auto Info =
5191 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
5192 Value *Kernel =
5193 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
5194 Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5195 const char *Name =
5196 BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
5197 ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
5198 : "__get_kernel_sub_group_count_for_ndrange_impl";
5199 return RValue::get(EmitRuntimeCall(
5200 CGM.CreateRuntimeFunction(
5201 llvm::FunctionType::get(
5202 IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
5203 false),
5204 Name),
5205 {NDRange, Kernel, Block}));
5206 }
5207
5208 case Builtin::BI__builtin_store_half:
5209 case Builtin::BI__builtin_store_halff: {
5210 Value *Val = EmitScalarExpr(E->getArg(0));
5211 Address Address = EmitPointerWithAlignment(E->getArg(1));
5212 Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
5213 Builder.CreateStore(HalfVal, Address);
5214 return RValue::get(nullptr);
5215 }
5216 case Builtin::BI__builtin_load_half: {
5217 Address Address = EmitPointerWithAlignment(E->getArg(0));
5218 Value *HalfVal = Builder.CreateLoad(Address);
5219 return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
5220 }
5221 case Builtin::BI__builtin_load_halff: {
5222 Address Address = EmitPointerWithAlignment(E->getArg(0));
5223 Value *HalfVal = Builder.CreateLoad(Address);
5224 return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
5225 }
5226 case Builtin::BIprintf:
5227 if (getTarget().getTriple().isNVPTX() ||
5228 getTarget().getTriple().isAMDGCN()) {
5229 if (getLangOpts().OpenMPIsDevice)
5230 return EmitOpenMPDevicePrintfCallExpr(E);
5231 if (getTarget().getTriple().isNVPTX())
5232 return EmitNVPTXDevicePrintfCallExpr(E);
5233 if (getTarget().getTriple().isAMDGCN() && getLangOpts().HIP)
5234 return EmitAMDGPUDevicePrintfCallExpr(E);
5235 }
5236
5237 break;
5238 case Builtin::BI__builtin_canonicalize:
5239 case Builtin::BI__builtin_canonicalizef:
5240 case Builtin::BI__builtin_canonicalizef16:
5241 case Builtin::BI__builtin_canonicalizel:
5242 return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::canonicalize));
5243
5244 case Builtin::BI__builtin_thread_pointer: {
5245 if (!getContext().getTargetInfo().isTLSSupported())
5246 CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
5247 // Fall through - it's already mapped to the intrinsic by ClangBuiltin.
5248 break;
5249 }
5250 case Builtin::BI__builtin_os_log_format:
5251 return emitBuiltinOSLogFormat(*E);
5252
5253 case Builtin::BI__xray_customevent: {
5254 if (!ShouldXRayInstrumentFunction())
5255 return RValue::getIgnored();
5256
5257 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
5258 XRayInstrKind::Custom))
5259 return RValue::getIgnored();
5260
5261 if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
5262 if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
5263 return RValue::getIgnored();
5264
5265 Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
5266 auto FTy = F->getFunctionType();
5267 auto Arg0 = E->getArg(0);
5268 auto Arg0Val = EmitScalarExpr(Arg0);
5269 auto Arg0Ty = Arg0->getType();
5270 auto PTy0 = FTy->getParamType(0);
5271 if (PTy0 != Arg0Val->getType()) {
5272 if (Arg0Ty->isArrayType())
5273 Arg0Val = EmitArrayToPointerDecay(Arg0).getPointer();
5274 else
5275 Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
5276 }
5277 auto Arg1 = EmitScalarExpr(E->getArg(1));
5278 auto PTy1 = FTy->getParamType(1);
5279 if (PTy1 != Arg1->getType())
5280 Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
5281 return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
5282 }
5283
5284 case Builtin::BI__xray_typedevent: {
5285 // TODO: There should be a way to always emit events even if the current
5286 // function is not instrumented. Losing events in a stream can cripple
5287 // a trace.
5288 if (!ShouldXRayInstrumentFunction())
5289 return RValue::getIgnored();
5290
5291 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
5292 XRayInstrKind::Typed))
5293 return RValue::getIgnored();
5294
5295 if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
5296 if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
5297 return RValue::getIgnored();
5298
5299 Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
5300 auto FTy = F->getFunctionType();
5301 auto Arg0 = EmitScalarExpr(E->getArg(0));
5302 auto PTy0 = FTy->getParamType(0);
5303 if (PTy0 != Arg0->getType())
5304 Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
5305 auto Arg1 = E->getArg(1);
5306 auto Arg1Val = EmitScalarExpr(Arg1);
5307 auto Arg1Ty = Arg1->getType();
5308 auto PTy1 = FTy->getParamType(1);
5309 if (PTy1 != Arg1Val->getType()) {
5310 if (Arg1Ty->isArrayType())
5311 Arg1Val = EmitArrayToPointerDecay(Arg1).getPointer();
5312 else
5313 Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
5314 }
5315 auto Arg2 = EmitScalarExpr(E->getArg(2));
5316 auto PTy2 = FTy->getParamType(2);
5317 if (PTy2 != Arg2->getType())
5318 Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
5319 return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
5320 }
5321
5322 case Builtin::BI__builtin_ms_va_start:
5323 case Builtin::BI__builtin_ms_va_end:
5324 return RValue::get(
5325 EmitVAStartEnd(EmitMSVAListRef(E->getArg(0)).getPointer(),
5326 BuiltinID == Builtin::BI__builtin_ms_va_start));
5327
5328 case Builtin::BI__builtin_ms_va_copy: {
5329 // Lower this manually. We can't reliably determine whether or not any
5330 // given va_copy() is for a Win64 va_list from the calling convention
5331 // alone, because it's legal to do this from a System V ABI function.
5332 // With opaque pointer types, we won't have enough information in LLVM
5333 // IR to determine this from the argument types, either. Best to do it
5334 // now, while we have enough information.
5335 Address DestAddr = EmitMSVAListRef(E->getArg(0));
5336 Address SrcAddr = EmitMSVAListRef(E->getArg(1));
5337
5338 llvm::Type *BPP = Int8PtrPtrTy;
5339
5340 DestAddr = Address(Builder.CreateBitCast(DestAddr.getPointer(), BPP, "cp"),
5341 Int8PtrTy, DestAddr.getAlignment());
5342 SrcAddr = Address(Builder.CreateBitCast(SrcAddr.getPointer(), BPP, "ap"),
5343 Int8PtrTy, SrcAddr.getAlignment());
5344
5345 Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
5346 return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
5347 }
5348
5349 case Builtin::BI__builtin_get_device_side_mangled_name: {
5350 auto Name = CGM.getCUDARuntime().getDeviceSideName(
5351 cast<DeclRefExpr>(E->getArg(0)->IgnoreImpCasts())->getDecl());
5352 auto Str = CGM.GetAddrOfConstantCString(Name, "");
5353 llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
5354 llvm::ConstantInt::get(SizeTy, 0)};
5355 auto *Ptr = llvm::ConstantExpr::getGetElementPtr(Str.getElementType(),
5356 Str.getPointer(), Zeros);
5357 return RValue::get(Ptr);
5358 }
5359 }
5360
5361 // If this is an alias for a lib function (e.g. __builtin_sin), emit
5362 // the call using the normal call path, but using the unmangled
5363 // version of the function name.
5364 if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
5365 return emitLibraryCall(*this, FD, E,
5366 CGM.getBuiltinLibFunction(FD, BuiltinID));
5367
5368 // If this is a predefined lib function (e.g. malloc), emit the call
5369 // using exactly the normal call path.
5370 if (getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
5371 return emitLibraryCall(*this, FD, E,
5372 cast<llvm::Constant>(EmitScalarExpr(E->getCallee())));
5373
5374 // Check that a call to a target specific builtin has the correct target
5375 // features.
5376 // This is down here to avoid non-target specific builtins, however, if
5377 // generic builtins start to require generic target features then we
5378 // can move this up to the beginning of the function.
5379 checkTargetFeatures(E, FD);
5380
5381 if (unsigned VectorWidth = getContext().BuiltinInfo.getRequiredVectorWidth(BuiltinID))
5382 LargestVectorWidth = std::max(LargestVectorWidth, VectorWidth);
5383
5384 // See if we have a target specific intrinsic.
5385 StringRef Name = getContext().BuiltinInfo.getName(BuiltinID);
5386 Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
5387 StringRef Prefix =
5388 llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
5389 if (!Prefix.empty()) {
5390 IntrinsicID = Intrinsic::getIntrinsicForClangBuiltin(Prefix.data(), Name);
5391 // NOTE we don't need to perform a compatibility flag check here since the
5392 // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
5393 // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
5394 if (IntrinsicID == Intrinsic::not_intrinsic)
5395 IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
5396 }
5397
5398 if (IntrinsicID != Intrinsic::not_intrinsic) {
5399 SmallVector<Value*, 16> Args;
5400
5401 // Find out if any arguments are required to be integer constant
5402 // expressions.
5403 unsigned ICEArguments = 0;
5404 ASTContext::GetBuiltinTypeError Error;
5405 getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
5406 assert(Error == ASTContext::GE_None && "Should not codegen an error")(static_cast <bool> (Error == ASTContext::GE_None &&
"Should not codegen an error") ? void (0) : __assert_fail ("Error == ASTContext::GE_None && \"Should not codegen an error\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5406, __extension__ __PRETTY_FUNCTION__
))
;
5407
5408 Function *F = CGM.getIntrinsic(IntrinsicID);
5409 llvm::FunctionType *FTy = F->getFunctionType();
5410
5411 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
5412 Value *ArgValue;
5413 // If this is a normal argument, just emit it as a scalar.
5414 if ((ICEArguments & (1 << i)) == 0) {
5415 ArgValue = EmitScalarExpr(E->getArg(i));
5416 } else {
5417 // If this is required to be a constant, constant fold it so that we
5418 // know that the generated intrinsic gets a ConstantInt.
5419 ArgValue = llvm::ConstantInt::get(
5420 getLLVMContext(),
5421 *E->getArg(i)->getIntegerConstantExpr(getContext()));
5422 }
5423
5424 // If the intrinsic arg type is different from the builtin arg type
5425 // we need to do a bit cast.
5426 llvm::Type *PTy = FTy->getParamType(i);
5427 if (PTy != ArgValue->getType()) {
5428 // XXX - vector of pointers?
5429 if (auto *PtrTy = dyn_cast<llvm::PointerType>(PTy)) {
5430 if (PtrTy->getAddressSpace() !=
5431 ArgValue->getType()->getPointerAddressSpace()) {
5432 ArgValue = Builder.CreateAddrSpaceCast(
5433 ArgValue,
5434 ArgValue->getType()->getPointerTo(PtrTy->getAddressSpace()));
5435 }
5436 }
5437
5438 assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) &&(static_cast <bool> (PTy->canLosslesslyBitCastTo(FTy
->getParamType(i)) && "Must be able to losslessly bit cast to param"
) ? void (0) : __assert_fail ("PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) && \"Must be able to losslessly bit cast to param\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5439, __extension__ __PRETTY_FUNCTION__
))
5439 "Must be able to losslessly bit cast to param")(static_cast <bool> (PTy->canLosslesslyBitCastTo(FTy
->getParamType(i)) && "Must be able to losslessly bit cast to param"
) ? void (0) : __assert_fail ("PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) && \"Must be able to losslessly bit cast to param\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5439, __extension__ __PRETTY_FUNCTION__
))
;
5440 // Cast vector type (e.g., v256i32) to x86_amx, this only happen
5441 // in amx intrinsics.
5442 if (PTy->isX86_AMXTy())
5443 ArgValue = Builder.CreateIntrinsic(Intrinsic::x86_cast_vector_to_tile,
5444 {ArgValue->getType()}, {ArgValue});
5445 else
5446 ArgValue = Builder.CreateBitCast(ArgValue, PTy);
5447 }
5448
5449 Args.push_back(ArgValue);
5450 }
5451
5452 Value *V = Builder.CreateCall(F, Args);
5453 QualType BuiltinRetType = E->getType();
5454
5455 llvm::Type *RetTy = VoidTy;
5456 if (!BuiltinRetType->isVoidType())
5457 RetTy = ConvertType(BuiltinRetType);
5458
5459 if (RetTy != V->getType()) {
5460 // XXX - vector of pointers?
5461 if (auto *PtrTy = dyn_cast<llvm::PointerType>(RetTy)) {
5462 if (PtrTy->getAddressSpace() != V->getType()->getPointerAddressSpace()) {
5463 V = Builder.CreateAddrSpaceCast(
5464 V, V->getType()->getPointerTo(PtrTy->getAddressSpace()));
5465 }
5466 }
5467
5468 assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&(static_cast <bool> (V->getType()->canLosslesslyBitCastTo
(RetTy) && "Must be able to losslessly bit cast result type"
) ? void (0) : __assert_fail ("V->getType()->canLosslesslyBitCastTo(RetTy) && \"Must be able to losslessly bit cast result type\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5469, __extension__ __PRETTY_FUNCTION__
))
5469 "Must be able to losslessly bit cast result type")(static_cast <bool> (V->getType()->canLosslesslyBitCastTo
(RetTy) && "Must be able to losslessly bit cast result type"
) ? void (0) : __assert_fail ("V->getType()->canLosslesslyBitCastTo(RetTy) && \"Must be able to losslessly bit cast result type\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5469, __extension__ __PRETTY_FUNCTION__
))
;
5470 // Cast x86_amx to vector type (e.g., v256i32), this only happen
5471 // in amx intrinsics.
5472 if (V->getType()->isX86_AMXTy())
5473 V = Builder.CreateIntrinsic(Intrinsic::x86_cast_tile_to_vector, {RetTy},
5474 {V});
5475 else
5476 V = Builder.CreateBitCast(V, RetTy);
5477 }
5478
5479 if (RetTy->isVoidTy())
5480 return RValue::get(nullptr);
5481
5482 return RValue::get(V);
5483 }
5484
5485 // Some target-specific builtins can have aggregate return values, e.g.
5486 // __builtin_arm_mve_vld2q_u32. So if the result is an aggregate, force
5487 // ReturnValue to be non-null, so that the target-specific emission code can
5488 // always just emit into it.
5489 TypeEvaluationKind EvalKind = getEvaluationKind(E->getType());
5490 if (EvalKind == TEK_Aggregate && ReturnValue.isNull()) {
5491 Address DestPtr = CreateMemTemp(E->getType(), "agg.tmp");
5492 ReturnValue = ReturnValueSlot(DestPtr, false);
5493 }
5494
5495 // Now see if we can emit a target-specific builtin.
5496 if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E, ReturnValue)) {
5497 switch (EvalKind) {
5498 case TEK_Scalar:
5499 if (V->getType()->isVoidTy())
5500 return RValue::get(nullptr);
5501 return RValue::get(V);
5502 case TEK_Aggregate:
5503 return RValue::getAggregate(ReturnValue.getValue(),
5504 ReturnValue.isVolatile());
5505 case TEK_Complex:
5506 llvm_unreachable("No current target builtin returns complex")::llvm::llvm_unreachable_internal("No current target builtin returns complex"
, "clang/lib/CodeGen/CGBuiltin.cpp", 5506)
;
5507 }
5508 llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr")::llvm::llvm_unreachable_internal("Bad evaluation kind in EmitBuiltinExpr"
, "clang/lib/CodeGen/CGBuiltin.cpp", 5508)
;
5509 }
5510
5511 ErrorUnsupported(E, "builtin function");
5512
5513 // Unknown builtin, for now just dump it out and return undef.
5514 return GetUndefRValue(E->getType());
5515}
5516
5517static Value *EmitTargetArchBuiltinExpr(CodeGenFunction *CGF,
5518 unsigned BuiltinID, const CallExpr *E,
5519 ReturnValueSlot ReturnValue,
5520 llvm::Triple::ArchType Arch) {
5521 switch (Arch) {
5522 case llvm::Triple::arm:
5523 case llvm::Triple::armeb:
5524 case llvm::Triple::thumb:
5525 case llvm::Triple::thumbeb:
5526 return CGF->EmitARMBuiltinExpr(BuiltinID, E, ReturnValue, Arch);
5527 case llvm::Triple::aarch64:
5528 case llvm::Triple::aarch64_32:
5529 case llvm::Triple::aarch64_be:
5530 return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
5531 case llvm::Triple::bpfeb:
5532 case llvm::Triple::bpfel:
5533 return CGF->EmitBPFBuiltinExpr(BuiltinID, E);
5534 case llvm::Triple::x86:
5535 case llvm::Triple::x86_64:
5536 return CGF->EmitX86BuiltinExpr(BuiltinID, E);
5537 case llvm::Triple::ppc:
5538 case llvm::Triple::ppcle:
5539 case llvm::Triple::ppc64:
5540 case llvm::Triple::ppc64le:
5541 return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
5542 case llvm::Triple::r600:
5543 case llvm::Triple::amdgcn:
5544 return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
5545 case llvm::Triple::systemz:
5546 return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
5547 case llvm::Triple::nvptx:
5548 case llvm::Triple::nvptx64:
5549 return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
5550 case llvm::Triple::wasm32:
5551 case llvm::Triple::wasm64:
5552 return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
5553 case llvm::Triple::hexagon:
5554 return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
5555 case llvm::Triple::riscv32:
5556 case llvm::Triple::riscv64:
5557 return CGF->EmitRISCVBuiltinExpr(BuiltinID, E, ReturnValue);
5558 case llvm::Triple::loongarch32:
5559 case llvm::Triple::loongarch64:
5560 return CGF->EmitLoongArchBuiltinExpr(BuiltinID, E);
5561 default:
5562 return nullptr;
5563 }
5564}
5565
5566Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID,
5567 const CallExpr *E,
5568 ReturnValueSlot ReturnValue) {
5569 if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
5570 assert(getContext().getAuxTargetInfo() && "Missing aux target info")(static_cast <bool> (getContext().getAuxTargetInfo() &&
"Missing aux target info") ? void (0) : __assert_fail ("getContext().getAuxTargetInfo() && \"Missing aux target info\""
, "clang/lib/CodeGen/CGBuiltin.cpp", 5570, __extension__ __PRETTY_FUNCTION__
))
;
5571 return EmitTargetArchBuiltinExpr(
5572 this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
5573 ReturnValue, getContext().getAuxTargetInfo()->getTriple().getArch());
5574 }
5575
5576 return EmitTargetArchBuiltinExpr(this, BuiltinID, E, ReturnValue,
5577 getTarget().getTriple().getArch());
5578}
5579
5580static llvm::FixedVectorType *GetNeonType(CodeGenFunction *CGF,
5581 NeonTypeFlags TypeFlags,
5582 bool HasLegalHalfType = true,
5583 bool V1Ty = false,
5584 bool AllowBFloatArgsAndRet = true) {
5585 int IsQuad = TypeFlags.isQuad();
5586 switch (TypeFlags.getEltType()) {
5587 case NeonTypeFlags::Int8:
5588 case NeonTypeFlags::Poly8:
5589 return llvm::FixedVectorType::get(CGF->Int8Ty, V1Ty ? 1 : (8 << IsQuad));
5590 case NeonTypeFlags::Int16:
5591 case NeonTypeFlags::Poly16:
5592 return llvm::FixedVectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
5593 case NeonTypeFlags::BFloat16:
5594 if (AllowBFloatArgsAndRet)
5595 return llvm::FixedVectorType::get(CGF->BFloatTy, V1Ty ? 1 : (4 << IsQuad));
5596 else
5597 return llvm::FixedVectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
5598 case NeonTypeFlags::Float16:
5599 if (HasLegalHalfType)
5600 return llvm::FixedVectorType::get(CGF->HalfTy, V1Ty ? 1 : (4 << IsQuad));
5601 else
5602 return llvm::FixedVectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
5603 case NeonTypeFlags::Int32:
5604 return llvm::FixedVectorType::get(CGF->Int32Ty, V1Ty ? 1 : (2 << IsQuad));
5605 case NeonTypeFlags::Int64:
5606 case NeonTypeFlags::Poly64:
5607 return llvm::FixedVectorType::get(CGF->Int64Ty, V1Ty ? 1 : (1 << IsQuad));
5608 case NeonTypeFlags::Poly128:
5609 // FIXME: i128 and f128 doesn't get fully support in Clang and llvm.
5610 // There is a lot of i128 and f128 API missing.
5611 // so we use v16i8 to represent poly128 and get pattern matched.
5612 return llvm::FixedVectorType::get(CGF->Int8Ty, 16);
5613 case NeonTypeFlags::Float32:
5614 return llvm::FixedVectorType::get(CGF->FloatTy, V1Ty ? 1 : (2 << IsQuad));
5615 case NeonTypeFlags::Float64:
5616 return llvm::FixedVectorType::get(CGF->DoubleTy, V1Ty ? 1 : (1 << IsQuad));
5617 }
5618 llvm_unreachable("Unknown vector element type!")::llvm::llvm_unreachable_internal("Unknown vector element type!"
, "clang/lib/CodeGen/CGBuiltin.cpp", 5618)
;
5619}
5620
5621static llvm::VectorType *GetFloatNeonType(CodeGenFunction *CGF,
5622 NeonTypeFlags IntTypeFlags) {
5623 int IsQuad = IntTypeFlags.isQuad();
5624 switch (IntTypeFlags.getEltType()) {
5625 case NeonTypeFlags::Int16:
5626 return llvm::FixedVectorType::get(CGF->HalfTy, (4 << IsQuad));
5627 case NeonTypeFlags::Int32:
5628 return llvm::FixedVectorType::get(CGF->FloatTy, (2 << IsQuad));
5629 case NeonTypeFlags::Int64:
5630 return llvm::FixedVectorType::get(CGF->DoubleTy, (1 << IsQuad));
5631 default:
5632 llvm_unreachable("Type can't be converted to floating-point!")::llvm::llvm_unreachable_internal("Type can't be converted to floating-point!"
, "clang/lib/CodeGen/CGBuiltin.cpp", 5632)
;
5633 }
5634}
5635
5636Value *CodeGenFunction::EmitNeonSplat(Value *V, Constant *C,
5637 const ElementCount &Count) {
5638 Value *SV = llvm::ConstantVector::getSplat(Count, C);
5639 return Builder.CreateShuffleVector(V, V, SV, "lane");
5640}
5641
5642Value *CodeGenFunction::EmitNeonSplat(Value *V, Constant *C) {
5643 ElementCount EC = cast<llvm::VectorType>(V->getType())->getElementCount();
5644 return EmitNeonSplat(V, C, EC);
5645}
5646
5647Value *CodeGenFunction::EmitNeonCall(Function *F, SmallVectorImpl<Value*> &Ops,
5648 const char *name,
5649 unsigned shift, bool rightshift) {
5650 unsigned j = 0;
5651 for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
5652 ai != ae; ++ai, ++j) {
5653 if (F->isConstrainedFPIntrinsic())
5654 if (ai->getType()->isMetadataTy())
5655 continue;
5656 if (shift > 0 && shift == j)
5657 Ops[j] = EmitNeonShiftVector(Ops[j], ai->getType(), rightshift);
5658 else
5659 Ops[j] = Builder.CreateBitCast(Ops[j], ai->getType(), name);
5660 }
5661
5662 if (F->isConstrainedFPIntrinsic())
5663 return Builder.CreateConstrainedFPCall(F, Ops, name);
5664 else
5665 return Builder.CreateCall(F, Ops, name);
5666}
5667
5668Value *CodeGenFunction::EmitNeonShiftVector(Value *V, llvm::Type *Ty,
5669 bool neg) {
5670 int SV = cast<ConstantInt>(V)->getSExtValue();
5671 return ConstantInt::get(Ty, neg ? -SV : SV);
5672}
5673
5674// Right-shift a vector by a constant.
5675Value *CodeGenFunction::EmitNeonRShiftImm(Value *Vec, Value *Shift,
5676 llvm::Type *Ty, bool usgn,
5677 const char *name) {
5678 llvm::VectorType *VTy = cast<llvm::VectorType>(Ty);
5679
5680 int ShiftAmt = cast<ConstantInt>(Shift)->getSExtValue();
5681 int EltSize = VTy->getScalarSizeInBits();
5682
5683 Vec = Builder.CreateBitCast(Vec, Ty);
5684
5685 // lshr/ashr are undefined when the shift amount is equal to the vector
5686 // element size.
5687 if (ShiftAmt == EltSize) {
5688 if (usgn) {
5689 // Right-shifting an unsigned value by its size yields 0.
5690 return llvm::ConstantAggregateZero::get(VTy);
5691 } else {
5692 // Right-shifting a signed value by its size is equivalent
5693 // to a shift of size-1.
5694 --ShiftAmt;
5695 Shift = ConstantInt::get(VTy->getElementType(), ShiftAmt);
5696 }
5697 }
5698
5699 Shift = EmitNeonShiftVector(Shift, Ty, false);
5700 if (usgn)
5701 return Builder.CreateLShr(Vec, Shift, name);
5702 else
5703 return Builder.CreateAShr(Vec, Shift, name);
5704}
5705
5706enum {
5707 AddRetType = (1 << 0),
5708 Add1ArgType = (1 << 1),
5709 Add2ArgTypes = (1 << 2),
5710
5711 VectorizeRetType = (1 << 3),
5712 VectorizeArgTypes = (1 << 4),
5713
5714 InventFloatType = (1 << 5),
5715 UnsignedAlts = (1 << 6),
5716
5717 Use64BitVectors = (1 << 7),
5718 Use128BitVectors = (1 << 8),
5719
5720 Vectorize1ArgType = Add1ArgType | VectorizeArgTypes,
5721 VectorRet = AddRetType | VectorizeRetType,
5722 VectorRetGetArgs01 =
5723 AddRetType | Add2ArgTypes | VectorizeRetType | VectorizeArgTypes,
5724 FpCmpzModifiers =
5725 AddRetType | VectorizeRetType | Add1ArgType | InventFloatType
5726};
5727
5728namespace {
5729struct ARMVectorIntrinsicInfo {
5730 const char *NameHint;
5731 unsigned BuiltinID;
5732 unsigned LLVMIntrinsic;
5733 unsigned AltLLVMIntrinsic;
5734 uint64_t TypeModifier;
5735
5736 bool operator<(unsigned RHSBuiltinID) const {
5737 return BuiltinID < RHSBuiltinID;
5738 }
5739 bool operator<(const ARMVectorIntrinsicInfo &TE) const {
5740 return BuiltinID < TE.BuiltinID;
5741 }
5742};
5743} // end anonymous namespace
5744
5745#define NEONMAP0(NameBase) \
5746 { #NameBase, NEON::BI__builtin_neon_ ## NameBase, 0, 0, 0 }
5747
5748#define NEONMAP1(NameBase, LLVMIntrinsic, TypeModifier) \
5749 { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
5750 Intrinsic::LLVMIntrinsic, 0, TypeModifier }
5751
5752#define NEONMAP2(NameBase, LLVMIntrinsic, AltLLVMIntrinsic, TypeModifier) \
5753 { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
5754 Intrinsic::LLVMIntrinsic, Intrinsic::AltLLVMIntrinsic, \
5755 TypeModifier }
5756
5757static const ARMVectorIntrinsicInfo ARMSIMDIntrinsicMap [] = {
5758 NEONMAP1(__a32_vcvt_bf16_f32, arm_neon_vcvtfp2bf, 0),
5759 NEONMAP0(splat_lane_v),
5760 NEONMAP0(splat_laneq_v),
5761 NEONMAP0(splatq_lane_v),
5762 NEONMAP0(splatq_laneq_v),
5763 NEONMAP2(vabd_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
5764 NEONMAP2(vabdq_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
5765 NEONMAP1(vabs_v, arm_neon_vabs, 0),
5766 NEONMAP1(vabsq_v, arm_neon_vabs, 0),
5767 NEONMAP0(vadd_v),
5768 NEONMAP0(vaddhn_v),
5769 NEONMAP0(vaddq_v),
5770 NEONMAP1(vaesdq_u8, arm_neon_aesd, 0),
5771 NEONMAP1(vaeseq_u8, arm_neon_aese, 0),
5772 NEONMAP1(vaesimcq_u8, arm_neon_aesimc, 0),
5773 NEONMAP1(vaesmcq_u8, arm_neon_aesmc, 0),
5774 NEONMAP1(vbfdot_f32, arm_neon_bfdot, 0),
5775 NEONMAP1(vbfdotq_f32, arm_neon_bfdot, 0),
5776 NEONMAP1(vbfmlalbq_f32, arm_neon_bfmlalb, 0),
5777 NEONMAP1(vbfmlaltq_f32, arm_neon_bfmlalt, 0),
5778 NEONMAP1(vbfmmlaq_f32, arm_neon_bfmmla, 0),
5779 NEONMAP1(vbsl_v, arm_neon_vbsl, AddRetType),
5780 NEONMAP1(vbslq_v, arm_neon_vbsl, AddRetType),
5781 NEONMAP1(vcadd_rot270_f16, arm_neon_vcadd_rot270, Add1ArgType),
5782 NEONMAP1(vcadd_rot270_f32, arm_neon_vcadd_rot270, Add1ArgType),
5783 NEONMAP1(vcadd_rot90_f16, arm_neon_vcadd_rot90, Add1ArgType),
5784 NEONMAP1(vcadd_rot90_f32, arm_neon_vcadd_rot90, Add1ArgType),
5785 NEONMAP1(vcaddq_rot270_f16, arm_neon_vcadd_rot270, Add1ArgType),
5786 NEONMAP1(vcaddq_rot270_f32, arm_neon_vcadd_rot270, Add1ArgType),
5787 NEONMAP1(vcaddq_rot270_f64, arm_neon_vcadd_rot270, Add1ArgType),
5788 NEONMAP1(vcaddq_rot90_f16, arm_neon_vcadd_rot90, Add1ArgType),
5789 NEONMAP1(vcaddq_rot90_f32, arm_neon_vcadd_rot90, Add1ArgType),
5790 NEONMAP1(vcaddq_rot90_f64, arm_neon_vcadd_rot90, Add1ArgType),
5791 NEONMAP1(vcage_v, arm_neon_vacge, 0),
5792 NEONMAP1(vcageq_v, arm_neon_vacge, 0),
5793 NEONMAP1(vcagt_v, arm_neon_vacgt, 0),
5794 NEONMAP1(vcagtq_v, arm_neon_vacgt, 0),
5795 NEONMAP1(vcale_v, arm_neon_vacge, 0),
5796 NEONMAP1(vcaleq_v, arm_neon_vacge, 0),
5797 NEONMAP1(vcalt_v, arm_neon_vacgt, 0),
5798 NEONMAP1(vcaltq_v, arm_neon_vacgt, 0),
5799 NEONMAP0(vceqz_v),
5800 NEONMAP0(vceqzq_v),
5801 NEONMAP0(vcgez_v),
5802 NEONMAP0(vcgezq_v),
5803 NEONMAP0(vcgtz_v),
5804 NEONMAP0(vcgtzq_v),
5805 NEONMAP0(vclez_v),
5806 NEONMAP0(vclezq_v),
5807 NEONMAP1(vcls_v, arm_neon_vcls, Add1ArgType),
5808 NEONMAP1(vclsq_v, arm_neon_vcls, Add1ArgType),
5809 NEONMAP0(vcltz_v),
5810 NEONMAP0(vcltzq_v),
5811 NEONMAP1(vclz_v, ctlz, Add1ArgType),
5812 NEONMAP1(vclzq_v, ctlz, Add1ArgType),
5813 NEONMAP1(vcnt_v, ctpop, Add1ArgType),
5814 NEONMAP1(vcntq_v, ctpop, Add1ArgType),
5815 NEONMAP1(vcvt_f16_f32, arm_neon_vcvtfp2hf, 0),
5816 NEONMAP0(vcvt_f16_s16),
5817 NEONMAP0(vcvt_f16_u16),
5818 NEONMAP1(vcvt_f32_f16, arm_neon_vcvthf2fp, 0),
5819 NEONMAP0(vcvt_f32_v),
5820 NEONMAP1(vcvt_n_f16_s16, arm_neon_vcvtfxs2fp, 0),
5821 NEONMAP1(vcvt_n_f16_u16, arm_neon_vcvtfxu2fp, 0),
5822 NEONMAP2(vcvt_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
5823 NEONMAP1(vcvt_n_s16_f16, arm_neon_vcvtfp2fxs, 0),
5824 NEONMAP1(vcvt_n_s32_v, arm_neon_vcvtfp2fxs, 0),
5825 NEONMAP1(vcvt_n_s64_v, arm_neon_vcvtfp2fxs, 0),
5826 NEONMAP1(vcvt_n_u16_f16, arm_neon_vcvtfp2fxu, 0),
5827 NEONMAP1(vcvt_n_u32_v, arm_neon_vcvtfp2fxu, 0),
5828 NEONMAP1(vcvt_n_u64_v, arm_neon_vcvtfp2fxu, 0),
5829 NEONMAP0(vcvt_s16_f16),
5830 NEONMAP0(vcvt_s32_v),
5831 NEONMAP0(vcvt_s64_v),
5832 NEONMAP0(vcvt_u16_f16),
5833 NEONMAP0(vcvt_u32_v),
5834 NEONMAP0(vcvt_u64_v),
5835 NEONMAP1(vcvta_s16_f16, arm_neon_vcvtas, 0),
5836 NEONMAP1(vcvta_s32_v, arm_neon_vcvtas, 0),
5837 NEONMAP1(vcvta_s64_v, arm_neon_vcvtas, 0),
5838 NEONMAP1(vcvta_u16_f16, arm_neon_vcvtau, 0),
5839 NEONMAP1(vcvta_u32_v, arm_neon_vcvtau, 0),
5840 NEONMAP1(vcvta_u64_v, arm_neon_vcvtau, 0),
5841 NEONMAP1(vcvtaq_s16_f16, arm_neon_vcvtas, 0),
5842 NEONMAP1(vcvtaq_s32_v, arm_neon_vcvtas, 0),
5843 NEONMAP1(vcvtaq_s64_v, arm_neon_vcvtas, 0),
5844 NEONMAP1(vcvtaq_u16_f16, arm_neon_vcvtau, 0),
5845 NEONMAP1(vcvtaq_u32_v, arm_neon_vcvtau, 0),
5846 NEONMAP1(vcvtaq_u64_v, arm_neon_vcvtau, 0),
5847 NEONMAP1(vcvth_bf16_f32, arm_neon_vcvtbfp2bf, 0),
5848 NEONMAP1(vcvtm_s16_f16, arm_neon_vcvtms, 0),
5849 NEONMAP1(vcvtm_s32_v, arm_neon_vcvtms, 0),
5850 NEONMAP1(vcvtm_s64_v, arm_neon_vcvtms, 0),
5851 NEONMAP1(vcvtm_u16_f16, arm_neon_vcvtmu, 0),
5852 NEONMAP1(vcvtm_u32_v, arm_neon_vcvtmu, 0),
5853 NEONMAP1(vcvtm_u64_v, arm_neon_vcvtmu, 0),
5854 NEONMAP1(vcvtmq_s16_f16, arm_neon_vcvtms, 0),
5855 NEONMAP1(vcvtmq_s32_v, arm_neon_vcvtms, 0),
5856 NEONMAP1(vcvtmq_s64_v, arm_neon_vcvtms, 0),
5857 NEONMAP1(vcvtmq_u16_f16, arm_neon_vcvtmu, 0),
5858 NEONMAP1(vcvtmq_u32_v, arm_neon_vcvtmu, 0),
5859 NEONMAP1(vcvtmq_u64_v, arm_neon_vcvtmu, 0),
5860 NEONMAP1(vcvtn_s16_f16, arm_neon_vcvtns, 0),
5861 NEONMAP1(vcvtn_s32_v, arm_neon_vcvtns, 0),
5862 NEONMAP1(vcvtn_s64_v, arm_neon_vcvtns, 0),
5863 NEONMAP1(vcvtn_u16_f16, arm_neon_vcvtnu, 0),
5864 NEONMAP1(vcvtn_u32_v, arm_neon_vcvtnu, 0),
5865 NEONMAP1(vcvtn_u64_v, arm_neon_vcvtnu, 0),
5866 NEONMAP1(vcvtnq_s16_f16, arm_neon_vcvtns, 0),
5867 NEONMAP1(vcvtnq_s32_v, arm_neon_vcvtns, 0),
5868 NEONMAP1(vcvtnq_s64_v, arm_neon_vcvtns, 0),
5869 NEONMAP1(vcvtnq_u16_f16, arm_neon_vcvtnu, 0),
5870 NEONMAP1(vcvtnq_u32_v, arm_neon_vcvtnu, 0),
5871 NEONMAP1(vcvtnq_u64_v, arm_neon_vcvtnu, 0),
5872 NEONMAP1(vcvtp_s16_f16, arm_neon_vcvtps, 0),
5873 NEONMAP1(vcvtp_s32_v, arm_neon_vcvtps, 0),
5874 NEONMAP1(vcvtp_s64_v, arm_neon_vcvtps, 0),
5875 NEONMAP1(vcvtp_u16_f16, arm_neon_vcvtpu, 0),
5876 NEONMAP1(vcvtp_u32_v, arm_neon_vcvtpu, 0),
5877 NEONMAP1(vcvtp_u64_v, arm_neon_vcvtpu, 0),
5878 NEONMAP1(vcvtpq_s16_f16, arm_neon_vcvtps, 0),
5879 NEONMAP1(vcvtpq_s32_v, arm_neon_vcvtps, 0),
5880 NEONMAP1(vcvtpq_s64_v, arm_neon_vcvtps, 0),
5881 NEONMAP1(vcvtpq_u16_f16, arm_neon_vcvtpu, 0),
5882 NEONMAP1(vcvtpq_u32_v, arm_neon_vcvtpu, 0),
5883 NEONMAP1(vcvtpq_u64_v, arm_neon_vcvtpu, 0),
5884 NEONMAP0(vcvtq_f16_s16),
5885 NEONMAP0(vcvtq_f16_u16),
5886 NEONMAP0(vcvtq_f32_v),
5887 NEONMAP1(vcvtq_n_f16_s16, arm_neon_vcvtfxs2fp, 0),
5888 NEONMAP1(vcvtq_n_f16_u16, arm_neon_vcvtfxu2fp, 0),
5889 NEONMAP2(vcvtq_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
5890 NEONMAP1(vcvtq_n_s16_f16, arm_neon_vcvtfp2fxs, 0),
5891 NEONMAP1(vcvtq_n_s32_v, arm_neon_vcvtfp2fxs, 0),
5892 NEONMAP1(vcvtq_n_s64_v, arm_neon_vcvtfp2fxs, 0),
5893 NEONMAP1(vcvtq_n_u16_f16, arm_neon_vcvtfp2fxu, 0),
5894 NEONMAP1(vcvtq_n_u32_v, arm_neon_vcvtfp2fxu, 0),
5895 NEONMAP1(vcvtq_n_u64_v, arm_neon_vcvtfp2fxu, 0),
5896 NEONMAP0(vcvtq_s16_f16),
5897