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