Bug Summary

File:clang/lib/CodeGen/CGBuiltin.cpp
Warning:line 1026, column 22
Value stored to 'RetType' during its initialization is never read

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