Bug Summary

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