Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/CodeGen/CGBuiltin.cpp
Warning:line 15588, column 5
Undefined or garbage value returned to caller

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