Coverage Report

Created: 2022-01-18 06:27

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