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