Coverage Report

Created: 2022-07-16 07:03

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