Coverage Report

Created: 2021-01-19 06:58

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