Coverage Report

Created: 2020-02-25 14:32

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