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