clang  7.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->getLocStart());
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 both x64 and ARM; to avoid repeating code, we
736 // 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 
1256  unsigned BuiltinID, const CallExpr *E,
1257  ReturnValueSlot ReturnValue) {
1258  // See if we can constant fold this builtin. If so, don't emit it at all.
1259  Expr::EvalResult Result;
1260  if (E->EvaluateAsRValue(Result, CGM.getContext()) &&
1261  !Result.hasSideEffects()) {
1262  if (Result.Val.isInt())
1263  return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
1264  Result.Val.getInt()));
1265  if (Result.Val.isFloat())
1266  return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
1267  Result.Val.getFloat()));
1268  }
1269 
1270  // There are LLVM math intrinsics/instructions corresponding to math library
1271  // functions except the LLVM op will never set errno while the math library
1272  // might. Also, math builtins have the same semantics as their math library
1273  // twins. Thus, we can transform math library and builtin calls to their
1274  // LLVM counterparts if the call is marked 'const' (known to never set errno).
1275  if (FD->hasAttr<ConstAttr>()) {
1276  switch (BuiltinID) {
1277  case Builtin::BIceil:
1278  case Builtin::BIceilf:
1279  case Builtin::BIceill:
1280  case Builtin::BI__builtin_ceil:
1281  case Builtin::BI__builtin_ceilf:
1282  case Builtin::BI__builtin_ceill:
1283  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::ceil));
1284 
1285  case Builtin::BIcopysign:
1286  case Builtin::BIcopysignf:
1287  case Builtin::BIcopysignl:
1288  case Builtin::BI__builtin_copysign:
1289  case Builtin::BI__builtin_copysignf:
1290  case Builtin::BI__builtin_copysignl:
1291  case Builtin::BI__builtin_copysignf128:
1293 
1294  case Builtin::BIcos:
1295  case Builtin::BIcosf:
1296  case Builtin::BIcosl:
1297  case Builtin::BI__builtin_cos:
1298  case Builtin::BI__builtin_cosf:
1299  case Builtin::BI__builtin_cosl:
1300  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::cos));
1301 
1302  case Builtin::BIexp:
1303  case Builtin::BIexpf:
1304  case Builtin::BIexpl:
1305  case Builtin::BI__builtin_exp:
1306  case Builtin::BI__builtin_expf:
1307  case Builtin::BI__builtin_expl:
1308  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::exp));
1309 
1310  case Builtin::BIexp2:
1311  case Builtin::BIexp2f:
1312  case Builtin::BIexp2l:
1313  case Builtin::BI__builtin_exp2:
1314  case Builtin::BI__builtin_exp2f:
1315  case Builtin::BI__builtin_exp2l:
1316  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::exp2));
1317 
1318  case Builtin::BIfabs:
1319  case Builtin::BIfabsf:
1320  case Builtin::BIfabsl:
1321  case Builtin::BI__builtin_fabs:
1322  case Builtin::BI__builtin_fabsf:
1323  case Builtin::BI__builtin_fabsl:
1324  case Builtin::BI__builtin_fabsf128:
1325  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::fabs));
1326 
1327  case Builtin::BIfloor:
1328  case Builtin::BIfloorf:
1329  case Builtin::BIfloorl:
1330  case Builtin::BI__builtin_floor:
1331  case Builtin::BI__builtin_floorf:
1332  case Builtin::BI__builtin_floorl:
1333  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::floor));
1334 
1335  case Builtin::BIfma:
1336  case Builtin::BIfmaf:
1337  case Builtin::BIfmal:
1338  case Builtin::BI__builtin_fma:
1339  case Builtin::BI__builtin_fmaf:
1340  case Builtin::BI__builtin_fmal:
1341  return RValue::get(emitTernaryBuiltin(*this, E, Intrinsic::fma));
1342 
1343  case Builtin::BIfmax:
1344  case Builtin::BIfmaxf:
1345  case Builtin::BIfmaxl:
1346  case Builtin::BI__builtin_fmax:
1347  case Builtin::BI__builtin_fmaxf:
1348  case Builtin::BI__builtin_fmaxl:
1349  return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::maxnum));
1350 
1351  case Builtin::BIfmin:
1352  case Builtin::BIfminf:
1353  case Builtin::BIfminl:
1354  case Builtin::BI__builtin_fmin:
1355  case Builtin::BI__builtin_fminf:
1356  case Builtin::BI__builtin_fminl:
1357  return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::minnum));
1358 
1359  // fmod() is a special-case. It maps to the frem instruction rather than an
1360  // LLVM intrinsic.
1361  case Builtin::BIfmod:
1362  case Builtin::BIfmodf:
1363  case Builtin::BIfmodl:
1364  case Builtin::BI__builtin_fmod:
1365  case Builtin::BI__builtin_fmodf:
1366  case Builtin::BI__builtin_fmodl: {
1367  Value *Arg1 = EmitScalarExpr(E->getArg(0));
1368  Value *Arg2 = EmitScalarExpr(E->getArg(1));
1369  return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
1370  }
1371 
1372  case Builtin::BIlog:
1373  case Builtin::BIlogf:
1374  case Builtin::BIlogl:
1375  case Builtin::BI__builtin_log:
1376  case Builtin::BI__builtin_logf:
1377  case Builtin::BI__builtin_logl:
1378  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::log));
1379 
1380  case Builtin::BIlog10:
1381  case Builtin::BIlog10f:
1382  case Builtin::BIlog10l:
1383  case Builtin::BI__builtin_log10:
1384  case Builtin::BI__builtin_log10f:
1385  case Builtin::BI__builtin_log10l:
1386  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::log10));
1387 
1388  case Builtin::BIlog2:
1389  case Builtin::BIlog2f:
1390  case Builtin::BIlog2l:
1391  case Builtin::BI__builtin_log2:
1392  case Builtin::BI__builtin_log2f:
1393  case Builtin::BI__builtin_log2l:
1394  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::log2));
1395 
1396  case Builtin::BInearbyint:
1397  case Builtin::BInearbyintf:
1398  case Builtin::BInearbyintl:
1399  case Builtin::BI__builtin_nearbyint:
1400  case Builtin::BI__builtin_nearbyintf:
1401  case Builtin::BI__builtin_nearbyintl:
1403 
1404  case Builtin::BIpow:
1405  case Builtin::BIpowf:
1406  case Builtin::BIpowl:
1407  case Builtin::BI__builtin_pow:
1408  case Builtin::BI__builtin_powf:
1409  case Builtin::BI__builtin_powl:
1410  return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::pow));
1411 
1412  case Builtin::BIrint:
1413  case Builtin::BIrintf:
1414  case Builtin::BIrintl:
1415  case Builtin::BI__builtin_rint:
1416  case Builtin::BI__builtin_rintf:
1417  case Builtin::BI__builtin_rintl:
1418  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::rint));
1419 
1420  case Builtin::BIround:
1421  case Builtin::BIroundf:
1422  case Builtin::BIroundl:
1423  case Builtin::BI__builtin_round:
1424  case Builtin::BI__builtin_roundf:
1425  case Builtin::BI__builtin_roundl:
1426  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::round));
1427 
1428  case Builtin::BIsin:
1429  case Builtin::BIsinf:
1430  case Builtin::BIsinl:
1431  case Builtin::BI__builtin_sin:
1432  case Builtin::BI__builtin_sinf:
1433  case Builtin::BI__builtin_sinl:
1434  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::sin));
1435 
1436  case Builtin::BIsqrt:
1437  case Builtin::BIsqrtf:
1438  case Builtin::BIsqrtl:
1439  case Builtin::BI__builtin_sqrt:
1440  case Builtin::BI__builtin_sqrtf:
1441  case Builtin::BI__builtin_sqrtl:
1442  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::sqrt));
1443 
1444  case Builtin::BItrunc:
1445  case Builtin::BItruncf:
1446  case Builtin::BItruncl:
1447  case Builtin::BI__builtin_trunc:
1448  case Builtin::BI__builtin_truncf:
1449  case Builtin::BI__builtin_truncl:
1450  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::trunc));
1451 
1452  default:
1453  break;
1454  }
1455  }
1456 
1457  switch (BuiltinID) {
1458  default: break;
1459  case Builtin::BI__builtin___CFStringMakeConstantString:
1460  case Builtin::BI__builtin___NSStringMakeConstantString:
1461  return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
1462  case Builtin::BI__builtin_stdarg_start:
1463  case Builtin::BI__builtin_va_start:
1464  case Builtin::BI__va_start:
1465  case Builtin::BI__builtin_va_end:
1466  return RValue::get(
1467  EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
1468  ? EmitScalarExpr(E->getArg(0))
1469  : EmitVAListRef(E->getArg(0)).getPointer(),
1470  BuiltinID != Builtin::BI__builtin_va_end));
1471  case Builtin::BI__builtin_va_copy: {
1472  Value *DstPtr = EmitVAListRef(E->getArg(0)).getPointer();
1473  Value *SrcPtr = EmitVAListRef(E->getArg(1)).getPointer();
1474 
1475  llvm::Type *Type = Int8PtrTy;
1476 
1477  DstPtr = Builder.CreateBitCast(DstPtr, Type);
1478  SrcPtr = Builder.CreateBitCast(SrcPtr, Type);
1479  return RValue::get(Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy),
1480  {DstPtr, SrcPtr}));
1481  }
1482  case Builtin::BI__builtin_abs:
1483  case Builtin::BI__builtin_labs:
1484  case Builtin::BI__builtin_llabs: {
1485  // X < 0 ? -X : X
1486  // The negation has 'nsw' because abs of INT_MIN is undefined.
1487  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1488  Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg");
1489  Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType());
1490  Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
1491  Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs");
1492  return RValue::get(Result);
1493  }
1494  case Builtin::BI__builtin_conj:
1495  case Builtin::BI__builtin_conjf:
1496  case Builtin::BI__builtin_conjl: {
1497  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
1498  Value *Real = ComplexVal.first;
1499  Value *Imag = ComplexVal.second;
1500  Value *Zero =
1501  Imag->getType()->isFPOrFPVectorTy()
1502  ? llvm::ConstantFP::getZeroValueForNegation(Imag->getType())
1503  : llvm::Constant::getNullValue(Imag->getType());
1504 
1505  Imag = Builder.CreateFSub(Zero, Imag, "sub");
1506  return RValue::getComplex(std::make_pair(Real, Imag));
1507  }
1508  case Builtin::BI__builtin_creal:
1509  case Builtin::BI__builtin_crealf:
1510  case Builtin::BI__builtin_creall:
1511  case Builtin::BIcreal:
1512  case Builtin::BIcrealf:
1513  case Builtin::BIcreall: {
1514  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
1515  return RValue::get(ComplexVal.first);
1516  }
1517 
1518  case Builtin::BI__builtin_dump_struct: {
1519  Value *Func = EmitScalarExpr(E->getArg(1)->IgnoreImpCasts());
1520  CharUnits Arg0Align = EmitPointerWithAlignment(E->getArg(0)).getAlignment();
1521 
1522  const Expr *Arg0 = E->getArg(0)->IgnoreImpCasts();
1523  QualType Arg0Type = Arg0->getType()->getPointeeType();
1524 
1525  Value *RecordPtr = EmitScalarExpr(Arg0);
1526  Value *Res = dumpRecord(*this, Arg0Type, RecordPtr, Arg0Align, Func, 0);
1527  return RValue::get(Res);
1528  }
1529 
1530  case Builtin::BI__builtin_cimag:
1531  case Builtin::BI__builtin_cimagf:
1532  case Builtin::BI__builtin_cimagl:
1533  case Builtin::BIcimag:
1534  case Builtin::BIcimagf:
1535  case Builtin::BIcimagl: {
1536  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
1537  return RValue::get(ComplexVal.second);
1538  }
1539 
1540  case Builtin::BI__builtin_ctzs:
1541  case Builtin::BI__builtin_ctz:
1542  case Builtin::BI__builtin_ctzl:
1543  case Builtin::BI__builtin_ctzll: {
1544  Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CTZPassedZero);
1545 
1546  llvm::Type *ArgType = ArgValue->getType();
1547  Value *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1548 
1549  llvm::Type *ResultType = ConvertType(E->getType());
1550  Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
1551  Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
1552  if (Result->getType() != ResultType)
1553  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1554  "cast");
1555  return RValue::get(Result);
1556  }
1557  case Builtin::BI__builtin_clzs:
1558  case Builtin::BI__builtin_clz:
1559  case Builtin::BI__builtin_clzl:
1560  case Builtin::BI__builtin_clzll: {
1561  Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CLZPassedZero);
1562 
1563  llvm::Type *ArgType = ArgValue->getType();
1564  Value *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1565 
1566  llvm::Type *ResultType = ConvertType(E->getType());
1567  Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
1568  Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
1569  if (Result->getType() != ResultType)
1570  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1571  "cast");
1572  return RValue::get(Result);
1573  }
1574  case Builtin::BI__builtin_ffs:
1575  case Builtin::BI__builtin_ffsl:
1576  case Builtin::BI__builtin_ffsll: {
1577  // ffs(x) -> x ? cttz(x) + 1 : 0
1578  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1579 
1580  llvm::Type *ArgType = ArgValue->getType();
1581  Value *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1582 
1583  llvm::Type *ResultType = ConvertType(E->getType());
1584  Value *Tmp =
1585  Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
1586  llvm::ConstantInt::get(ArgType, 1));
1587  Value *Zero = llvm::Constant::getNullValue(ArgType);
1588  Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
1589  Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
1590  if (Result->getType() != ResultType)
1591  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1592  "cast");
1593  return RValue::get(Result);
1594  }
1595  case Builtin::BI__builtin_parity:
1596  case Builtin::BI__builtin_parityl:
1597  case Builtin::BI__builtin_parityll: {
1598  // parity(x) -> ctpop(x) & 1
1599  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1600 
1601  llvm::Type *ArgType = ArgValue->getType();
1602  Value *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
1603 
1604  llvm::Type *ResultType = ConvertType(E->getType());
1605  Value *Tmp = Builder.CreateCall(F, ArgValue);
1606  Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
1607  if (Result->getType() != ResultType)
1608  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1609  "cast");
1610  return RValue::get(Result);
1611  }
1612  case Builtin::BI__popcnt16:
1613  case Builtin::BI__popcnt:
1614  case Builtin::BI__popcnt64:
1615  case Builtin::BI__builtin_popcount:
1616  case Builtin::BI__builtin_popcountl:
1617  case Builtin::BI__builtin_popcountll: {
1618  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1619 
1620  llvm::Type *ArgType = ArgValue->getType();
1621  Value *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
1622 
1623  llvm::Type *ResultType = ConvertType(E->getType());
1624  Value *Result = Builder.CreateCall(F, ArgValue);
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_rotr8:
1631  case Builtin::BI_rotr16:
1632  case Builtin::BI_rotr:
1633  case Builtin::BI_lrotr:
1634  case Builtin::BI_rotr64: {
1635  Value *Val = EmitScalarExpr(E->getArg(0));
1636  Value *Shift = EmitScalarExpr(E->getArg(1));
1637 
1638  llvm::Type *ArgType = Val->getType();
1639  Shift = Builder.CreateIntCast(Shift, ArgType, false);
1640  unsigned ArgWidth = ArgType->getIntegerBitWidth();
1641  Value *Mask = llvm::ConstantInt::get(ArgType, ArgWidth - 1);
1642 
1643  Value *RightShiftAmt = Builder.CreateAnd(Shift, Mask);
1644  Value *RightShifted = Builder.CreateLShr(Val, RightShiftAmt);
1645  Value *LeftShiftAmt = Builder.CreateAnd(Builder.CreateNeg(Shift), Mask);
1646  Value *LeftShifted = Builder.CreateShl(Val, LeftShiftAmt);
1647  Value *Result = Builder.CreateOr(LeftShifted, RightShifted);
1648  return RValue::get(Result);
1649  }
1650  case Builtin::BI_rotl8:
1651  case Builtin::BI_rotl16:
1652  case Builtin::BI_rotl:
1653  case Builtin::BI_lrotl:
1654  case Builtin::BI_rotl64: {
1655  Value *Val = EmitScalarExpr(E->getArg(0));
1656  Value *Shift = EmitScalarExpr(E->getArg(1));
1657 
1658  llvm::Type *ArgType = Val->getType();
1659  Shift = Builder.CreateIntCast(Shift, ArgType, false);
1660  unsigned ArgWidth = ArgType->getIntegerBitWidth();
1661  Value *Mask = llvm::ConstantInt::get(ArgType, ArgWidth - 1);
1662 
1663  Value *LeftShiftAmt = Builder.CreateAnd(Shift, Mask);
1664  Value *LeftShifted = Builder.CreateShl(Val, LeftShiftAmt);
1665  Value *RightShiftAmt = Builder.CreateAnd(Builder.CreateNeg(Shift), Mask);
1666  Value *RightShifted = Builder.CreateLShr(Val, RightShiftAmt);
1667  Value *Result = Builder.CreateOr(LeftShifted, RightShifted);
1668  return RValue::get(Result);
1669  }
1670  case Builtin::BI__builtin_unpredictable: {
1671  // Always return the argument of __builtin_unpredictable. LLVM does not
1672  // handle this builtin. Metadata for this builtin should be added directly
1673  // to instructions such as branches or switches that use it.
1674  return RValue::get(EmitScalarExpr(E->getArg(0)));
1675  }
1676  case Builtin::BI__builtin_expect: {
1677  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1678  llvm::Type *ArgType = ArgValue->getType();
1679 
1680  Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
1681  // Don't generate llvm.expect on -O0 as the backend won't use it for
1682  // anything.
1683  // Note, we still IRGen ExpectedValue because it could have side-effects.
1684  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1685  return RValue::get(ArgValue);
1686 
1687  Value *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
1688  Value *Result =
1689  Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
1690  return RValue::get(Result);
1691  }
1692  case Builtin::BI__builtin_assume_aligned: {
1693  Value *PtrValue = EmitScalarExpr(E->getArg(0));
1694  Value *OffsetValue =
1695  (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
1696 
1697  Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
1698  ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
1699  unsigned Alignment = (unsigned) AlignmentCI->getZExtValue();
1700 
1701  EmitAlignmentAssumption(PtrValue, Alignment, OffsetValue);
1702  return RValue::get(PtrValue);
1703  }
1704  case Builtin::BI__assume:
1705  case Builtin::BI__builtin_assume: {
1706  if (E->getArg(0)->HasSideEffects(getContext()))
1707  return RValue::get(nullptr);
1708 
1709  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1710  Value *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
1711  return RValue::get(Builder.CreateCall(FnAssume, ArgValue));
1712  }
1713  case Builtin::BI__builtin_bswap16:
1714  case Builtin::BI__builtin_bswap32:
1715  case Builtin::BI__builtin_bswap64: {
1716  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
1717  }
1718  case Builtin::BI__builtin_bitreverse8:
1719  case Builtin::BI__builtin_bitreverse16:
1720  case Builtin::BI__builtin_bitreverse32:
1721  case Builtin::BI__builtin_bitreverse64: {
1722  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bitreverse));
1723  }
1724  case Builtin::BI__builtin_object_size: {
1725  unsigned Type =
1726  E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
1727  auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
1728 
1729  // We pass this builtin onto the optimizer so that it can figure out the
1730  // object size in more complex cases.
1731  return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
1732  /*EmittedE=*/nullptr));
1733  }
1734  case Builtin::BI__builtin_prefetch: {
1735  Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
1736  // FIXME: Technically these constants should of type 'int', yes?
1737  RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) :
1738  llvm::ConstantInt::get(Int32Ty, 0);
1739  Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) :
1740  llvm::ConstantInt::get(Int32Ty, 3);
1741  Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
1742  Value *F = CGM.getIntrinsic(Intrinsic::prefetch);
1743  return RValue::get(Builder.CreateCall(F, {Address, RW, Locality, Data}));
1744  }
1745  case Builtin::BI__builtin_readcyclecounter: {
1746  Value *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
1747  return RValue::get(Builder.CreateCall(F));
1748  }
1749  case Builtin::BI__builtin___clear_cache: {
1750  Value *Begin = EmitScalarExpr(E->getArg(0));
1751  Value *End = EmitScalarExpr(E->getArg(1));
1752  Value *F = CGM.getIntrinsic(Intrinsic::clear_cache);
1753  return RValue::get(Builder.CreateCall(F, {Begin, End}));
1754  }
1755  case Builtin::BI__builtin_trap:
1756  return RValue::get(EmitTrapCall(Intrinsic::trap));
1757  case Builtin::BI__debugbreak:
1758  return RValue::get(EmitTrapCall(Intrinsic::debugtrap));
1759  case Builtin::BI__builtin_unreachable: {
1760  EmitUnreachable(E->getExprLoc());
1761 
1762  // We do need to preserve an insertion point.
1763  EmitBlock(createBasicBlock("unreachable.cont"));
1764 
1765  return RValue::get(nullptr);
1766  }
1767 
1768  case Builtin::BI__builtin_powi:
1769  case Builtin::BI__builtin_powif:
1770  case Builtin::BI__builtin_powil: {
1771  Value *Base = EmitScalarExpr(E->getArg(0));
1772  Value *Exponent = EmitScalarExpr(E->getArg(1));
1773  llvm::Type *ArgType = Base->getType();
1774  Value *F = CGM.getIntrinsic(Intrinsic::powi, ArgType);
1775  return RValue::get(Builder.CreateCall(F, {Base, Exponent}));
1776  }
1777 
1778  case Builtin::BI__builtin_isgreater:
1779  case Builtin::BI__builtin_isgreaterequal:
1780  case Builtin::BI__builtin_isless:
1781  case Builtin::BI__builtin_islessequal:
1782  case Builtin::BI__builtin_islessgreater:
1783  case Builtin::BI__builtin_isunordered: {
1784  // Ordered comparisons: we know the arguments to these are matching scalar
1785  // floating point values.
1786  Value *LHS = EmitScalarExpr(E->getArg(0));
1787  Value *RHS = EmitScalarExpr(E->getArg(1));
1788 
1789  switch (BuiltinID) {
1790  default: llvm_unreachable("Unknown ordered comparison");
1791  case Builtin::BI__builtin_isgreater:
1792  LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
1793  break;
1794  case Builtin::BI__builtin_isgreaterequal:
1795  LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
1796  break;
1797  case Builtin::BI__builtin_isless:
1798  LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
1799  break;
1800  case Builtin::BI__builtin_islessequal:
1801  LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
1802  break;
1803  case Builtin::BI__builtin_islessgreater:
1804  LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
1805  break;
1806  case Builtin::BI__builtin_isunordered:
1807  LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
1808  break;
1809  }
1810  // ZExt bool to int type.
1811  return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
1812  }
1813  case Builtin::BI__builtin_isnan: {
1814  Value *V = EmitScalarExpr(E->getArg(0));
1815  V = Builder.CreateFCmpUNO(V, V, "cmp");
1816  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
1817  }
1818 
1819  case Builtin::BIfinite:
1820  case Builtin::BI__finite:
1821  case Builtin::BIfinitef:
1822  case Builtin::BI__finitef:
1823  case Builtin::BIfinitel:
1824  case Builtin::BI__finitel:
1825  case Builtin::BI__builtin_isinf:
1826  case Builtin::BI__builtin_isfinite: {
1827  // isinf(x) --> fabs(x) == infinity
1828  // isfinite(x) --> fabs(x) != infinity
1829  // x != NaN via the ordered compare in either case.
1830  Value *V = EmitScalarExpr(E->getArg(0));
1831  Value *Fabs = EmitFAbs(*this, V);
1832  Constant *Infinity = ConstantFP::getInfinity(V->getType());
1833  CmpInst::Predicate Pred = (BuiltinID == Builtin::BI__builtin_isinf)
1834  ? CmpInst::FCMP_OEQ
1835  : CmpInst::FCMP_ONE;
1836  Value *FCmp = Builder.CreateFCmp(Pred, Fabs, Infinity, "cmpinf");
1837  return RValue::get(Builder.CreateZExt(FCmp, ConvertType(E->getType())));
1838  }
1839 
1840  case Builtin::BI__builtin_isinf_sign: {
1841  // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
1842  Value *Arg = EmitScalarExpr(E->getArg(0));
1843  Value *AbsArg = EmitFAbs(*this, Arg);
1844  Value *IsInf = Builder.CreateFCmpOEQ(
1845  AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
1846  Value *IsNeg = EmitSignBit(*this, Arg);
1847 
1848  llvm::Type *IntTy = ConvertType(E->getType());
1849  Value *Zero = Constant::getNullValue(IntTy);
1850  Value *One = ConstantInt::get(IntTy, 1);
1851  Value *NegativeOne = ConstantInt::get(IntTy, -1);
1852  Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
1853  Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
1854  return RValue::get(Result);
1855  }
1856 
1857  case Builtin::BI__builtin_isnormal: {
1858  // isnormal(x) --> x == x && fabsf(x) < infinity && fabsf(x) >= float_min
1859  Value *V = EmitScalarExpr(E->getArg(0));
1860  Value *Eq = Builder.CreateFCmpOEQ(V, V, "iseq");
1861 
1862  Value *Abs = EmitFAbs(*this, V);
1863  Value *IsLessThanInf =
1864  Builder.CreateFCmpULT(Abs, ConstantFP::getInfinity(V->getType()),"isinf");
1865  APFloat Smallest = APFloat::getSmallestNormalized(
1866  getContext().getFloatTypeSemantics(E->getArg(0)->getType()));
1867  Value *IsNormal =
1868  Builder.CreateFCmpUGE(Abs, ConstantFP::get(V->getContext(), Smallest),
1869  "isnormal");
1870  V = Builder.CreateAnd(Eq, IsLessThanInf, "and");
1871  V = Builder.CreateAnd(V, IsNormal, "and");
1872  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
1873  }
1874 
1875  case Builtin::BI__builtin_fpclassify: {
1876  Value *V = EmitScalarExpr(E->getArg(5));
1877  llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
1878 
1879  // Create Result
1880  BasicBlock *Begin = Builder.GetInsertBlock();
1881  BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
1882  Builder.SetInsertPoint(End);
1883  PHINode *Result =
1884  Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
1885  "fpclassify_result");
1886 
1887  // if (V==0) return FP_ZERO
1888  Builder.SetInsertPoint(Begin);
1889  Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
1890  "iszero");
1891  Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
1892  BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
1893  Builder.CreateCondBr(IsZero, End, NotZero);
1894  Result->addIncoming(ZeroLiteral, Begin);
1895 
1896  // if (V != V) return FP_NAN
1897  Builder.SetInsertPoint(NotZero);
1898  Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
1899  Value *NanLiteral = EmitScalarExpr(E->getArg(0));
1900  BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
1901  Builder.CreateCondBr(IsNan, End, NotNan);
1902  Result->addIncoming(NanLiteral, NotZero);
1903 
1904  // if (fabs(V) == infinity) return FP_INFINITY
1905  Builder.SetInsertPoint(NotNan);
1906  Value *VAbs = EmitFAbs(*this, V);
1907  Value *IsInf =
1908  Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
1909  "isinf");
1910  Value *InfLiteral = EmitScalarExpr(E->getArg(1));
1911  BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
1912  Builder.CreateCondBr(IsInf, End, NotInf);
1913  Result->addIncoming(InfLiteral, NotNan);
1914 
1915  // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
1916  Builder.SetInsertPoint(NotInf);
1917  APFloat Smallest = APFloat::getSmallestNormalized(
1918  getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
1919  Value *IsNormal =
1920  Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
1921  "isnormal");
1922  Value *NormalResult =
1923  Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
1924  EmitScalarExpr(E->getArg(3)));
1925  Builder.CreateBr(End);
1926  Result->addIncoming(NormalResult, NotInf);
1927 
1928  // return Result
1929  Builder.SetInsertPoint(End);
1930  return RValue::get(Result);
1931  }
1932 
1933  case Builtin::BIalloca:
1934  case Builtin::BI_alloca:
1935  case Builtin::BI__builtin_alloca: {
1936  Value *Size = EmitScalarExpr(E->getArg(0));
1937  const TargetInfo &TI = getContext().getTargetInfo();
1938  // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
1939  unsigned SuitableAlignmentInBytes =
1940  CGM.getContext()
1941  .toCharUnitsFromBits(TI.getSuitableAlign())
1942  .getQuantity();
1943  AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
1944  AI->setAlignment(SuitableAlignmentInBytes);
1945  return RValue::get(AI);
1946  }
1947 
1948  case Builtin::BI__builtin_alloca_with_align: {
1949  Value *Size = EmitScalarExpr(E->getArg(0));
1950  Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
1951  auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
1952  unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
1953  unsigned AlignmentInBytes =
1954  CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getQuantity();
1955  AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
1956  AI->setAlignment(AlignmentInBytes);
1957  return RValue::get(AI);
1958  }
1959 
1960  case Builtin::BIbzero:
1961  case Builtin::BI__builtin_bzero: {
1962  Address Dest = EmitPointerWithAlignment(E->getArg(0));
1963  Value *SizeVal = EmitScalarExpr(E->getArg(1));
1964  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
1965  E->getArg(0)->getExprLoc(), FD, 0);
1966  Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
1967  return RValue::get(nullptr);
1968  }
1969  case Builtin::BImemcpy:
1970  case Builtin::BI__builtin_memcpy: {
1971  Address Dest = EmitPointerWithAlignment(E->getArg(0));
1972  Address Src = EmitPointerWithAlignment(E->getArg(1));
1973  Value *SizeVal = EmitScalarExpr(E->getArg(2));
1974  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
1975  E->getArg(0)->getExprLoc(), FD, 0);
1976  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
1977  E->getArg(1)->getExprLoc(), FD, 1);
1978  Builder.CreateMemCpy(Dest, Src, SizeVal, false);
1979  return RValue::get(Dest.getPointer());
1980  }
1981 
1982  case Builtin::BI__builtin_char_memchr:
1983  BuiltinID = Builtin::BI__builtin_memchr;
1984  break;
1985 
1986  case Builtin::BI__builtin___memcpy_chk: {
1987  // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
1988  llvm::APSInt Size, DstSize;
1989  if (!E->getArg(2)->EvaluateAsInt(Size, CGM.getContext()) ||
1990  !E->getArg(3)->EvaluateAsInt(DstSize, CGM.getContext()))
1991  break;
1992  if (Size.ugt(DstSize))
1993  break;
1994  Address Dest = EmitPointerWithAlignment(E->getArg(0));
1995  Address Src = EmitPointerWithAlignment(E->getArg(1));
1996  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
1997  Builder.CreateMemCpy(Dest, Src, SizeVal, false);
1998  return RValue::get(Dest.getPointer());
1999  }
2000 
2001  case Builtin::BI__builtin_objc_memmove_collectable: {
2002  Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
2003  Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
2004  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2005  CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
2006  DestAddr, SrcAddr, SizeVal);
2007  return RValue::get(DestAddr.getPointer());
2008  }
2009 
2010  case Builtin::BI__builtin___memmove_chk: {
2011  // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
2012  llvm::APSInt Size, DstSize;
2013  if (!E->getArg(2)->EvaluateAsInt(Size, CGM.getContext()) ||
2014  !E->getArg(3)->EvaluateAsInt(DstSize, CGM.getContext()))
2015  break;
2016  if (Size.ugt(DstSize))
2017  break;
2018  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2019  Address Src = EmitPointerWithAlignment(E->getArg(1));
2020  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
2021  Builder.CreateMemMove(Dest, Src, SizeVal, false);
2022  return RValue::get(Dest.getPointer());
2023  }
2024 
2025  case Builtin::BImemmove:
2026  case Builtin::BI__builtin_memmove: {
2027  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2028  Address Src = EmitPointerWithAlignment(E->getArg(1));
2029  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2030  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
2031  E->getArg(0)->getExprLoc(), FD, 0);
2032  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
2033  E->getArg(1)->getExprLoc(), FD, 1);
2034  Builder.CreateMemMove(Dest, Src, SizeVal, false);
2035  return RValue::get(Dest.getPointer());
2036  }
2037  case Builtin::BImemset:
2038  case Builtin::BI__builtin_memset: {
2039  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2040  Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
2041  Builder.getInt8Ty());
2042  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2043  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
2044  E->getArg(0)->getExprLoc(), FD, 0);
2045  Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
2046  return RValue::get(Dest.getPointer());
2047  }
2048  case Builtin::BI__builtin___memset_chk: {
2049  // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
2050  llvm::APSInt Size, DstSize;
2051  if (!E->getArg(2)->EvaluateAsInt(Size, CGM.getContext()) ||
2052  !E->getArg(3)->EvaluateAsInt(DstSize, CGM.getContext()))
2053  break;
2054  if (Size.ugt(DstSize))
2055  break;
2056  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2057  Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
2058  Builder.getInt8Ty());
2059  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
2060  Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
2061  return RValue::get(Dest.getPointer());
2062  }
2063  case Builtin::BI__builtin_wmemcmp: {
2064  // The MSVC runtime library does not provide a definition of wmemcmp, so we
2065  // need an inline implementation.
2066  if (!getTarget().getTriple().isOSMSVCRT())
2067  break;
2068 
2069  llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
2070 
2071  Value *Dst = EmitScalarExpr(E->getArg(0));
2072  Value *Src = EmitScalarExpr(E->getArg(1));
2073  Value *Size = EmitScalarExpr(E->getArg(2));
2074 
2075  BasicBlock *Entry = Builder.GetInsertBlock();
2076  BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
2077  BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
2078  BasicBlock *Next = createBasicBlock("wmemcmp.next");
2079  BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
2080  Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
2081  Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
2082 
2083  EmitBlock(CmpGT);
2084  PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
2085  DstPhi->addIncoming(Dst, Entry);
2086  PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
2087  SrcPhi->addIncoming(Src, Entry);
2088  PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
2089  SizePhi->addIncoming(Size, Entry);
2090  CharUnits WCharAlign =
2091  getContext().getTypeAlignInChars(getContext().WCharTy);
2092  Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
2093  Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
2094  Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
2095  Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
2096 
2097  EmitBlock(CmpLT);
2098  Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
2099  Builder.CreateCondBr(DstLtSrc, Exit, Next);
2100 
2101  EmitBlock(Next);
2102  Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
2103  Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
2104  Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
2105  Value *NextSizeEq0 =
2106  Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
2107  Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
2108  DstPhi->addIncoming(NextDst, Next);
2109  SrcPhi->addIncoming(NextSrc, Next);
2110  SizePhi->addIncoming(NextSize, Next);
2111 
2112  EmitBlock(Exit);
2113  PHINode *Ret = Builder.CreatePHI(IntTy, 4);
2114  Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
2115  Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
2116  Ret->addIncoming(ConstantInt::get(IntTy, -1), CmpLT);
2117  Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
2118  return RValue::get(Ret);
2119  }
2120  case Builtin::BI__builtin_dwarf_cfa: {
2121  // The offset in bytes from the first argument to the CFA.
2122  //
2123  // Why on earth is this in the frontend? Is there any reason at
2124  // all that the backend can't reasonably determine this while
2125  // lowering llvm.eh.dwarf.cfa()?
2126  //
2127  // TODO: If there's a satisfactory reason, add a target hook for
2128  // this instead of hard-coding 0, which is correct for most targets.
2129  int32_t Offset = 0;
2130 
2131  Value *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
2132  return RValue::get(Builder.CreateCall(F,
2133  llvm::ConstantInt::get(Int32Ty, Offset)));
2134  }
2135  case Builtin::BI__builtin_return_address: {
2136  Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
2137  getContext().UnsignedIntTy);
2138  Value *F = CGM.getIntrinsic(Intrinsic::returnaddress);
2139  return RValue::get(Builder.CreateCall(F, Depth));
2140  }
2141  case Builtin::BI_ReturnAddress: {
2142  Value *F = CGM.getIntrinsic(Intrinsic::returnaddress);
2143  return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
2144  }
2145  case Builtin::BI__builtin_frame_address: {
2146  Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
2147  getContext().UnsignedIntTy);
2148  Value *F = CGM.getIntrinsic(Intrinsic::frameaddress);
2149  return RValue::get(Builder.CreateCall(F, Depth));
2150  }
2151  case Builtin::BI__builtin_extract_return_addr: {
2152  Value *Address = EmitScalarExpr(E->getArg(0));
2153  Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
2154  return RValue::get(Result);
2155  }
2156  case Builtin::BI__builtin_frob_return_addr: {
2157  Value *Address = EmitScalarExpr(E->getArg(0));
2158  Value *Result = getTargetHooks().encodeReturnAddress(*this, Address);
2159  return RValue::get(Result);
2160  }
2161  case Builtin::BI__builtin_dwarf_sp_column: {
2162  llvm::IntegerType *Ty
2163  = cast<llvm::IntegerType>(ConvertType(E->getType()));
2164  int Column = getTargetHooks().getDwarfEHStackPointer(CGM);
2165  if (Column == -1) {
2166  CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
2167  return RValue::get(llvm::UndefValue::get(Ty));
2168  }
2169  return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
2170  }
2171  case Builtin::BI__builtin_init_dwarf_reg_size_table: {
2172  Value *Address = EmitScalarExpr(E->getArg(0));
2173  if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
2174  CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
2175  return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
2176  }
2177  case Builtin::BI__builtin_eh_return: {
2178  Value *Int = EmitScalarExpr(E->getArg(0));
2179  Value *Ptr = EmitScalarExpr(E->getArg(1));
2180 
2181  llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
2182  assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&
2183  "LLVM's __builtin_eh_return only supports 32- and 64-bit variants");
2184  Value *F = CGM.getIntrinsic(IntTy->getBitWidth() == 32
2185  ? Intrinsic::eh_return_i32
2186  : Intrinsic::eh_return_i64);
2187  Builder.CreateCall(F, {Int, Ptr});
2188  Builder.CreateUnreachable();
2189 
2190  // We do need to preserve an insertion point.
2191  EmitBlock(createBasicBlock("builtin_eh_return.cont"));
2192 
2193  return RValue::get(nullptr);
2194  }
2195  case Builtin::BI__builtin_unwind_init: {
2196  Value *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
2197  return RValue::get(Builder.CreateCall(F));
2198  }
2199  case Builtin::BI__builtin_extend_pointer: {
2200  // Extends a pointer to the size of an _Unwind_Word, which is
2201  // uint64_t on all platforms. Generally this gets poked into a
2202  // register and eventually used as an address, so if the
2203  // addressing registers are wider than pointers and the platform
2204  // doesn't implicitly ignore high-order bits when doing
2205  // addressing, we need to make sure we zext / sext based on
2206  // the platform's expectations.
2207  //
2208  // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
2209 
2210  // Cast the pointer to intptr_t.
2211  Value *Ptr = EmitScalarExpr(E->getArg(0));
2212  Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
2213 
2214  // If that's 64 bits, we're done.
2215  if (IntPtrTy->getBitWidth() == 64)
2216  return RValue::get(Result);
2217 
2218  // Otherwise, ask the codegen data what to do.
2219  if (getTargetHooks().extendPointerWithSExt())
2220  return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
2221  else
2222  return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
2223  }
2224  case Builtin::BI__builtin_setjmp: {
2225  // Buffer is a void**.
2226  Address Buf = EmitPointerWithAlignment(E->getArg(0));
2227 
2228  // Store the frame pointer to the setjmp buffer.
2229  Value *FrameAddr =
2230  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::frameaddress),
2231  ConstantInt::get(Int32Ty, 0));
2232  Builder.CreateStore(FrameAddr, Buf);
2233 
2234  // Store the stack pointer to the setjmp buffer.
2235  Value *StackAddr =
2236  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::stacksave));
2237  Address StackSaveSlot =
2238  Builder.CreateConstInBoundsGEP(Buf, 2, getPointerSize());
2239  Builder.CreateStore(StackAddr, StackSaveSlot);
2240 
2241  // Call LLVM's EH setjmp, which is lightweight.
2242  Value *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
2243  Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
2244  return RValue::get(Builder.CreateCall(F, Buf.getPointer()));
2245  }
2246  case Builtin::BI__builtin_longjmp: {
2247  Value *Buf = EmitScalarExpr(E->getArg(0));
2248  Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
2249 
2250  // Call LLVM's EH longjmp, which is lightweight.
2251  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
2252 
2253  // longjmp doesn't return; mark this as unreachable.
2254  Builder.CreateUnreachable();
2255 
2256  // We do need to preserve an insertion point.
2257  EmitBlock(createBasicBlock("longjmp.cont"));
2258 
2259  return RValue::get(nullptr);
2260  }
2261  case Builtin::BI__sync_fetch_and_add:
2262  case Builtin::BI__sync_fetch_and_sub:
2263  case Builtin::BI__sync_fetch_and_or:
2264  case Builtin::BI__sync_fetch_and_and:
2265  case Builtin::BI__sync_fetch_and_xor:
2266  case Builtin::BI__sync_fetch_and_nand:
2267  case Builtin::BI__sync_add_and_fetch:
2268  case Builtin::BI__sync_sub_and_fetch:
2269  case Builtin::BI__sync_and_and_fetch:
2270  case Builtin::BI__sync_or_and_fetch:
2271  case Builtin::BI__sync_xor_and_fetch:
2272  case Builtin::BI__sync_nand_and_fetch:
2273  case Builtin::BI__sync_val_compare_and_swap:
2274  case Builtin::BI__sync_bool_compare_and_swap:
2275  case Builtin::BI__sync_lock_test_and_set:
2276  case Builtin::BI__sync_lock_release:
2277  case Builtin::BI__sync_swap:
2278  llvm_unreachable("Shouldn't make it through sema");
2279  case Builtin::BI__sync_fetch_and_add_1:
2280  case Builtin::BI__sync_fetch_and_add_2:
2281  case Builtin::BI__sync_fetch_and_add_4:
2282  case Builtin::BI__sync_fetch_and_add_8:
2283  case Builtin::BI__sync_fetch_and_add_16:
2284  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
2285  case Builtin::BI__sync_fetch_and_sub_1:
2286  case Builtin::BI__sync_fetch_and_sub_2:
2287  case Builtin::BI__sync_fetch_and_sub_4:
2288  case Builtin::BI__sync_fetch_and_sub_8:
2289  case Builtin::BI__sync_fetch_and_sub_16:
2290  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
2291  case Builtin::BI__sync_fetch_and_or_1:
2292  case Builtin::BI__sync_fetch_and_or_2:
2293  case Builtin::BI__sync_fetch_and_or_4:
2294  case Builtin::BI__sync_fetch_and_or_8:
2295  case Builtin::BI__sync_fetch_and_or_16:
2296  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
2297  case Builtin::BI__sync_fetch_and_and_1:
2298  case Builtin::BI__sync_fetch_and_and_2:
2299  case Builtin::BI__sync_fetch_and_and_4:
2300  case Builtin::BI__sync_fetch_and_and_8:
2301  case Builtin::BI__sync_fetch_and_and_16:
2302  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
2303  case Builtin::BI__sync_fetch_and_xor_1:
2304  case Builtin::BI__sync_fetch_and_xor_2:
2305  case Builtin::BI__sync_fetch_and_xor_4:
2306  case Builtin::BI__sync_fetch_and_xor_8:
2307  case Builtin::BI__sync_fetch_and_xor_16:
2308  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
2309  case Builtin::BI__sync_fetch_and_nand_1:
2310  case Builtin::BI__sync_fetch_and_nand_2:
2311  case Builtin::BI__sync_fetch_and_nand_4:
2312  case Builtin::BI__sync_fetch_and_nand_8:
2313  case Builtin::BI__sync_fetch_and_nand_16:
2314  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
2315 
2316  // Clang extensions: not overloaded yet.
2317  case Builtin::BI__sync_fetch_and_min:
2318  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
2319  case Builtin::BI__sync_fetch_and_max:
2320  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
2321  case Builtin::BI__sync_fetch_and_umin:
2322  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
2323  case Builtin::BI__sync_fetch_and_umax:
2324  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
2325 
2326  case Builtin::BI__sync_add_and_fetch_1:
2327  case Builtin::BI__sync_add_and_fetch_2:
2328  case Builtin::BI__sync_add_and_fetch_4:
2329  case Builtin::BI__sync_add_and_fetch_8:
2330  case Builtin::BI__sync_add_and_fetch_16:
2331  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Add, E,
2332  llvm::Instruction::Add);
2333  case Builtin::BI__sync_sub_and_fetch_1:
2334  case Builtin::BI__sync_sub_and_fetch_2:
2335  case Builtin::BI__sync_sub_and_fetch_4:
2336  case Builtin::BI__sync_sub_and_fetch_8:
2337  case Builtin::BI__sync_sub_and_fetch_16:
2338  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Sub, E,
2339  llvm::Instruction::Sub);
2340  case Builtin::BI__sync_and_and_fetch_1:
2341  case Builtin::BI__sync_and_and_fetch_2:
2342  case Builtin::BI__sync_and_and_fetch_4:
2343  case Builtin::BI__sync_and_and_fetch_8:
2344  case Builtin::BI__sync_and_and_fetch_16:
2347  case Builtin::BI__sync_or_and_fetch_1:
2348  case Builtin::BI__sync_or_and_fetch_2:
2349  case Builtin::BI__sync_or_and_fetch_4:
2350  case Builtin::BI__sync_or_and_fetch_8:
2351  case Builtin::BI__sync_or_and_fetch_16:
2352  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
2353  llvm::Instruction::Or);
2354  case Builtin::BI__sync_xor_and_fetch_1:
2355  case Builtin::BI__sync_xor_and_fetch_2:
2356  case Builtin::BI__sync_xor_and_fetch_4:
2357  case Builtin::BI__sync_xor_and_fetch_8:
2358  case Builtin::BI__sync_xor_and_fetch_16:
2359  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
2360  llvm::Instruction::Xor);
2361  case Builtin::BI__sync_nand_and_fetch_1:
2362  case Builtin::BI__sync_nand_and_fetch_2:
2363  case Builtin::BI__sync_nand_and_fetch_4:
2364  case Builtin::BI__sync_nand_and_fetch_8:
2365  case Builtin::BI__sync_nand_and_fetch_16:
2366  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
2367  llvm::Instruction::And, true);
2368 
2369  case Builtin::BI__sync_val_compare_and_swap_1:
2370  case Builtin::BI__sync_val_compare_and_swap_2:
2371  case Builtin::BI__sync_val_compare_and_swap_4:
2372  case Builtin::BI__sync_val_compare_and_swap_8:
2373  case Builtin::BI__sync_val_compare_and_swap_16:
2374  return RValue::get(MakeAtomicCmpXchgValue(*this, E, false));
2375 
2376  case Builtin::BI__sync_bool_compare_and_swap_1:
2377  case Builtin::BI__sync_bool_compare_and_swap_2:
2378  case Builtin::BI__sync_bool_compare_and_swap_4:
2379  case Builtin::BI__sync_bool_compare_and_swap_8:
2380  case Builtin::BI__sync_bool_compare_and_swap_16:
2381  return RValue::get(MakeAtomicCmpXchgValue(*this, E, true));
2382 
2383  case Builtin::BI__sync_swap_1:
2384  case Builtin::BI__sync_swap_2:
2385  case Builtin::BI__sync_swap_4:
2386  case Builtin::BI__sync_swap_8:
2387  case Builtin::BI__sync_swap_16:
2388  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
2389 
2390  case Builtin::BI__sync_lock_test_and_set_1:
2391  case Builtin::BI__sync_lock_test_and_set_2:
2392  case Builtin::BI__sync_lock_test_and_set_4:
2393  case Builtin::BI__sync_lock_test_and_set_8:
2394  case Builtin::BI__sync_lock_test_and_set_16:
2395  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
2396 
2397  case Builtin::BI__sync_lock_release_1:
2398  case Builtin::BI__sync_lock_release_2:
2399  case Builtin::BI__sync_lock_release_4:
2400  case Builtin::BI__sync_lock_release_8:
2401  case Builtin::BI__sync_lock_release_16: {
2402  Value *Ptr = EmitScalarExpr(E->getArg(0));
2403  QualType ElTy = E->getArg(0)->getType()->getPointeeType();
2404  CharUnits StoreSize = getContext().getTypeSizeInChars(ElTy);
2405  llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
2406  StoreSize.getQuantity() * 8);
2407  Ptr = Builder.CreateBitCast(Ptr, ITy->getPointerTo());
2408  llvm::StoreInst *Store =
2409  Builder.CreateAlignedStore(llvm::Constant::getNullValue(ITy), Ptr,
2410  StoreSize);
2411  Store->setAtomic(llvm::AtomicOrdering::Release);
2412  return RValue::get(nullptr);
2413  }
2414 
2415  case Builtin::BI__sync_synchronize: {
2416  // We assume this is supposed to correspond to a C++0x-style
2417  // sequentially-consistent fence (i.e. this is only usable for
2418  // synchronization, not device I/O or anything like that). This intrinsic
2419  // is really badly designed in the sense that in theory, there isn't
2420  // any way to safely use it... but in practice, it mostly works
2421  // to use it with non-atomic loads and stores to get acquire/release
2422  // semantics.
2423  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
2424  return RValue::get(nullptr);
2425  }
2426 
2427  case Builtin::BI__builtin_nontemporal_load:
2428  return RValue::get(EmitNontemporalLoad(*this, E));
2429  case Builtin::BI__builtin_nontemporal_store:
2430  return RValue::get(EmitNontemporalStore(*this, E));
2431  case Builtin::BI__c11_atomic_is_lock_free:
2432  case Builtin::BI__atomic_is_lock_free: {
2433  // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
2434  // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
2435  // _Atomic(T) is always properly-aligned.
2436  const char *LibCallName = "__atomic_is_lock_free";
2437  CallArgList Args;
2438  Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
2439  getContext().getSizeType());
2440  if (BuiltinID == Builtin::BI__atomic_is_lock_free)
2441  Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
2442  getContext().VoidPtrTy);
2443  else
2444  Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
2445  getContext().VoidPtrTy);
2446  const CGFunctionInfo &FuncInfo =
2447  CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
2448  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
2449  llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
2450  return EmitCall(FuncInfo, CGCallee::forDirect(Func),
2451  ReturnValueSlot(), Args);
2452  }
2453 
2454  case Builtin::BI__atomic_test_and_set: {
2455  // Look at the argument type to determine whether this is a volatile
2456  // operation. The parameter type is always volatile.
2457  QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
2458  bool Volatile =
2459  PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
2460 
2461  Value *Ptr = EmitScalarExpr(E->getArg(0));
2462  unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
2463  Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
2464  Value *NewVal = Builder.getInt8(1);
2465  Value *Order = EmitScalarExpr(E->getArg(1));
2466  if (isa<llvm::ConstantInt>(Order)) {
2467  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
2468  AtomicRMWInst *Result = nullptr;
2469  switch (ord) {
2470  case 0: // memory_order_relaxed
2471  default: // invalid order
2472  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2473  llvm::AtomicOrdering::Monotonic);
2474  break;
2475  case 1: // memory_order_consume
2476  case 2: // memory_order_acquire
2477  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2478  llvm::AtomicOrdering::Acquire);
2479  break;
2480  case 3: // memory_order_release
2481  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2482  llvm::AtomicOrdering::Release);
2483  break;
2484  case 4: // memory_order_acq_rel
2485 
2486  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2487  llvm::AtomicOrdering::AcquireRelease);
2488  break;
2489  case 5: // memory_order_seq_cst
2490  Result = Builder.CreateAtomicRMW(
2491  llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2492  llvm::AtomicOrdering::SequentiallyConsistent);
2493  break;
2494  }
2495  Result->setVolatile(Volatile);
2496  return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
2497  }
2498 
2499  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
2500 
2501  llvm::BasicBlock *BBs[5] = {
2502  createBasicBlock("monotonic", CurFn),
2503  createBasicBlock("acquire", CurFn),
2504  createBasicBlock("release", CurFn),
2505  createBasicBlock("acqrel", CurFn),
2506  createBasicBlock("seqcst", CurFn)
2507  };
2508  llvm::AtomicOrdering Orders[5] = {
2509  llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Acquire,
2510  llvm::AtomicOrdering::Release, llvm::AtomicOrdering::AcquireRelease,
2511  llvm::AtomicOrdering::SequentiallyConsistent};
2512 
2513  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
2514  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
2515 
2516  Builder.SetInsertPoint(ContBB);
2517  PHINode *Result = Builder.CreatePHI(Int8Ty, 5, "was_set");
2518 
2519  for (unsigned i = 0; i < 5; ++i) {
2520  Builder.SetInsertPoint(BBs[i]);
2521  AtomicRMWInst *RMW = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
2522  Ptr, NewVal, Orders[i]);
2523  RMW->setVolatile(Volatile);
2524  Result->addIncoming(RMW, BBs[i]);
2525  Builder.CreateBr(ContBB);
2526  }
2527 
2528  SI->addCase(Builder.getInt32(0), BBs[0]);
2529  SI->addCase(Builder.getInt32(1), BBs[1]);
2530  SI->addCase(Builder.getInt32(2), BBs[1]);
2531  SI->addCase(Builder.getInt32(3), BBs[2]);
2532  SI->addCase(Builder.getInt32(4), BBs[3]);
2533  SI->addCase(Builder.getInt32(5), BBs[4]);
2534 
2535  Builder.SetInsertPoint(ContBB);
2536  return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
2537  }
2538 
2539  case Builtin::BI__atomic_clear: {
2540  QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
2541  bool Volatile =
2542  PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
2543 
2544  Address Ptr = EmitPointerWithAlignment(E->getArg(0));
2545  unsigned AddrSpace = Ptr.getPointer()->getType()->getPointerAddressSpace();
2546  Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
2547  Value *NewVal = Builder.getInt8(0);
2548  Value *Order = EmitScalarExpr(E->getArg(1));
2549  if (isa<llvm::ConstantInt>(Order)) {
2550  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
2551  StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
2552  switch (ord) {
2553  case 0: // memory_order_relaxed
2554  default: // invalid order
2555  Store->setOrdering(llvm::AtomicOrdering::Monotonic);
2556  break;
2557  case 3: // memory_order_release
2558  Store->setOrdering(llvm::AtomicOrdering::Release);
2559  break;
2560  case 5: // memory_order_seq_cst
2561  Store->setOrdering(llvm::AtomicOrdering::SequentiallyConsistent);
2562  break;
2563  }
2564  return RValue::get(nullptr);
2565  }
2566 
2567  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
2568 
2569  llvm::BasicBlock *BBs[3] = {
2570  createBasicBlock("monotonic", CurFn),
2571  createBasicBlock("release", CurFn),
2572  createBasicBlock("seqcst", CurFn)
2573  };
2574  llvm::AtomicOrdering Orders[3] = {
2575  llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Release,
2576  llvm::AtomicOrdering::SequentiallyConsistent};
2577 
2578  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
2579  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
2580 
2581  for (unsigned i = 0; i < 3; ++i) {
2582  Builder.SetInsertPoint(BBs[i]);
2583  StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
2584  Store->setOrdering(Orders[i]);
2585  Builder.CreateBr(ContBB);
2586  }
2587 
2588  SI->addCase(Builder.getInt32(0), BBs[0]);
2589  SI->addCase(Builder.getInt32(3), BBs[1]);
2590  SI->addCase(Builder.getInt32(5), BBs[2]);
2591 
2592  Builder.SetInsertPoint(ContBB);
2593  return RValue::get(nullptr);
2594  }
2595 
2596  case Builtin::BI__atomic_thread_fence:
2597  case Builtin::BI__atomic_signal_fence:
2598  case Builtin::BI__c11_atomic_thread_fence:
2599  case Builtin::BI__c11_atomic_signal_fence: {
2600  llvm::SyncScope::ID SSID;
2601  if (BuiltinID == Builtin::BI__atomic_signal_fence ||
2602  BuiltinID == Builtin::BI__c11_atomic_signal_fence)
2603  SSID = llvm::SyncScope::SingleThread;
2604  else
2605  SSID = llvm::SyncScope::System;
2606  Value *Order = EmitScalarExpr(E->getArg(0));
2607  if (isa<llvm::ConstantInt>(Order)) {
2608  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
2609  switch (ord) {
2610  case 0: // memory_order_relaxed
2611  default: // invalid order
2612  break;
2613  case 1: // memory_order_consume
2614  case 2: // memory_order_acquire
2615  Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
2616  break;
2617  case 3: // memory_order_release
2618  Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
2619  break;
2620  case 4: // memory_order_acq_rel
2621  Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
2622  break;
2623  case 5: // memory_order_seq_cst
2624  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
2625  break;
2626  }
2627  return RValue::get(nullptr);
2628  }
2629 
2630  llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
2631  AcquireBB = createBasicBlock("acquire", CurFn);
2632  ReleaseBB = createBasicBlock("release", CurFn);
2633  AcqRelBB = createBasicBlock("acqrel", CurFn);
2634  SeqCstBB = createBasicBlock("seqcst", CurFn);
2635  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
2636 
2637  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
2638  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
2639 
2640  Builder.SetInsertPoint(AcquireBB);
2641  Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
2642  Builder.CreateBr(ContBB);
2643  SI->addCase(Builder.getInt32(1), AcquireBB);
2644  SI->addCase(Builder.getInt32(2), AcquireBB);
2645 
2646  Builder.SetInsertPoint(ReleaseBB);
2647  Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
2648  Builder.CreateBr(ContBB);
2649  SI->addCase(Builder.getInt32(3), ReleaseBB);
2650 
2651  Builder.SetInsertPoint(AcqRelBB);
2652  Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
2653  Builder.CreateBr(ContBB);
2654  SI->addCase(Builder.getInt32(4), AcqRelBB);
2655 
2656  Builder.SetInsertPoint(SeqCstBB);
2657  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
2658  Builder.CreateBr(ContBB);
2659  SI->addCase(Builder.getInt32(5), SeqCstBB);
2660 
2661  Builder.SetInsertPoint(ContBB);
2662  return RValue::get(nullptr);
2663  }
2664 
2665  case Builtin::BI__builtin_signbit:
2666  case Builtin::BI__builtin_signbitf:
2667  case Builtin::BI__builtin_signbitl: {
2668  return RValue::get(
2669  Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
2670  ConvertType(E->getType())));
2671  }
2672  case Builtin::BI__annotation: {
2673  // Re-encode each wide string to UTF8 and make an MDString.
2675  for (const Expr *Arg : E->arguments()) {
2676  const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
2677  assert(Str->getCharByteWidth() == 2);
2678  StringRef WideBytes = Str->getBytes();
2679  std::string StrUtf8;
2680  if (!convertUTF16ToUTF8String(
2681  makeArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)) {
2682  CGM.ErrorUnsupported(E, "non-UTF16 __annotation argument");
2683  continue;
2684  }
2685  Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
2686  }
2687 
2688  // Build and MDTuple of MDStrings and emit the intrinsic call.
2689  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::codeview_annotation, {});
2690  MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
2691  Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
2692  return RValue::getIgnored();
2693  }
2694  case Builtin::BI__builtin_annotation: {
2695  llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
2696  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::annotation,
2697  AnnVal->getType());
2698 
2699  // Get the annotation string, go through casts. Sema requires this to be a
2700  // non-wide string literal, potentially casted, so the cast<> is safe.
2701  const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
2702  StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
2703  return RValue::get(EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc()));
2704  }
2705  case Builtin::BI__builtin_addcb:
2706  case Builtin::BI__builtin_addcs:
2707  case Builtin::BI__builtin_addc:
2708  case Builtin::BI__builtin_addcl:
2709  case Builtin::BI__builtin_addcll:
2710  case Builtin::BI__builtin_subcb:
2711  case Builtin::BI__builtin_subcs:
2712  case Builtin::BI__builtin_subc:
2713  case Builtin::BI__builtin_subcl:
2714  case Builtin::BI__builtin_subcll: {
2715 
2716  // We translate all of these builtins from expressions of the form:
2717  // int x = ..., y = ..., carryin = ..., carryout, result;
2718  // result = __builtin_addc(x, y, carryin, &carryout);
2719  //
2720  // to LLVM IR of the form:
2721  //
2722  // %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
2723  // %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
2724  // %carry1 = extractvalue {i32, i1} %tmp1, 1
2725  // %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
2726  // i32 %carryin)
2727  // %result = extractvalue {i32, i1} %tmp2, 0
2728  // %carry2 = extractvalue {i32, i1} %tmp2, 1
2729  // %tmp3 = or i1 %carry1, %carry2
2730  // %tmp4 = zext i1 %tmp3 to i32
2731  // store i32 %tmp4, i32* %carryout
2732 
2733  // Scalarize our inputs.
2734  llvm::Value *X = EmitScalarExpr(E->getArg(0));
2735  llvm::Value *Y = EmitScalarExpr(E->getArg(1));
2736  llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
2737  Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
2738 
2739  // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
2740  llvm::Intrinsic::ID IntrinsicId;
2741  switch (BuiltinID) {
2742  default: llvm_unreachable("Unknown multiprecision builtin id.");
2743  case Builtin::BI__builtin_addcb:
2744  case Builtin::BI__builtin_addcs:
2745  case Builtin::BI__builtin_addc:
2746  case Builtin::BI__builtin_addcl:
2747  case Builtin::BI__builtin_addcll:
2748  IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
2749  break;
2750  case Builtin::BI__builtin_subcb:
2751  case Builtin::BI__builtin_subcs:
2752  case Builtin::BI__builtin_subc:
2753  case Builtin::BI__builtin_subcl:
2754  case Builtin::BI__builtin_subcll:
2755  IntrinsicId = llvm::Intrinsic::usub_with_overflow;
2756  break;
2757  }
2758 
2759  // Construct our resulting LLVM IR expression.
2760  llvm::Value *Carry1;
2761  llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
2762  X, Y, Carry1);
2763  llvm::Value *Carry2;
2764  llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
2765  Sum1, Carryin, Carry2);
2766  llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
2767  X->getType());
2768  Builder.CreateStore(CarryOut, CarryOutPtr);
2769  return RValue::get(Sum2);
2770  }
2771 
2772  case Builtin::BI__builtin_add_overflow:
2773  case Builtin::BI__builtin_sub_overflow:
2774  case Builtin::BI__builtin_mul_overflow: {
2775  const clang::Expr *LeftArg = E->getArg(0);
2776  const clang::Expr *RightArg = E->getArg(1);
2777  const clang::Expr *ResultArg = E->getArg(2);
2778 
2779  clang::QualType ResultQTy =
2780  ResultArg->getType()->castAs<PointerType>()->getPointeeType();
2781 
2782  WidthAndSignedness LeftInfo =
2783  getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
2784  WidthAndSignedness RightInfo =
2785  getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
2786  WidthAndSignedness ResultInfo =
2787  getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
2788 
2789  // Handle mixed-sign multiplication as a special case, because adding
2790  // runtime or backend support for our generic irgen would be too expensive.
2791  if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
2792  return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
2793  RightInfo, ResultArg, ResultQTy,
2794  ResultInfo);
2795 
2796  WidthAndSignedness EncompassingInfo =
2797  EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
2798 
2799  llvm::Type *EncompassingLLVMTy =
2800  llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
2801 
2802  llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
2803 
2804  llvm::Intrinsic::ID IntrinsicId;
2805  switch (BuiltinID) {
2806  default:
2807  llvm_unreachable("Unknown overflow builtin id.");
2808  case Builtin::BI__builtin_add_overflow:
2809  IntrinsicId = EncompassingInfo.Signed
2810  ? llvm::Intrinsic::sadd_with_overflow
2811  : llvm::Intrinsic::uadd_with_overflow;
2812  break;
2813  case Builtin::BI__builtin_sub_overflow:
2814  IntrinsicId = EncompassingInfo.Signed
2815  ? llvm::Intrinsic::ssub_with_overflow
2816  : llvm::Intrinsic::usub_with_overflow;
2817  break;
2818  case Builtin::BI__builtin_mul_overflow:
2819  IntrinsicId = EncompassingInfo.Signed
2820  ? llvm::Intrinsic::smul_with_overflow
2821  : llvm::Intrinsic::umul_with_overflow;
2822  break;
2823  }
2824 
2825  llvm::Value *Left = EmitScalarExpr(LeftArg);
2826  llvm::Value *Right = EmitScalarExpr(RightArg);
2827  Address ResultPtr = EmitPointerWithAlignment(ResultArg);
2828 
2829  // Extend each operand to the encompassing type.
2830  Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
2831  Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
2832 
2833  // Perform the operation on the extended values.
2834  llvm::Value *Overflow, *Result;
2835  Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
2836 
2837  if (EncompassingInfo.Width > ResultInfo.Width) {
2838  // The encompassing type is wider than the result type, so we need to
2839  // truncate it.
2840  llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
2841 
2842  // To see if the truncation caused an overflow, we will extend
2843  // the result and then compare it to the original result.
2844  llvm::Value *ResultTruncExt = Builder.CreateIntCast(
2845  ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
2846  llvm::Value *TruncationOverflow =
2847  Builder.CreateICmpNE(Result, ResultTruncExt);
2848 
2849  Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
2850  Result = ResultTrunc;
2851  }
2852 
2853  // Finally, store the result using the pointer.
2854  bool isVolatile =
2855  ResultArg->getType()->getPointeeType().isVolatileQualified();
2856  Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
2857 
2858  return RValue::get(Overflow);
2859  }
2860 
2861  case Builtin::BI__builtin_uadd_overflow:
2862  case Builtin::BI__builtin_uaddl_overflow:
2863  case Builtin::BI__builtin_uaddll_overflow:
2864  case Builtin::BI__builtin_usub_overflow:
2865  case Builtin::BI__builtin_usubl_overflow:
2866  case Builtin::BI__builtin_usubll_overflow:
2867  case Builtin::BI__builtin_umul_overflow:
2868  case Builtin::BI__builtin_umull_overflow:
2869  case Builtin::BI__builtin_umulll_overflow:
2870  case Builtin::BI__builtin_sadd_overflow:
2871  case Builtin::BI__builtin_saddl_overflow:
2872  case Builtin::BI__builtin_saddll_overflow:
2873  case Builtin::BI__builtin_ssub_overflow:
2874  case Builtin::BI__builtin_ssubl_overflow:
2875  case Builtin::BI__builtin_ssubll_overflow:
2876  case Builtin::BI__builtin_smul_overflow:
2877  case Builtin::BI__builtin_smull_overflow:
2878  case Builtin::BI__builtin_smulll_overflow: {
2879 
2880  // We translate all of these builtins directly to the relevant llvm IR node.
2881 
2882  // Scalarize our inputs.
2883  llvm::Value *X = EmitScalarExpr(E->getArg(0));
2884  llvm::Value *Y = EmitScalarExpr(E->getArg(1));
2885  Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
2886 
2887  // Decide which of the overflow intrinsics we are lowering to:
2888  llvm::Intrinsic::ID IntrinsicId;
2889  switch (BuiltinID) {
2890  default: llvm_unreachable("Unknown overflow builtin id.");
2891  case Builtin::BI__builtin_uadd_overflow:
2892  case Builtin::BI__builtin_uaddl_overflow:
2893  case Builtin::BI__builtin_uaddll_overflow:
2894  IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
2895  break;
2896  case Builtin::BI__builtin_usub_overflow:
2897  case Builtin::BI__builtin_usubl_overflow:
2898  case Builtin::BI__builtin_usubll_overflow:
2899  IntrinsicId = llvm::Intrinsic::usub_with_overflow;
2900  break;
2901  case Builtin::BI__builtin_umul_overflow:
2902  case Builtin::BI__builtin_umull_overflow:
2903  case Builtin::BI__builtin_umulll_overflow:
2904  IntrinsicId = llvm::Intrinsic::umul_with_overflow;
2905  break;
2906  case Builtin::BI__builtin_sadd_overflow:
2907  case Builtin::BI__builtin_saddl_overflow:
2908  case Builtin::BI__builtin_saddll_overflow:
2909  IntrinsicId = llvm::Intrinsic::sadd_with_overflow;
2910  break;
2911  case Builtin::BI__builtin_ssub_overflow:
2912  case Builtin::BI__builtin_ssubl_overflow:
2913  case Builtin::BI__builtin_ssubll_overflow:
2914  IntrinsicId = llvm::Intrinsic::ssub_with_overflow;
2915  break;
2916  case Builtin::BI__builtin_smul_overflow:
2917  case Builtin::BI__builtin_smull_overflow:
2918  case Builtin::BI__builtin_smulll_overflow:
2919  IntrinsicId = llvm::Intrinsic::smul_with_overflow;
2920  break;
2921  }
2922 
2923 
2924  llvm::Value *Carry;
2925  llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
2926  Builder.CreateStore(Sum, SumOutPtr);
2927 
2928  return RValue::get(Carry);
2929  }
2930  case Builtin::BI__builtin_addressof:
2931  return RValue::get(EmitLValue(E->getArg(0)).getPointer());
2932  case Builtin::BI__builtin_operator_new:
2933  return EmitBuiltinNewDeleteCall(
2934  E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
2935  case Builtin::BI__builtin_operator_delete:
2936  return EmitBuiltinNewDeleteCall(
2937  E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
2938 
2939  case Builtin::BI__noop:
2940  // __noop always evaluates to an integer literal zero.
2941  return RValue::get(ConstantInt::get(IntTy, 0));
2942  case Builtin::BI__builtin_call_with_static_chain: {
2943  const CallExpr *Call = cast<CallExpr>(E->getArg(0));
2944  const Expr *Chain = E->getArg(1);
2945  return EmitCall(Call->getCallee()->getType(),
2946  EmitCallee(Call->getCallee()), Call, ReturnValue,
2947  EmitScalarExpr(Chain));
2948  }
2949  case Builtin::BI_InterlockedExchange8:
2950  case Builtin::BI_InterlockedExchange16:
2951  case Builtin::BI_InterlockedExchange:
2952  case Builtin::BI_InterlockedExchangePointer:
2953  return RValue::get(
2954  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchange, E));
2955  case Builtin::BI_InterlockedCompareExchangePointer: {
2956  llvm::Type *RTy;
2957  llvm::IntegerType *IntType =
2958  IntegerType::get(getLLVMContext(),
2959  getContext().getTypeSize(E->getType()));
2960  llvm::Type *IntPtrType = IntType->getPointerTo();
2961 
2962  llvm::Value *Destination =
2963  Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), IntPtrType);
2964 
2965  llvm::Value *Exchange = EmitScalarExpr(E->getArg(1));
2966  RTy = Exchange->getType();
2967  Exchange = Builder.CreatePtrToInt(Exchange, IntType);
2968 
2969  llvm::Value *Comparand =
2970  Builder.CreatePtrToInt(EmitScalarExpr(E->getArg(2)), IntType);
2971 
2972  auto Result =
2973  Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
2974  AtomicOrdering::SequentiallyConsistent,
2975  AtomicOrdering::SequentiallyConsistent);
2976  Result->setVolatile(true);
2977 
2978  return RValue::get(Builder.CreateIntToPtr(Builder.CreateExtractValue(Result,
2979  0),
2980  RTy));
2981  }
2982  case Builtin::BI_InterlockedCompareExchange8:
2983  case Builtin::BI_InterlockedCompareExchange16:
2984  case Builtin::BI_InterlockedCompareExchange:
2985  case Builtin::BI_InterlockedCompareExchange64: {
2986  AtomicCmpXchgInst *CXI = Builder.CreateAtomicCmpXchg(
2987  EmitScalarExpr(E->getArg(0)),
2988  EmitScalarExpr(E->getArg(2)),
2989  EmitScalarExpr(E->getArg(1)),
2990  AtomicOrdering::SequentiallyConsistent,
2991  AtomicOrdering::SequentiallyConsistent);
2992  CXI->setVolatile(true);
2993  return RValue::get(Builder.CreateExtractValue(CXI, 0));
2994  }
2995  case Builtin::BI_InterlockedIncrement16:
2996  case Builtin::BI_InterlockedIncrement:
2997  return RValue::get(
2998  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedIncrement, E));
2999  case Builtin::BI_InterlockedDecrement16:
3000  case Builtin::BI_InterlockedDecrement:
3001  return RValue::get(
3002  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedDecrement, E));
3003  case Builtin::BI_InterlockedAnd8:
3004  case Builtin::BI_InterlockedAnd16:
3005  case Builtin::BI_InterlockedAnd:
3006  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedAnd, E));
3007  case Builtin::BI_InterlockedExchangeAdd8:
3008  case Builtin::BI_InterlockedExchangeAdd16:
3009  case Builtin::BI_InterlockedExchangeAdd:
3010  return RValue::get(
3011  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeAdd, E));
3012  case Builtin::BI_InterlockedExchangeSub8:
3013  case Builtin::BI_InterlockedExchangeSub16:
3014  case Builtin::BI_InterlockedExchangeSub:
3015  return RValue::get(
3016  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeSub, E));
3017  case Builtin::BI_InterlockedOr8:
3018  case Builtin::BI_InterlockedOr16:
3019  case Builtin::BI_InterlockedOr:
3020  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedOr, E));
3021  case Builtin::BI_InterlockedXor8:
3022  case Builtin::BI_InterlockedXor16:
3023  case Builtin::BI_InterlockedXor:
3024  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedXor, E));
3025 
3026  case Builtin::BI_bittest64:
3027  case Builtin::BI_bittest:
3028  case Builtin::BI_bittestandcomplement64:
3029  case Builtin::BI_bittestandcomplement:
3030  case Builtin::BI_bittestandreset64:
3031  case Builtin::BI_bittestandreset:
3032  case Builtin::BI_bittestandset64:
3033  case Builtin::BI_bittestandset:
3034  case Builtin::BI_interlockedbittestandreset:
3035  case Builtin::BI_interlockedbittestandreset64:
3036  case Builtin::BI_interlockedbittestandset64:
3037  case Builtin::BI_interlockedbittestandset:
3038  case Builtin::BI_interlockedbittestandset_acq:
3039  case Builtin::BI_interlockedbittestandset_rel:
3040  case Builtin::BI_interlockedbittestandset_nf:
3041  case Builtin::BI_interlockedbittestandreset_acq:
3042  case Builtin::BI_interlockedbittestandreset_rel:
3043  case Builtin::BI_interlockedbittestandreset_nf:
3044  return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
3045 
3046  case Builtin::BI__exception_code:
3047  case Builtin::BI_exception_code:
3048  return RValue::get(EmitSEHExceptionCode());
3049  case Builtin::BI__exception_info:
3050  case Builtin::BI_exception_info:
3051  return RValue::get(EmitSEHExceptionInfo());
3052  case Builtin::BI__abnormal_termination:
3053  case Builtin::BI_abnormal_termination:
3054  return RValue::get(EmitSEHAbnormalTermination());
3055  case Builtin::BI_setjmpex:
3056  if (getTarget().getTriple().isOSMSVCRT())
3057  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
3058  break;
3059  case Builtin::BI_setjmp:
3060  if (getTarget().getTriple().isOSMSVCRT()) {
3061  if (getTarget().getTriple().getArch() == llvm::Triple::x86)
3062  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
3063  else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
3064  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
3065  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
3066  }
3067  break;
3068 
3069  case Builtin::BI__GetExceptionInfo: {
3070  if (llvm::GlobalVariable *GV =
3071  CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
3072  return RValue::get(llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy));
3073  break;
3074  }
3075 
3076  case Builtin::BI__fastfail:
3077  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::__fastfail, E));
3078 
3079  case Builtin::BI__builtin_coro_size: {
3080  auto & Context = getContext();
3081  auto SizeTy = Context.getSizeType();
3082  auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3083  Value *F = CGM.getIntrinsic(Intrinsic::coro_size, T);
3084  return RValue::get(Builder.CreateCall(F));
3085  }
3086 
3087  case Builtin::BI__builtin_coro_id:
3088  return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
3089  case Builtin::BI__builtin_coro_promise:
3090  return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
3091  case Builtin::BI__builtin_coro_resume:
3092  return EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
3093  case Builtin::BI__builtin_coro_frame:
3094  return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
3095  case Builtin::BI__builtin_coro_noop:
3096  return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
3097  case Builtin::BI__builtin_coro_free:
3098  return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
3099  case Builtin::BI__builtin_coro_destroy:
3100  return EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
3101  case Builtin::BI__builtin_coro_done:
3102  return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
3103  case Builtin::BI__builtin_coro_alloc:
3104  return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
3105  case Builtin::BI__builtin_coro_begin:
3106  return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
3107  case Builtin::BI__builtin_coro_end:
3108  return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
3109  case Builtin::BI__builtin_coro_suspend:
3110  return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
3111  case Builtin::BI__builtin_coro_param:
3112  return EmitCoroutineIntrinsic(E, Intrinsic::coro_param);
3113 
3114  // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
3115  case Builtin::BIread_pipe:
3116  case Builtin::BIwrite_pipe: {
3117  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
3118  *Arg1 = EmitScalarExpr(E->getArg(1));
3119  CGOpenCLRuntime OpenCLRT(CGM);
3120  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3121  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3122 
3123  // Type of the generic packet parameter.
3124  unsigned GenericAS =
3125  getContext().getTargetAddressSpace(LangAS::opencl_generic);
3126  llvm::Type *I8PTy = llvm::PointerType::get(
3127  llvm::Type::getInt8Ty(getLLVMContext()), GenericAS);
3128 
3129  // Testing which overloaded version we should generate the call for.
3130  if (2U == E->getNumArgs()) {
3131  const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
3132  : "__write_pipe_2";
3133  // Creating a generic function type to be able to call with any builtin or
3134  // user defined type.
3135  llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
3136  llvm::FunctionType *FTy = llvm::FunctionType::get(
3137  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3138  Value *BCast = Builder.CreatePointerCast(Arg1, I8PTy);
3139  return RValue::get(
3140  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3141  {Arg0, BCast, PacketSize, PacketAlign}));
3142  } else {
3143  assert(4 == E->getNumArgs() &&
3144  "Illegal number of parameters to pipe function");
3145  const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
3146  : "__write_pipe_4";
3147 
3148  llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
3149  Int32Ty, Int32Ty};
3150  Value *Arg2 = EmitScalarExpr(E->getArg(2)),
3151  *Arg3 = EmitScalarExpr(E->getArg(3));
3152  llvm::FunctionType *FTy = llvm::FunctionType::get(
3153  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3154  Value *BCast = Builder.CreatePointerCast(Arg3, I8PTy);
3155  // We know the third argument is an integer type, but we may need to cast
3156  // it to i32.
3157  if (Arg2->getType() != Int32Ty)
3158  Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
3159  return RValue::get(Builder.CreateCall(
3160  CGM.CreateRuntimeFunction(FTy, Name),
3161  {Arg0, Arg1, Arg2, BCast, PacketSize, PacketAlign}));
3162  }
3163  }
3164  // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
3165  // functions
3166  case Builtin::BIreserve_read_pipe:
3167  case Builtin::BIreserve_write_pipe:
3168  case Builtin::BIwork_group_reserve_read_pipe:
3169  case Builtin::BIwork_group_reserve_write_pipe:
3170  case Builtin::BIsub_group_reserve_read_pipe:
3171  case Builtin::BIsub_group_reserve_write_pipe: {
3172  // Composing the mangled name for the function.
3173  const char *Name;
3174  if (BuiltinID == Builtin::BIreserve_read_pipe)
3175  Name = "__reserve_read_pipe";
3176  else if (BuiltinID == Builtin::BIreserve_write_pipe)
3177  Name = "__reserve_write_pipe";
3178  else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
3179  Name = "__work_group_reserve_read_pipe";
3180  else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
3181  Name = "__work_group_reserve_write_pipe";
3182  else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
3183  Name = "__sub_group_reserve_read_pipe";
3184  else
3185  Name = "__sub_group_reserve_write_pipe";
3186 
3187  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
3188  *Arg1 = EmitScalarExpr(E->getArg(1));
3189  llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
3190  CGOpenCLRuntime OpenCLRT(CGM);
3191  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3192  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3193 
3194  // Building the generic function prototype.
3195  llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
3196  llvm::FunctionType *FTy = llvm::FunctionType::get(
3197  ReservedIDTy, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3198  // We know the second argument is an integer type, but we may need to cast
3199  // it to i32.
3200  if (Arg1->getType() != Int32Ty)
3201  Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
3202  return RValue::get(
3203  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3204  {Arg0, Arg1, PacketSize, PacketAlign}));
3205  }
3206  // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
3207  // functions
3208  case Builtin::BIcommit_read_pipe:
3209  case Builtin::BIcommit_write_pipe:
3210  case Builtin::BIwork_group_commit_read_pipe:
3211  case Builtin::BIwork_group_commit_write_pipe:
3212  case Builtin::BIsub_group_commit_read_pipe:
3213  case Builtin::BIsub_group_commit_write_pipe: {
3214  const char *Name;
3215  if (BuiltinID == Builtin::BIcommit_read_pipe)
3216  Name = "__commit_read_pipe";
3217  else if (BuiltinID == Builtin::BIcommit_write_pipe)
3218  Name = "__commit_write_pipe";
3219  else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
3220  Name = "__work_group_commit_read_pipe";
3221  else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
3222  Name = "__work_group_commit_write_pipe";
3223  else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
3224  Name = "__sub_group_commit_read_pipe";
3225  else
3226  Name = "__sub_group_commit_write_pipe";
3227 
3228  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
3229  *Arg1 = EmitScalarExpr(E->getArg(1));
3230  CGOpenCLRuntime OpenCLRT(CGM);
3231  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3232  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3233 
3234  // Building the generic function prototype.
3235  llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
3236  llvm::FunctionType *FTy =
3237  llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
3238  llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3239 
3240  return RValue::get(
3241  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3242  {Arg0, Arg1, PacketSize, PacketAlign}));
3243  }
3244  // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
3245  case Builtin::BIget_pipe_num_packets:
3246  case Builtin::BIget_pipe_max_packets: {
3247  const char *BaseName;
3248  const PipeType *PipeTy = E->getArg(0)->getType()->getAs<PipeType>();
3249  if (BuiltinID == Builtin::BIget_pipe_num_packets)
3250  BaseName = "__get_pipe_num_packets";
3251  else
3252  BaseName = "__get_pipe_max_packets";
3253  auto Name = std::string(BaseName) +
3254  std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
3255 
3256  // Building the generic function prototype.
3257  Value *Arg0 = EmitScalarExpr(E->getArg(0));
3258  CGOpenCLRuntime OpenCLRT(CGM);
3259  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3260  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3261  llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
3262  llvm::FunctionType *FTy = llvm::FunctionType::get(
3263  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3264 
3265  return RValue::get(Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3266  {Arg0, PacketSize, PacketAlign}));
3267  }
3268 
3269  // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
3270  case Builtin::BIto_global:
3271  case Builtin::BIto_local:
3272  case Builtin::BIto_private: {
3273  auto Arg0 = EmitScalarExpr(E->getArg(0));
3274  auto NewArgT = llvm::PointerType::get(Int8Ty,
3275  CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
3276  auto NewRetT = llvm::PointerType::get(Int8Ty,
3277  CGM.getContext().getTargetAddressSpace(
3279  auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
3280  llvm::Value *NewArg;
3281  if (Arg0->getType()->getPointerAddressSpace() !=
3282  NewArgT->getPointerAddressSpace())
3283  NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
3284  else
3285  NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
3286  auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
3287  auto NewCall =
3288  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
3289  return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
3290  ConvertType(E->getType())));
3291  }
3292 
3293  // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
3294  // It contains four different overload formats specified in Table 6.13.17.1.
3295  case Builtin::BIenqueue_kernel: {
3296  StringRef Name; // Generated function call name
3297  unsigned NumArgs = E->getNumArgs();
3298 
3299  llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
3300  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3301  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3302 
3303  llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
3304  llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
3305  LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
3306  llvm::Value *Range = NDRangeL.getAddress().getPointer();
3307  llvm::Type *RangeTy = NDRangeL.getAddress().getType();
3308 
3309  if (NumArgs == 4) {
3310  // The most basic form of the call with parameters:
3311  // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
3312  Name = "__enqueue_kernel_basic";
3313  llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangeTy, GenericVoidPtrTy,
3314  GenericVoidPtrTy};
3315  llvm::FunctionType *FTy = llvm::FunctionType::get(
3316  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3317 
3318  auto Info =
3319  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
3320  llvm::Value *Kernel =
3321  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3322  llvm::Value *Block =
3323  Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3324 
3325  AttrBuilder B;
3326  B.addAttribute(Attribute::ByVal);
3327  llvm::AttributeList ByValAttrSet =
3328  llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);
3329 
3330  auto RTCall =
3331  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name, ByValAttrSet),
3332  {Queue, Flags, Range, Kernel, Block});
3333  RTCall->setAttributes(ByValAttrSet);
3334  return RValue::get(RTCall);
3335  }
3336  assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
3337 
3338  // Create a temporary array to hold the sizes of local pointer arguments
3339  // for the block. \p First is the position of the first size argument.
3340  auto CreateArrayForSizeVar = [=](unsigned First) {
3341  auto *AT = llvm::ArrayType::get(SizeTy, NumArgs - First);
3342  auto *Arr = Builder.CreateAlloca(AT);
3343  llvm::Value *Ptr;
3344  // Each of the following arguments specifies the size of the corresponding
3345  // argument passed to the enqueued block.
3346  auto *Zero = llvm::ConstantInt::get(IntTy, 0);
3347  for (unsigned I = First; I < NumArgs; ++I) {
3348  auto *Index = llvm::ConstantInt::get(IntTy, I - First);
3349  auto *GEP = Builder.CreateGEP(Arr, {Zero, Index});
3350  if (I == First)
3351  Ptr = GEP;
3352  auto *V =
3353  Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
3354  Builder.CreateAlignedStore(
3355  V, GEP, CGM.getDataLayout().getPrefTypeAlignment(SizeTy));
3356  }
3357  return Ptr;
3358  };
3359 
3360  // Could have events and/or varargs.
3361  if (E->getArg(3)->getType()->isBlockPointerType()) {
3362  // No events passed, but has variadic arguments.
3363  Name = "__enqueue_kernel_varargs";
3364  auto Info =
3365  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
3366  llvm::Value *Kernel =
3367  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3368  auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3369  auto *PtrToSizeArray = CreateArrayForSizeVar(4);
3370 
3371  // Create a vector of the arguments, as well as a constant value to
3372  // express to the runtime the number of variadic arguments.
3373  std::vector<llvm::Value *> Args = {
3374  Queue, Flags, Range,
3375  Kernel, Block, ConstantInt::get(IntTy, NumArgs - 4),
3376  PtrToSizeArray};
3377  std::vector<llvm::Type *> ArgTys = {
3378  QueueTy, IntTy, RangeTy,
3379  GenericVoidPtrTy, GenericVoidPtrTy, IntTy,
3380  PtrToSizeArray->getType()};
3381 
3382  llvm::FunctionType *FTy = llvm::FunctionType::get(
3383  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3384  return RValue::get(
3385  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3387  }
3388  // Any calls now have event arguments passed.
3389  if (NumArgs >= 7) {
3390  llvm::Type *EventTy = ConvertType(getContext().OCLClkEventTy);
3391  llvm::Type *EventPtrTy = EventTy->getPointerTo(
3392  CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
3393 
3394  llvm::Value *NumEvents =
3395  Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
3396  llvm::Value *EventList =
3397  E->getArg(4)->getType()->isArrayType()
3398  ? EmitArrayToPointerDecay(E->getArg(4)).getPointer()
3399  : EmitScalarExpr(E->getArg(4));
3400  llvm::Value *ClkEvent = EmitScalarExpr(E->getArg(5));
3401  // Convert to generic address space.
3402  EventList = Builder.CreatePointerCast(EventList, EventPtrTy);
3403  ClkEvent = Builder.CreatePointerCast(ClkEvent, EventPtrTy);
3404  auto Info =
3405  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
3406  llvm::Value *Kernel =
3407  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3408  llvm::Value *Block =
3409  Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3410 
3411  std::vector<llvm::Type *> ArgTys = {
3412  QueueTy, Int32Ty, RangeTy, Int32Ty,
3413  EventPtrTy, EventPtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
3414 
3415  std::vector<llvm::Value *> Args = {Queue, Flags, Range, NumEvents,
3416  EventList, ClkEvent, Kernel, Block};
3417 
3418  if (NumArgs == 7) {
3419  // Has events but no variadics.
3420  Name = "__enqueue_kernel_basic_events";
3421  llvm::FunctionType *FTy = llvm::FunctionType::get(
3422  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3423  return RValue::get(
3424  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3426  }
3427  // Has event info and variadics
3428  // Pass the number of variadics to the runtime function too.
3429  Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
3430  ArgTys.push_back(Int32Ty);
3431  Name = "__enqueue_kernel_events_varargs";
3432 
3433  auto *PtrToSizeArray = CreateArrayForSizeVar(7);
3434  Args.push_back(PtrToSizeArray);
3435  ArgTys.push_back(PtrToSizeArray->getType());
3436 
3437  llvm::FunctionType *FTy = llvm::FunctionType::get(
3438  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3439  return RValue::get(
3440  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3442  }
3443  LLVM_FALLTHROUGH;
3444  }
3445  // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
3446  // parameter.
3447  case Builtin::BIget_kernel_work_group_size: {
3448  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3449  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3450  auto Info =
3451  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
3452  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3453  Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3454  return RValue::get(Builder.CreateCall(
3455  CGM.CreateRuntimeFunction(
3456  llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
3457  false),
3458  "__get_kernel_work_group_size_impl"),
3459  {Kernel, Arg}));
3460  }
3461  case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
3462  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3463  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3464  auto Info =
3465  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
3466  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3467  Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3468  return RValue::get(Builder.CreateCall(
3469  CGM.CreateRuntimeFunction(
3470  llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
3471  false),
3472  "__get_kernel_preferred_work_group_size_multiple_impl"),
3473  {Kernel, Arg}));
3474  }
3475  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3476  case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
3477  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3478  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3479  LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
3480  llvm::Value *NDRange = NDRangeL.getAddress().getPointer();
3481  auto Info =
3482  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
3483  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3484  Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3485  const char *Name =
3486  BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
3487  ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
3488  : "__get_kernel_sub_group_count_for_ndrange_impl";
3489  return RValue::get(Builder.CreateCall(
3490  CGM.CreateRuntimeFunction(
3491  llvm::FunctionType::get(
3492  IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
3493  false),
3494  Name),
3495  {NDRange, Kernel, Block}));
3496  }
3497 
3498  case Builtin::BI__builtin_store_half:
3499  case Builtin::BI__builtin_store_halff: {
3500  Value *Val = EmitScalarExpr(E->getArg(0));
3501  Address Address = EmitPointerWithAlignment(E->getArg(1));
3502  Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
3503  return RValue::get(Builder.CreateStore(HalfVal, Address));
3504  }
3505  case Builtin::BI__builtin_load_half: {
3506  Address Address = EmitPointerWithAlignment(E->getArg(0));
3507  Value *HalfVal = Builder.CreateLoad(Address);
3508  return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
3509  }
3510  case Builtin::BI__builtin_load_halff: {
3511  Address Address = EmitPointerWithAlignment(E->getArg(0));
3512  Value *HalfVal = Builder.CreateLoad(Address);
3513  return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
3514  }
3515  case Builtin::BIprintf:
3516  if (getTarget().getTriple().isNVPTX())
3517  return EmitNVPTXDevicePrintfCallExpr(E, ReturnValue);
3518  break;
3519  case Builtin::BI__builtin_canonicalize:
3520  case Builtin::BI__builtin_canonicalizef:
3521  case Builtin::BI__builtin_canonicalizel:
3522  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::canonicalize));
3523 
3524  case Builtin::BI__builtin_thread_pointer: {
3525  if (!getContext().getTargetInfo().isTLSSupported())
3526  CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
3527  // Fall through - it's already mapped to the intrinsic by GCCBuiltin.
3528  break;
3529  }
3530  case Builtin::BI__builtin_os_log_format:
3531  return emitBuiltinOSLogFormat(*E);
3532 
3533  case Builtin::BI__builtin_os_log_format_buffer_size: {
3535  analyze_os_log::computeOSLogBufferLayout(CGM.getContext(), E, Layout);
3536  return RValue::get(ConstantInt::get(ConvertType(E->getType()),
3537  Layout.size().getQuantity()));
3538  }
3539 
3540  case Builtin::BI__xray_customevent: {
3541  if (!ShouldXRayInstrumentFunction())
3542  return RValue::getIgnored();
3543 
3544  if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
3546  return RValue::getIgnored();
3547 
3548  if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
3549  if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
3550  return RValue::getIgnored();
3551 
3552  Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
3553  auto FTy = F->getFunctionType();
3554  auto Arg0 = E->getArg(0);
3555  auto Arg0Val = EmitScalarExpr(Arg0);
3556  auto Arg0Ty = Arg0->getType();
3557  auto PTy0 = FTy->getParamType(0);
3558  if (PTy0 != Arg0Val->getType()) {
3559  if (Arg0Ty->isArrayType())
3560  Arg0Val = EmitArrayToPointerDecay(Arg0).getPointer();
3561  else
3562  Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
3563  }
3564  auto Arg1 = EmitScalarExpr(E->getArg(1));
3565  auto PTy1 = FTy->getParamType(1);
3566  if (PTy1 != Arg1->getType())
3567  Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
3568  return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
3569  }
3570 
3571  case Builtin::BI__xray_typedevent: {
3572  // TODO: There should be a way to always emit events even if the current
3573  // function is not instrumented. Losing events in a stream can cripple
3574  // a trace.
3575  if (!ShouldXRayInstrumentFunction())
3576  return RValue::getIgnored();
3577 
3578  if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
3580  return RValue::getIgnored();
3581 
3582  if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
3583  if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
3584  return RValue::getIgnored();
3585 
3586  Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
3587  auto FTy = F->getFunctionType();
3588  auto Arg0 = EmitScalarExpr(E->getArg(0));
3589  auto PTy0 = FTy->getParamType(0);
3590  if (PTy0 != Arg0->getType())
3591  Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
3592  auto Arg1 = E->getArg(1);
3593  auto Arg1Val = EmitScalarExpr(Arg1);
3594  auto Arg1Ty = Arg1->getType();
3595  auto PTy1 = FTy->getParamType(1);
3596  if (PTy1 != Arg1Val->getType()) {
3597  if (Arg1Ty->isArrayType())
3598  Arg1Val = EmitArrayToPointerDecay(Arg1).getPointer();
3599  else
3600  Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
3601  }
3602  auto Arg2 = EmitScalarExpr(E->getArg(2));
3603  auto PTy2 = FTy->getParamType(2);
3604  if (PTy2 != Arg2->getType())
3605  Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
3606  return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
3607  }
3608 
3609  case Builtin::BI__builtin_ms_va_start:
3610  case Builtin::BI__builtin_ms_va_end:
3611  return RValue::get(
3612  EmitVAStartEnd(EmitMSVAListRef(E->getArg(0)).getPointer(),
3613  BuiltinID == Builtin::BI__builtin_ms_va_start));
3614 
3615  case Builtin::BI__builtin_ms_va_copy: {
3616  // Lower this manually. We can't reliably determine whether or not any
3617  // given va_copy() is for a Win64 va_list from the calling convention
3618  // alone, because it's legal to do this from a System V ABI function.
3619  // With opaque pointer types, we won't have enough information in LLVM
3620  // IR to determine this from the argument types, either. Best to do it
3621  // now, while we have enough information.
3622  Address DestAddr = EmitMSVAListRef(E->getArg(0));
3623  Address SrcAddr = EmitMSVAListRef(E->getArg(1));
3624 
3625  llvm::Type *BPP = Int8PtrPtrTy;
3626 
3627  DestAddr = Address(Builder.CreateBitCast(DestAddr.getPointer(), BPP, "cp"),
3628  DestAddr.getAlignment());
3629  SrcAddr = Address(Builder.CreateBitCast(SrcAddr.getPointer(), BPP, "ap"),
3630  SrcAddr.getAlignment());
3631 
3632  Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
3633  return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
3634  }
3635  }
3636 
3637  // If this is an alias for a lib function (e.g. __builtin_sin), emit
3638  // the call using the normal call path, but using the unmangled
3639  // version of the function name.
3640  if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
3641  return emitLibraryCall(*this, FD, E,
3642  CGM.getBuiltinLibFunction(FD, BuiltinID));
3643 
3644  // If this is a predefined lib function (e.g. malloc), emit the call
3645  // using exactly the normal call path.
3646  if (getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3647  return emitLibraryCall(*this, FD, E,
3648  cast<llvm::Constant>(EmitScalarExpr(E->getCallee())));
3649 
3650  // Check that a call to a target specific builtin has the correct target
3651  // features.
3652  // This is down here to avoid non-target specific builtins, however, if
3653  // generic builtins start to require generic target features then we
3654  // can move this up to the beginning of the function.
3655  checkTargetFeatures(E, FD);
3656 
3657  // See if we have a target specific intrinsic.
3658  const char *Name = getContext().BuiltinInfo.getName(BuiltinID);
3659  Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
3660  StringRef Prefix =
3661  llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
3662  if (!Prefix.empty()) {
3663  IntrinsicID = Intrinsic::getIntrinsicForGCCBuiltin(Prefix.data(), Name);
3664  // NOTE we don't need to perform a compatibility flag check here since the
3665  // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
3666  // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
3667  if (IntrinsicID == Intrinsic::not_intrinsic)
3668  IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
3669  }
3670 
3671  if (IntrinsicID != Intrinsic::not_intrinsic) {
3673 
3674  // Find out if any arguments are required to be integer constant
3675  // expressions.
3676  unsigned ICEArguments = 0;
3678  getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
3679  assert(Error == ASTContext::GE_None && "Should not codegen an error");
3680 
3681  Function *F = CGM.getIntrinsic(IntrinsicID);
3682  llvm::FunctionType *FTy = F->getFunctionType();
3683 
3684  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
3685  Value *ArgValue;
3686  // If this is a normal argument, just emit it as a scalar.
3687  if ((ICEArguments & (1 << i)) == 0) {
3688  ArgValue = EmitScalarExpr(E->getArg(i));
3689  } else {
3690  // If this is required to be a constant, constant fold it so that we
3691  // know that the generated intrinsic gets a ConstantInt.
3692  llvm::APSInt Result;
3693  bool IsConst = E->getArg(i)->isIntegerConstantExpr(Result,getContext());
3694  assert(IsConst && "Constant arg isn't actually constant?");
3695  (void)IsConst;
3696  ArgValue = llvm::ConstantInt::get(getLLVMContext(), Result);
3697  }
3698 
3699  // If the intrinsic arg type is different from the builtin arg type
3700  // we need to do a bit cast.
3701  llvm::Type *PTy = FTy->getParamType(i);
3702  if (PTy != ArgValue->getType()) {
3703  assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) &&
3704  "Must be able to losslessly bit cast to param");
3705  ArgValue = Builder.CreateBitCast(ArgValue, PTy);
3706  }
3707 
3708  Args.push_back(ArgValue);
3709  }
3710 
3711  Value *V = Builder.CreateCall(F, Args);
3712  QualType BuiltinRetType = E->getType();
3713 
3714  llvm::Type *RetTy = VoidTy;
3715  if (!BuiltinRetType->isVoidType())
3716  RetTy = ConvertType(BuiltinRetType);
3717 
3718  if (RetTy != V->getType()) {
3719  assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
3720  "Must be able to losslessly bit cast result type");
3721  V = Builder.CreateBitCast(V, RetTy);
3722  }
3723 
3724  return RValue::get(V);
3725  }
3726 
3727  // See if we have a target specific builtin that needs to be lowered.
3728  if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E))
3729  return RValue::get(V);
3730 
3731  ErrorUnsupported(E, "builtin function");
3732 
3733  // Unknown builtin, for now just dump it out and return undef.
3734  return GetUndefRValue(E->getType());
3735 }
3736 
3738  unsigned BuiltinID, const CallExpr *E,
3739  llvm::Triple::ArchType Arch) {
3740  switch (Arch) {
3741  case llvm::Triple::arm:
3742  case llvm::Triple::armeb:
3743  case llvm::Triple::thumb:
3744  case llvm::Triple::thumbeb:
3745  return CGF->EmitARMBuiltinExpr(BuiltinID, E, Arch);
3746  case llvm::Triple::aarch64:
3747  case llvm::Triple::aarch64_be:
3748  return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
3749  case llvm::Triple::x86:
3750  case llvm::Triple::x86_64:
3751  return CGF->EmitX86BuiltinExpr(BuiltinID, E);
3752  case llvm::Triple::ppc:
3753  case llvm::Triple::ppc64:
3754  case llvm::Triple::ppc64le:
3755  return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
3756  case llvm::Triple::r600:
3757  case llvm::Triple::amdgcn:
3758  return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
3759  case llvm::Triple::systemz:
3760  return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
3761  case llvm::Triple::nvptx:
3762  case llvm::Triple::nvptx64:
3763  return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
3764  case llvm::Triple::wasm32:
3765  case llvm::Triple::wasm64:
3766  return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
3767  case llvm::Triple::hexagon:
3768  return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
3769  default:
3770  return nullptr;
3771  }
3772 }
3773 
3775  const CallExpr *E) {
3776  if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
3777  assert(getContext().getAuxTargetInfo() && "Missing aux target info");
3779  this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
3780  getContext().getAuxTargetInfo()->getTriple().getArch());
3781  }
3782 
3783  return EmitTargetArchBuiltinExpr(this, BuiltinID, E,
3784  getTarget().getTriple().getArch());
3785 }
3786 
3787 static llvm::VectorType *GetNeonType(CodeGenFunction *CGF,
3788  NeonTypeFlags TypeFlags,
3789  bool HasLegalHalfType=true,
3790  bool V1Ty=false) {
3791  int IsQuad = TypeFlags.isQuad();
3792  switch (TypeFlags.getEltType()) {
3793  case NeonTypeFlags::Int8:
3794  case NeonTypeFlags::Poly8:
3795  return llvm::VectorType::get(CGF->Int8Ty, V1Ty ? 1 : (8 << IsQuad));
3796  case NeonTypeFlags::Int16:
3797  case NeonTypeFlags::Poly16:
3798  return llvm::VectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
3800  if (HasLegalHalfType)
3801  return llvm::VectorType::get(CGF->HalfTy, V1Ty ? 1 : (4 << IsQuad));
3802  else
3803  return llvm::VectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
3804  case NeonTypeFlags::Int32:
3805  return llvm::VectorType::get(CGF->Int32Ty, V1Ty ? 1 : (2 << IsQuad));
3806  case NeonTypeFlags::Int64:
3807  case NeonTypeFlags::Poly64:
3808  return llvm::VectorType::get(CGF->Int64Ty, V1Ty ? 1 : (1 << IsQuad));
3810  // FIXME: i128 and f128 doesn't get fully support in Clang and llvm.
3811  // There is a lot of i128 and f128 API missing.
3812  // so we use v16i8 to represent poly128 and get pattern matched.
3813  return llvm::VectorType::get(CGF->Int8Ty, 16);
3815  return llvm::VectorType::get(CGF->FloatTy, V1Ty ? 1 : (2 << IsQuad));
3817  return llvm::VectorType::get(CGF->DoubleTy, V1Ty ? 1 : (1 << IsQuad));
3818  }
3819  llvm_unreachable("Unknown vector element type!");
3820 }
3821 
3822 static llvm::VectorType *GetFloatNeonType(CodeGenFunction *CGF,
3823  NeonTypeFlags IntTypeFlags) {
3824  int IsQuad = IntTypeFlags.isQuad();
3825  switch (IntTypeFlags.getEltType()) {
3826  case NeonTypeFlags::Int16:
3827  return llvm::VectorType::get(CGF->HalfTy, (4 << IsQuad));
3828  case NeonTypeFlags::Int32:
3829  return llvm::VectorType::get(CGF->FloatTy, (2 << IsQuad));
3830  case NeonTypeFlags::Int64:
3831  return llvm::VectorType::get(CGF->DoubleTy, (1 << IsQuad));
3832  default:
3833  llvm_unreachable("Type can't be converted to floating-point!");
3834  }
3835 }
3836 
3838  unsigned nElts = V->getType()->getVectorNumElements();
3839  Value* SV = llvm::ConstantVector::getSplat(nElts, C);
3840  return Builder.CreateShuffleVector(V, V, SV, "lane");
3841 }
3842 
3844  const char *name,
3845  unsigned shift, bool rightshift) {
3846  unsigned j = 0;
3847  for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
3848  ai != ae; ++ai, ++j)
3849  if (shift > 0 && shift == j)
3850  Ops[j] = EmitNeonShiftVector(Ops[j], ai->getType(), rightshift);
3851  else
3852  Ops[j] = Builder.CreateBitCast(Ops[j], ai->getType(), name);
3853 
3854  return Builder.CreateCall(F, Ops, name);
3855 }
3856 
3858  bool neg) {
3859  int SV = cast<ConstantInt>(V)->getSExtValue();
3860  return ConstantInt::get(Ty, neg ? -SV : SV);
3861 }
3862 
3863 // Right-shift a vector by a constant.
3865  llvm::Type *Ty, bool usgn,
3866  const char *name) {
3867  llvm::VectorType *VTy = cast<llvm::VectorType>(Ty);
3868 
3869  int ShiftAmt = cast<ConstantInt>(Shift)->getSExtValue();
3870  int EltSize = VTy->getScalarSizeInBits();
3871 
3872  Vec = Builder.CreateBitCast(Vec, Ty);
3873 
3874  // lshr/ashr are undefined when the shift amount is equal to the vector
3875  // element size.
3876  if (ShiftAmt == EltSize) {
3877  if (usgn) {
3878  // Right-shifting an unsigned value by its size yields 0.
3879  return llvm::ConstantAggregateZero::get(VTy);
3880  } else {
3881  // Right-shifting a signed value by its size is equivalent
3882  // to a shift of size-1.
3883  --ShiftAmt;
3884  Shift = ConstantInt::get(VTy->getElementType(), ShiftAmt);
3885  }
3886  }
3887 
3888  Shift = EmitNeonShiftVector(Shift, Ty, false);
3889  if (usgn)
3890  return Builder.CreateLShr(Vec, Shift, name);
3891  else
3892  return Builder.CreateAShr(Vec, Shift, name);
3893 }
3894 
3895 enum {
3896  AddRetType = (1 << 0),
3897  Add1ArgType = (1 << 1),
3898  Add2ArgTypes = (1 << 2),
3899 
3900  VectorizeRetType = (1 << 3),
3901  VectorizeArgTypes = (1 << 4),
3902 
3903  InventFloatType = (1 << 5),
3904  UnsignedAlts = (1 << 6),
3905 
3906  Use64BitVectors = (1 << 7),
3907  Use128BitVectors = (1 << 8),
3908 
3915 };
3916 
3917 namespace {
3918 struct NeonIntrinsicInfo {
3919  const char *NameHint;
3920  unsigned BuiltinID;
3921  unsigned LLVMIntrinsic;
3922  unsigned AltLLVMIntrinsic;
3923  unsigned TypeModifier;
3924 
3925  bool operator<(unsigned RHSBuiltinID) const {
3926  return BuiltinID < RHSBuiltinID;
3927  }
3928  bool operator<(const NeonIntrinsicInfo &TE) const {
3929  return BuiltinID < TE.BuiltinID;
3930  }
3931 };
3932 } // end anonymous namespace
3933 
3934 #define NEONMAP0(NameBase) \
3935  { #NameBase, NEON::BI__builtin_neon_ ## NameBase, 0, 0, 0 }
3936 
3937 #define NEONMAP1(NameBase, LLVMIntrinsic, TypeModifier) \
3938  { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
3939  Intrinsic::LLVMIntrinsic, 0, TypeModifier }
3940 
3941 #define NEONMAP2(NameBase, LLVMIntrinsic, AltLLVMIntrinsic, TypeModifier) \
3942  { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
3943  Intrinsic::LLVMIntrinsic, Intrinsic::AltLLVMIntrinsic, \
3944  TypeModifier }
3945 
3946 static const NeonIntrinsicInfo ARMSIMDIntrinsicMap [] = {
3947  NEONMAP2(vabd_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
3948  NEONMAP2(vabdq_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
3949  NEONMAP1(vabs_v, arm_neon_vabs, 0),
3950  NEONMAP1(vabsq_v, arm_neon_vabs, 0),
3951  NEONMAP0(vaddhn_v),
3952  NEONMAP1(vaesdq_v, arm_neon_aesd, 0),
3953  NEONMAP1(vaeseq_v, arm_neon_aese, 0),
3954  NEONMAP1(vaesimcq_v, arm_neon_aesimc, 0),
3955  NEONMAP1(vaesmcq_v, arm_neon_aesmc, 0),
3956  NEONMAP1(vbsl_v, arm_neon_vbsl, AddRetType),
3957  NEONMAP1(vbslq_v, arm_neon_vbsl, AddRetType),
3958  NEONMAP1(vcage_v, arm_neon_vacge, 0),
3959  NEONMAP1(vcageq_v, arm_neon_vacge, 0),
3960  NEONMAP1(vcagt_v, arm_neon_vacgt, 0),
3961  NEONMAP1(vcagtq_v, arm_neon_vacgt, 0),
3962  NEONMAP1(vcale_v, arm_neon_vacge, 0),
3963  NEONMAP1(vcaleq_v, arm_neon_vacge, 0),
3964  NEONMAP1(vcalt_v, arm_neon_vacgt, 0),
3965  NEONMAP1(vcaltq_v, arm_neon_vacgt, 0),
3966  NEONMAP0(vceqz_v),
3967  NEONMAP0(vceqzq_v),
3968  NEONMAP0(vcgez_v),
3969  NEONMAP0(vcgezq_v),
3970  NEONMAP0(vcgtz_v),
3971  NEONMAP0(vcgtzq_v),
3972  NEONMAP0(vclez_v),
3973  NEONMAP0(vclezq_v),
3974  NEONMAP1(vcls_v, arm_neon_vcls, Add1ArgType),
3975  NEONMAP1(vclsq_v, arm_neon_vcls, Add1ArgType),
3976  NEONMAP0(vcltz_v),
3977  NEONMAP0(vcltzq_v),
3978  NEONMAP1(vclz_v, ctlz, Add1ArgType),
3979  NEONMAP1(vclzq_v, ctlz, Add1ArgType),
3980  NEONMAP1(vcnt_v, ctpop, Add1ArgType),
3981  NEONMAP1(vcntq_v, ctpop, Add1ArgType),
3982  NEONMAP1(vcvt_f16_f32, arm_neon_vcvtfp2hf, 0),
3983  NEONMAP0(vcvt_f16_v),
3984  NEONMAP1(vcvt_f32_f16, arm_neon_vcvthf2fp, 0),
3985  NEONMAP0(vcvt_f32_v),
3986  NEONMAP2(vcvt_n_f16_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
3987  NEONMAP2(vcvt_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
3988  NEONMAP1(vcvt_n_s16_v, arm_neon_vcvtfp2fxs, 0),
3989  NEONMAP1(vcvt_n_s32_v, arm_neon_vcvtfp2fxs, 0),
3990  NEONMAP1(vcvt_n_s64_v, arm_neon_vcvtfp2fxs, 0),
3991  NEONMAP1(vcvt_n_u16_v, arm_neon_vcvtfp2fxu, 0),
3992  NEONMAP1(vcvt_n_u32_v, arm_neon_vcvtfp2fxu, 0),
3993  NEONMAP1(vcvt_n_u64_v, arm_neon_vcvtfp2fxu, 0),
3994  NEONMAP0(vcvt_s16_v),
3995  NEONMAP0(vcvt_s32_v),
3996  NEONMAP0(vcvt_s64_v),
3997  NEONMAP0(vcvt_u16_v),
3998  NEONMAP0(vcvt_u32_v),
3999  NEONMAP0(vcvt_u64_v),
4000  NEONMAP1(vcvta_s16_v, arm_neon_vcvtas, 0),
4001  NEONMAP1(vcvta_s32_v, arm_neon_vcvtas, 0),
4002  NEONMAP1(vcvta_s64_v, arm_neon_vcvtas, 0),
4003  NEONMAP1(vcvta_u16_v, arm_neon_vcvtau, 0),
4004  NEONMAP1(vcvta_u32_v, arm_neon_vcvtau, 0),
4005  NEONMAP1(vcvta_u64_v, arm_neon_vcvtau, 0),
4006  NEONMAP1(vcvtaq_s16_v, arm_neon_vcvtas, 0),
4007  NEONMAP1(vcvtaq_s32_v, arm_neon_vcvtas, 0),
4008  NEONMAP1(vcvtaq_s64_v, arm_neon_vcvtas, 0),
4009  NEONMAP1(vcvtaq_u16_v, arm_neon_vcvtau, 0),
4010  NEONMAP1(vcvtaq_u32_v, arm_neon_vcvtau, 0),
4011  NEONMAP1(vcvtaq_u64_v, arm_neon_vcvtau, 0),
4012  NEONMAP1(vcvtm_s16_v, arm_neon_vcvtms, 0),
4013  NEONMAP1(vcvtm_s32_v, arm_neon_vcvtms, 0),
4014  NEONMAP1(vcvtm_s64_v, arm_neon_vcvtms, 0),
4015  NEONMAP1(vcvtm_u16_v, arm_neon_vcvtmu, 0),
4016  NEONMAP1(vcvtm_u32_v, arm_neon_vcvtmu, 0),
4017  NEONMAP1(vcvtm_u64_v, arm_neon_vcvtmu, 0),
4018  NEONMAP1(vcvtmq_s16_v, arm_neon_vcvtms, 0),
4019  NEONMAP1(vcvtmq_s32_v, arm_neon_vcvtms, 0),
4020  NEONMAP1(vcvtmq_s64_v, arm_neon_vcvtms, 0),
4021  NEONMAP1(vcvtmq_u16_v, arm_neon_vcvtmu, 0),
4022  NEONMAP1(vcvtmq_u32_v, arm_neon_vcvtmu, 0),
4023  NEONMAP1(vcvtmq_u64_v, arm_neon_vcvtmu, 0),
4024  NEONMAP1(vcvtn_s16_v, arm_neon_vcvtns, 0),
4025  NEONMAP1(vcvtn_s32_v, arm_neon_vcvtns, 0),
4026  NEONMAP1(vcvtn_s64_v, arm_neon_vcvtns, 0),
4027  NEONMAP1(vcvtn_u16_v, arm_neon_vcvtnu, 0),
4028  NEONMAP1(vcvtn_u32_v, arm_neon_vcvtnu, 0),
4029  NEONMAP1(vcvtn_u64_v, arm_neon_vcvtnu, 0),
4030  NEONMAP1(vcvtnq_s16_v, arm_neon_vcvtns, 0),
4031  NEONMAP1(vcvtnq_s32_v, arm_neon_vcvtns, 0),
4032  NEONMAP1(vcvtnq_s64_v, arm_neon_vcvtns, 0),
4033  NEONMAP1(vcvtnq_u16_v, arm_neon_vcvtnu, 0),
4034  NEONMAP1(vcvtnq_u32_v, arm_neon_vcvtnu, 0),
4035  NEONMAP1(vcvtnq_u64_v, arm_neon_vcvtnu, 0),
4036  NEONMAP1(vcvtp_s16_v, arm_neon_vcvtps, 0),
4037  NEONMAP1(vcvtp_s32_v, arm_neon_vcvtps, 0),
4038  NEONMAP1(vcvtp_s64_v, arm_neon_vcvtps, 0),
4039  NEONMAP1(vcvtp_u16_v, arm_neon_vcvtpu, 0),
4040  NEONMAP1(vcvtp_u32_v, arm_neon_vcvtpu, 0),
4041  NEONMAP1(vcvtp_u64_v, arm_neon_vcvtpu, 0),
4042  NEONMAP1(vcvtpq_s16_v, arm_neon_vcvtps, 0),
4043  NEONMAP1(vcvtpq_s32_v, arm_neon_vcvtps, 0),
4044  NEONMAP1(vcvtpq_s64_v, arm_neon_vcvtps, 0),
4045  NEONMAP1(vcvtpq_u16_v, arm_neon_vcvtpu, 0),
4046  NEONMAP1(vcvtpq_u32_v, arm_neon_vcvtpu, 0),
4047  NEONMAP1(vcvtpq_u64_v, arm_neon_vcvtpu, 0),
4048  NEONMAP0(vcvtq_f16_v),
4049  NEONMAP0(vcvtq_f32_v),
4050  NEONMAP2(vcvtq_n_f16_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
4051  NEONMAP2(vcvtq_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
4052  NEONMAP1(vcvtq_n_s16_v, arm_neon_vcvtfp2fxs, 0),
4053  NEONMAP1(vcvtq_n_s32_v, arm_neon_vcvtfp2fxs, 0),
4054  NEONMAP1(vcvtq_n_s64_v, arm_neon_vcvtfp2fxs, 0),
4055  NEONMAP1(vcvtq_n_u16_v, arm_neon_vcvtfp2fxu, 0),
4056  NEONMAP1(vcvtq_n_u32_v, arm_neon_vcvtfp2fxu, 0),
4057  NEONMAP1(vcvtq_n_u64_v, arm_neon_vcvtfp2fxu, 0),
4058  NEONMAP0(vcvtq_s16_v),
4059  NEONMAP0(vcvtq_s32_v),
4060  NEONMAP0(vcvtq_s64_v),
4061  NEONMAP0(vcvtq_u16_v),
4062  NEONMAP0(vcvtq_u32_v),
4063  NEONMAP0(vcvtq_u64_v),
4064  NEONMAP2(vdot_v, arm_neon_udot, arm_neon_sdot, 0),
4065  NEONMAP2(vdotq_v, arm_neon_udot, arm_neon_sdot, 0),
4066  NEONMAP0(vext_v),
4067  NEONMAP0(vextq_v),
4068  NEONMAP0(vfma_v),
4069  NEONMAP0(vfmaq_v),
4070  NEONMAP2(vhadd_v, arm_neon_vhaddu, arm_neon_vhadds, Add1ArgType | UnsignedAlts),
4071  NEONMAP2(vhaddq_v, arm_neon_vhaddu, arm_neon_vhadds, Add1ArgType | UnsignedAlts),
4072  NEONMAP2(vhsub_v, arm_neon_vhsubu, arm_neon_vhsubs, Add1ArgType | UnsignedAlts),
4073  NEONMAP2(vhsubq_v, arm_neon_vhsubu, arm_neon_vhsubs, Add1ArgType | UnsignedAlts),
4074  NEONMAP0(vld1_dup_v),
4075  NEONMAP1(vld1_v, arm_neon_vld1, 0),
4076  NEONMAP1(vld1_x2_v, arm_neon_vld1x2, 0),
4077  NEONMAP1(vld1_x3_v, arm_neon_vld1x3, 0),
4078  NEONMAP1(vld1_x4_v, arm_neon_vld1x4, 0),
4079  NEONMAP0(vld1q_dup_v),
4080  NEONMAP1(vld1q_v, arm_neon_vld1, 0),
4081  NEONMAP1(vld1q_x2_v, arm_neon_vld1x2, 0),
4082  NEONMAP1(vld1q_x3_v, arm_neon_vld1x3, 0),
4083  NEONMAP1(vld1q_x4_v, arm_neon_vld1x4, 0),
4084  NEONMAP1(vld2_lane_v, arm_neon_vld2lane, 0),
4085  NEONMAP1(vld2_v, arm_neon_vld2, 0),
4086  NEONMAP1(vld2q_lane_v, arm_neon_vld2lane, 0),
4087  NEONMAP1(vld2q_v, arm_neon_vld2, 0),
4088  NEONMAP1(vld3_lane_v, arm_neon_vld3lane, 0),
4089  NEONMAP1(vld3_v, arm_neon_vld3, 0),
4090  NEONMAP1(vld3q_lane_v, arm_neon_vld3lane, 0),
4091  NEONMAP1(vld3q_v, arm_neon_vld3, 0),
4092  NEONMAP1(vld4_lane_v, arm_neon_vld4lane, 0),
4093  NEONMAP1(vld4_v, arm_neon_vld4, 0),
4094  NEONMAP1(vld4q_lane_v, arm_neon_vld4lane, 0),
4095  NEONMAP1(vld4q_v, arm_neon_vld4, 0),
4096  NEONMAP2(vmax_v, arm_neon_vmaxu, arm_neon_vmaxs, Add1ArgType | UnsignedAlts),
4097  NEONMAP1(vmaxnm_v, arm_neon_vmaxnm, Add1ArgType),
4098  NEONMAP1(vmaxnmq_v, arm_neon_vmaxnm, Add1ArgType),
4099  NEONMAP2(vmaxq_v, arm_neon_vmaxu, arm_neon_vmaxs, Add1ArgType | UnsignedAlts),
4100  NEONMAP2(vmin_v, arm_neon_vminu, arm_neon_vmins, Add1ArgType | UnsignedAlts),
4101  NEONMAP1(vminnm_v, arm_neon_vminnm, Add1ArgType),
4102  NEONMAP1(vminnmq_v, arm_neon_vminnm, Add1ArgType),
4103  NEONMAP2(vminq_v, arm_neon_vminu, arm_neon_vmins, Add1ArgType | UnsignedAlts),
4104  NEONMAP0(vmovl_v),
4105  NEONMAP0(vmovn_v),
4106  NEONMAP1(vmul_v, arm_neon_vmulp, Add1ArgType),
4107  NEONMAP0(vmull_v),
4108  NEONMAP1(vmulq_v, arm_neon_vmulp, Add1ArgType),
4109  NEONMAP2(vpadal_v, arm_neon_vpadalu, arm_neon_vpadals, UnsignedAlts),
4110  NEONMAP2(vpadalq_v, arm_neon_vpadalu, arm_neon_vpadals, UnsignedAlts),
4111  NEONMAP1(vpadd_v, arm_neon_vpadd, Add1ArgType),
4112  NEONMAP2(vpaddl_v, arm_neon_vpaddlu, arm_neon_vpaddls, UnsignedAlts),
4113  NEONMAP2(vpaddlq_v, arm_neon_vpaddlu, arm_neon_vpaddls, UnsignedAlts),
4114  NEONMAP1(vpaddq_v, arm_neon_vpadd, Add1ArgType),
4115  NEONMAP2(vpmax_v, arm_neon_vpmaxu, arm_neon_vpmaxs, Add1ArgType | UnsignedAlts),
4116  NEONMAP2(vpmin_v, arm_neon_vpminu, arm_neon_vpmins, Add1ArgType | UnsignedAlts),
4117  NEONMAP1(vqabs_v, arm_neon_vqabs, Add1ArgType),
4118  NEONMAP1(vqabsq_v, arm_neon_vqabs, Add1ArgType),
4119  NEONMAP2(vqadd_v, arm_neon_vqaddu, arm_neon_vqadds, Add1ArgType | UnsignedAlts),
4120  NEONMAP2(vqaddq_v, arm_neon_vqaddu, arm_neon_vqadds, Add1ArgType | UnsignedAlts),
4121  NEONMAP2(vqdmlal_v, arm_neon_vqdmull, arm_neon_vqadds, 0),
4122  NEONMAP2(vqdmlsl_v, arm_neon_vqdmull, arm_neon_vqsubs, 0),
4123  NEONMAP1(vqdmulh_v, arm_neon_vqdmulh, Add1ArgType),
4124  NEONMAP1(vqdmulhq_v, arm_neon_vqdmulh, Add1ArgType),
4125  NEONMAP1(vqdmull_v, arm_neon_vqdmull, Add1ArgType),
4126  NEONMAP2(vqmovn_v, arm_neon_vqmovnu, arm_neon_vqmovns, Add1ArgType | UnsignedAlts),
4127  NEONMAP1(vqmovun_v, arm_neon_vqmovnsu, Add1ArgType),
4128  NEONMAP1(vqneg_v, arm_neon_vqneg, Add1ArgType),
4129  NEONMAP1(vqnegq_v, arm_neon_vqneg, Add1ArgType),
4130  NEONMAP1(vqrdmulh_v, arm_neon_vqrdmulh, Add1ArgType),
4131  NEONMAP1(vqrdmulhq_v, arm_neon_vqrdmulh, Add1ArgType),
4132  NEONMAP2(vqrshl_v, arm_neon_vqrshiftu, arm_neon_vqrshifts, Add1ArgType | UnsignedAlts),
4133  NEONMAP2(vqrshlq_v, arm_neon_vqrshiftu, arm_neon_vqrshifts, Add1ArgType | UnsignedAlts),
4134  NEONMAP2(vqshl_n_v, arm_neon_vqshiftu, arm_neon_vqshifts, UnsignedAlts),
4135  NEONMAP2(vqshl_v, arm_neon_vqshiftu, arm_neon_vqshifts, Add1ArgType | UnsignedAlts),
4136  NEONMAP2(vqshlq_n_v, arm_neon_vqshiftu, arm_neon_vqshifts, UnsignedAlts),
4137  NEONMAP2(vqshlq_v, arm_neon_vqshiftu, arm_neon_vqshifts, Add1ArgType | UnsignedAlts),
4138  NEONMAP1(vqshlu_n_v, arm_neon_vqshiftsu, 0),
4139  NEONMAP1(vqshluq_n_v, arm_neon_vqshiftsu, 0),
4140  NEONMAP2(vqsub_v, arm_neon_vqsubu, arm_neon_vqsubs, Add1ArgType | UnsignedAlts),
4141  NEONMAP2(vqsubq_v, arm_neon_vqsubu, arm_neon_vqsubs, Add1ArgType | UnsignedAlts),
4142  NEONMAP1(vraddhn_v, arm_neon_vraddhn, Add1ArgType),
4143  NEONMAP2(vrecpe_v, arm_neon_vrecpe, arm_neon_vrecpe, 0),
4144  NEONMAP2(vrecpeq_v, arm_neon_vrecpe, arm_neon_vrecpe, 0),
4145  NEONMAP1(vrecps_v, arm_neon_vrecps, Add1ArgType),
4146  NEONMAP1(vrecpsq_v, arm_neon_vrecps, Add1ArgType),
4147  NEONMAP2(vrhadd_v, arm_neon_vrhaddu, arm_neon_vrhadds, Add1ArgType | UnsignedAlts),
4148  NEONMAP2(vrhaddq_v, arm_neon_vrhaddu, arm_neon_vrhadds, Add1ArgType | UnsignedAlts),
4149  NEONMAP1(vrnd_v, arm_neon_vrintz, Add1ArgType),
4150  NEONMAP1(vrnda_v, arm_neon_vrinta, Add1ArgType),
4151  NEONMAP1(vrndaq_v, arm_neon_vrinta, Add1ArgType),
4152  NEONMAP1(vrndm_v, arm_neon_vrintm, Add1ArgType),
4153  NEONMAP1(vrndmq_v, arm_neon_vrintm, Add1ArgType),
4154  NEONMAP1(vrndn_v, arm_neon_vrintn, Add1ArgType),
4155  NEONMAP1(vrndnq_v, arm_neon_vrintn, Add1ArgType),
4156  NEONMAP1(vrndp_v, arm_neon_vrintp, Add1ArgType),
4157  NEONMAP1(vrndpq_v, arm_neon_vrintp, Add1ArgType),
4158  NEONMAP1(vrndq_v, arm_neon_vrintz, Add1ArgType),
4159  NEONMAP1(vrndx_v, arm_neon_vrintx, Add1ArgType),
4160  NEONMAP1(vrndxq_v, arm_neon_vrintx, Add1ArgType),
4161  NEONMAP2(vrshl_v, arm_neon_vrshiftu, arm_neon_vrshifts, Add1ArgType | UnsignedAlts),
4162  NEONMAP2(vrshlq_v, arm_neon_vrshiftu, arm_neon_vrshifts, Add1ArgType | UnsignedAlts),
4163  NEONMAP2(vrshr_n_v, arm_neon_vrshiftu, arm_neon_vrshifts, UnsignedAlts),
4164  NEONMAP2(vrshrq_n_v, arm_neon_vrshiftu, arm_neon_vrshifts, UnsignedAlts),
4165  NEONMAP2(vrsqrte_v, arm_neon_vrsqrte, arm_neon_vrsqrte, 0),
4166  NEONMAP2(vrsqrteq_v, arm_neon_vrsqrte, arm_neon_vrsqrte, 0),
4167  NEONMAP1(vrsqrts_v, arm_neon_vrsqrts, Add1ArgType),
4168  NEONMAP1(vrsqrtsq_v, arm_neon_vrsqrts, Add1ArgType),
4169  NEONMAP1(vrsubhn_v, arm_neon_vrsubhn, Add1ArgType),
4170  NEONMAP1(vsha1su0q_v, arm_neon_sha1su0, 0),
4171  NEONMAP1(vsha1su1q_v, arm_neon_sha1su1, 0),
4172  NEONMAP1(vsha256h2q_v, arm_neon_sha256h2, 0),
4173  NEONMAP1(vsha256hq_v, arm_neon_sha256h, 0),
4174  NEONMAP1(vsha256su0q_v, arm_neon_sha256su0, 0),
4175  NEONMAP1(vsha256su1q_v, arm_neon_sha256su1, 0),
4176  NEONMAP0(vshl_n_v),
4177  NEONMAP2(vshl_v, arm_neon_vshiftu, arm_neon_vshifts, Add1ArgType | UnsignedAlts),
4178  NEONMAP0(vshll_n_v),
4179  NEONMAP0(vshlq_n_v),
4180  NEONMAP2(vshlq_v, arm_neon_vshiftu, arm_neon_vshifts, Add1ArgType | UnsignedAlts),
4181  NEONMAP0(vshr_n_v),
4182  NEONMAP0(vshrn_n_v),
4183  NEONMAP0(vshrq_n_v),
4184  NEONMAP1(vst1_v, arm_neon_vst1, 0),
4185  NEONMAP1(vst1_x2_v, arm_neon_vst1x2, 0),
4186  NEONMAP1(vst1_x3_v, arm_neon_vst1x3, 0),
4187  NEONMAP1(vst1_x4_v, arm_neon_vst1x4, 0),
4188  NEONMAP1(vst1q_v, arm_neon_vst1, 0),
4189  NEONMAP1(vst1q_x2_v, arm_neon_vst1x2, 0),
4190  NEONMAP1(vst1q_x3_v, arm_neon_vst1x3, 0),
4191  NEONMAP1(vst1q_x4_v, arm_neon_vst1x4, 0),
4192  NEONMAP1(vst2_lane_v, arm_neon_vst2lane, 0),
4193  NEONMAP1(vst2_v, arm_neon_vst2, 0),
4194  NEONMAP1(vst2q_lane_v, arm_neon_vst2lane, 0),
4195  NEONMAP1(vst2q_v, arm_neon_vst2, 0),
4196  NEONMAP1(vst3_lane_v, arm_neon_vst3lane, 0),
4197  NEONMAP1(vst3_v, arm_neon_vst3, 0),
4198  NEONMAP1(vst3q_lane_v, arm_neon_vst3lane, 0),
4199  NEONMAP1(vst3q_v, arm_neon_vst3, 0),
4200  NEONMAP1(vst4_lane_v, arm_neon_vst4lane, 0),
4201  NEONMAP1(vst4_v, arm_neon_vst4, 0),
4202  NEONMAP1(vst4q_lane_v, arm_neon_vst4lane, 0),
4203  NEONMAP1(vst4q_v, arm_neon_vst4, 0),
4204  NEONMAP0(vsubhn_v),
4205  NEONMAP0(vtrn_v),
4206  NEONMAP0(vtrnq_v),
4207  NEONMAP0(vtst_v),
4208  NEONMAP0(vtstq_v),
4209  NEONMAP0(vuzp_v),
4210  NEONMAP0(vuzpq_v),
4211  NEONMAP0(vzip_v),
4212  NEONMAP0(vzipq_v)
4213 };
4214 
4215 static const NeonIntrinsicInfo AArch64SIMDIntrinsicMap[] = {
4216  NEONMAP1(vabs_v, aarch64_neon_abs, 0),
4217  NEONMAP1(vabsq_v, aarch64_neon_abs, 0),
4218  NEONMAP0(vaddhn_v),
4219  NEONMAP1(vaesdq_v, aarch64_crypto_aesd, 0),
4220  NEONMAP1(vaeseq_v, aarch64_crypto_aese, 0),
4221  NEONMAP1(vaesimcq_v, aarch64_crypto_aesimc, 0),
4222  NEONMAP1(vaesmcq_v, aarch64_crypto_aesmc, 0),
4223  NEONMAP1(vcage_v, aarch64_neon_facge, 0),
4224  NEONMAP1(vcageq_v, aarch64_neon_facge, 0),
4225  NEONMAP1(vcagt_v, aarch64_neon_facgt, 0),
4226  NEONMAP1(vcagtq_v, aarch64_neon_facgt, 0),
4227  NEONMAP1(vcale_v, aarch64_neon_facge, 0),
4228  NEONMAP1(vcaleq_v, aarch64_neon_facge, 0),
4229  NEONMAP1(vcalt_v, aarch64_neon_facgt, 0),
4230  NEONMAP1(vcaltq_v, aarch64_neon_facgt, 0),
4231  NEONMAP0(vceqz_v),
4232  NEONMAP0(vceqzq_v),
4233  NEONMAP0(vcgez_v),
4234  NEONMAP0(vcgezq_v),
4235  NEONMAP0(vcgtz_v),
4236  NEONMAP0(vcgtzq_v),
4237  NEONMAP0(vclez_v),
4238  NEONMAP0(vclezq_v),
4239  NEONMAP1(vcls_v, aarch64_neon_cls, Add1ArgType),
4240  NEONMAP1(vclsq_v, aarch64_neon_cls, Add1ArgType),
4241  NEONMAP0(vcltz_v),
4242  NEONMAP0(vcltzq_v),
4243  NEONMAP1(vclz_v, ctlz, Add1ArgType),
4244  NEONMAP1(vclzq_v, ctlz, Add1ArgType),
4245  NEONMAP1(vcnt_v, ctpop, Add1ArgType),
4246  NEONMAP1(vcntq_v, ctpop, Add1ArgType),
4247  NEONMAP1(vcvt_f16_f32, aarch64_neon_vcvtfp2hf, 0),
4248  NEONMAP0(vcvt_f16_v),
4249  NEONMAP1(vcvt_f32_f16, aarch64_neon_vcvthf2fp, 0),
4250  NEONMAP0(vcvt_f32_v),
4251  NEONMAP2(vcvt_n_f16_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4252  NEONMAP2(vcvt_n_f32_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4253  NEONMAP2(vcvt_n_f64_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4254  NEONMAP1(vcvt_n_s16_v, aarch64_neon_vcvtfp2fxs, 0),
4255  NEONMAP1(vcvt_n_s32_v, aarch64_neon_vcvtfp2fxs, 0),
4256  NEONMAP1(vcvt_n_s64_v, aarch64_neon_vcvtfp2fxs, 0),
4257  NEONMAP1(vcvt_n_u16_v, aarch64_neon_vcvtfp2fxu, 0),
4258  NEONMAP1(vcvt_n_u32_v, aarch64_neon_vcvtfp2fxu, 0),
4259  NEONMAP1(vcvt_n_u64_v, aarch64_neon_vcvtfp2fxu, 0),
4260  NEONMAP0(vcvtq_f16_v),
4261  NEONMAP0(vcvtq_f32_v),
4262  NEONMAP2(vcvtq_n_f16_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4263  NEONMAP2(vcvtq_n_f32_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4264  NEONMAP2(vcvtq_n_f64_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4265  NEONMAP1(vcvtq_n_s16_v, aarch64_neon_vcvtfp2fxs, 0),
4266  NEONMAP1(vcvtq_n_s32_v, aarch64_neon_vcvtfp2fxs, 0),
4267  NEONMAP1(vcvtq_n_s64_v, aarch64_neon_vcvtfp2fxs, 0),
4268  NEONMAP1(vcvtq_n_u16_v, aarch64_neon_vcvtfp2fxu, 0),
4269  NEONMAP1(vcvtq_n_u32_v, aarch64_neon_vcvtfp2fxu, 0),
4270  NEONMAP1(vcvtq_n_u64_v, aarch64_neon_vcvtfp2fxu, 0),
4271  NEONMAP1(vcvtx_f32_v, aarch64_neon_fcvtxn, AddRetType | Add1ArgType),
4272  NEONMAP2(vdot_v, aarch64_neon_udot, aarch64_neon_sdot, 0),
4273  NEONMAP2(vdotq_v, aarch64_neon_udot, aarch64_neon_sdot, 0),
4274  NEONMAP0(vext_v),
4275  NEONMAP0(vextq_v),
4276  NEONMAP0(vfma_v),
4277  NEONMAP0(vfmaq_v),
4278  NEONMAP2(vhadd_v, aarch64_neon_uhadd, aarch64_neon_shadd, Add1ArgType | UnsignedAlts),
4279  NEONMAP2(vhaddq_v, aarch64_neon_uhadd, aarch64_neon_shadd, Add1ArgType | UnsignedAlts),
4280  NEONMAP2(vhsub_v, aarch64_neon_uhsub, aarch64_neon_shsub, Add1ArgType | UnsignedAlts),
4281  NEONMAP2(vhsubq_v, aarch64_neon_uhsub, aarch64_neon_shsub, Add1ArgType | UnsignedAlts),
4282  NEONMAP1(vld1_x2_v, aarch64_neon_ld1x2, 0),
4283  NEONMAP1(vld1_x3_v, aarch64_neon_ld1x3, 0),
4284  NEONMAP1(vld1_x4_v, aarch64_neon_ld1x4, 0),
4285  NEONMAP1(vld1q_x2_v, aarch64_neon_ld1x2, 0),
4286  NEONMAP1(vld1q_x3_v, aarch64_neon_ld1x3, 0),
4287  NEONMAP1(vld1q_x4_v, aarch64_neon_ld1x4, 0),
4288  NEONMAP0(vmovl_v),
4289  NEONMAP0(vmovn_v),
4290  NEONMAP1(vmul_v, aarch64_neon_pmul, Add1ArgType),
4291  NEONMAP1(vmulq_v, aarch64_neon_pmul, Add1ArgType),
4292  NEONMAP1(vpadd_v, aarch64_neon_addp, Add1ArgType),
4293  NEONMAP2(vpaddl_v, aarch64_neon_uaddlp, aarch64_neon_saddlp, UnsignedAlts),
4294  NEONMAP2(vpaddlq_v, aarch64_neon_uaddlp, aarch64_neon_saddlp, UnsignedAlts),
4295  NEONMAP1(vpaddq_v, aarch64_neon_addp, Add1ArgType),
4296  NEONMAP1(vqabs_v, aarch64_neon_sqabs, Add1ArgType),
4297  NEONMAP1(vqabsq_v, aarch64_neon_sqabs, Add1ArgType),
4298  NEONMAP2(vqadd_v, aarch64_neon_uqadd, aarch64_neon_sqadd, Add1ArgType | UnsignedAlts),
4299  NEONMAP2(vqaddq_v, aarch64_neon_uqadd, aarch64_neon_sqadd, Add1ArgType | UnsignedAlts),
4300  NEONMAP2(vqdmlal_v, aarch64_neon_sqdmull, aarch64_neon_sqadd, 0),
4301  NEONMAP2(vqdmlsl_v, aarch64_neon_sqdmull, aarch64_neon_sqsub, 0),
4302  NEONMAP1(vqdmulh_v, aarch64_neon_sqdmulh, Add1ArgType),
4303  NEONMAP1(vqdmulhq_v, aarch64_neon_sqdmulh, Add1ArgType),
4304  NEONMAP1(vqdmull_v, aarch64_neon_sqdmull, Add1ArgType),
4305  NEONMAP2(vqmovn_v, aarch64_neon_uqxtn, aarch64_neon_sqxtn, Add1ArgType | UnsignedAlts),
4306  NEONMAP1(vqmovun_v, aarch64_neon_sqxtun, Add1ArgType),
4307  NEONMAP1(vqneg_v, aarch64_neon_sqneg, Add1ArgType),
4308  NEONMAP1(vqnegq_v, aarch64_neon_sqneg, Add1ArgType),
4309  NEONMAP1(vqrdmulh_v, aarch64_neon_sqrdmulh, Add1ArgType),
4310  NEONMAP1(vqrdmulhq_v, aarch64_neon_sqrdmulh, Add1ArgType),
4311  NEONMAP2(vqrshl_v, aarch64_neon_uqrshl, aarch64_neon_sqrshl, Add1ArgType | UnsignedAlts),
4312  NEONMAP2(vqrshlq_v, aarch64_neon_uqrshl, aarch64_neon_sqrshl, Add1ArgType | UnsignedAlts),
4313  NEONMAP2(vqshl_n_v, aarch64_neon_uqshl, aarch64_neon_sqshl, UnsignedAlts),
4314  NEONMAP2(vqshl_v, aarch64_neon_uqshl, aarch64_neon_sqshl, Add1ArgType | UnsignedAlts),
4315  NEONMAP2(vqshlq_n_v, aarch64_neon_uqshl, aarch64_neon_sqshl,UnsignedAlts),
4316  NEONMAP2(vqshlq_v, aarch64_neon_uqshl, aarch64_neon_sqshl, Add1ArgType | UnsignedAlts),
4317  NEONMAP1(vqshlu_n_v, aarch64_neon_sqshlu, 0),
4318  NEONMAP1(vqshluq_n_v, aarch64_neon_sqshlu, 0),
4319  NEONMAP2(vqsub_v, aarch64_neon_uqsub, aarch64_neon_sqsub, Add1ArgType | UnsignedAlts),
4320  NEONMAP2(vqsubq_v, aarch64_neon_uqsub, aarch64_neon_sqsub, Add1ArgType | UnsignedAlts),
4321  NEONMAP1(vraddhn_v, aarch64_neon_raddhn, Add1ArgType),
4322  NEONMAP2(vrecpe_v, aarch64_neon_frecpe, aarch64_neon_urecpe, 0),
4323  NEONMAP2(vrecpeq_v, aarch64_neon_frecpe, aarch64_neon_urecpe, 0),
4324  NEONMAP1(vrecps_v, aarch64_neon_frecps, Add1ArgType),
4325  NEONMAP1(vrecpsq_v, aarch64_neon_frecps, Add1ArgType),
4326  NEONMAP2(vrhadd_v, aarch64_neon_urhadd, aarch64_neon_srhadd, Add1ArgType | UnsignedAlts),
4327  NEONMAP2(vrhaddq_v, aarch64_neon_urhadd, aarch64_neon_srhadd, Add1ArgType | UnsignedAlts),
4328  NEONMAP2(vrshl_v, aarch64_neon_urshl, aarch64_neon_srshl, Add1ArgType | UnsignedAlts),
4329  NEONMAP2(vrshlq_v, aarch64_neon_urshl, aarch64_neon_srshl, Add1ArgType | UnsignedAlts),
4330  NEONMAP2(vrshr_n_v, aarch64_neon_urshl, aarch64_neon_srshl, UnsignedAlts),
4331  NEONMAP2(vrshrq_n_v, aarch64_neon_urshl, aarch64_neon_srshl, UnsignedAlts),
4332  NEONMAP2(vrsqrte_v, aarch64_neon_frsqrte, aarch64_neon_ursqrte, 0),
4333  NEONMAP2(vrsqrteq_v, aarch64_neon_frsqrte, aarch64_neon_ursqrte, 0),
4334  NEONMAP1(vrsqrts_v, aarch64_neon_frsqrts, Add1ArgType),
4335  NEONMAP1(vrsqrtsq_v, aarch64_neon_frsqrts, Add1ArgType),
4336  NEONMAP1(vrsubhn_v, aarch64_neon_rsubhn, Add1ArgType),
4337  NEONMAP1(vsha1su0q_v, aarch64_crypto_sha1su0, 0),
4338  NEONMAP1(vsha1su1q_v, aarch64_crypto_sha1su1, 0),
4339  NEONMAP1(vsha256h2q_v, aarch64_crypto_sha256h2, 0),
4340  NEONMAP1(vsha256hq_v, aarch64_crypto_sha256h, 0),
4341  NEONMAP1(vsha256su0q_v, aarch64_crypto_sha256su0, 0),
4342  NEONMAP1(vsha256su1q_v, aarch64_crypto_sha256su1, 0),
4343  NEONMAP0(vshl_n_v),
4344  NEONMAP2(vshl_v, aarch64_neon_ushl, aarch64_neon_sshl, Add1ArgType | UnsignedAlts),
4345  NEONMAP0(vshll_n_v),
4346  NEONMAP0(vshlq_n_v),
4347  NEONMAP2(vshlq_v, aarch64_neon_ushl, aarch64_neon_sshl, Add1ArgType | UnsignedAlts),
4348  NEONMAP0(vshr_n_v),
4349  NEONMAP0(vshrn_n_v),
4350  NEONMAP0(vshrq_n_v),
4351  NEONMAP1(vst1_x2_v, aarch64_neon_st1x2, 0),
4352  NEONMAP1(vst1_x3_v, aarch64_neon_st1x3, 0),
4353  NEONMAP1(vst1_x4_v, aarch64_neon_st1x4, 0),
4354  NEONMAP1(vst1q_x2_v, aarch64_neon_st1x2, 0),
4355  NEONMAP1(vst1q_x3_v, aarch64_neon_st1x3, 0),
4356  NEONMAP1(vst1q_x4_v, aarch64_neon_st1x4, 0),
4357  NEONMAP0(vsubhn_v),
4358  NEONMAP0(vtst_v),
4359  NEONMAP0(vtstq_v),
4360 };
4361 
4362 static const NeonIntrinsicInfo AArch64SISDIntrinsicMap[] = {
4363  NEONMAP1(vabdd_f64, aarch64_sisd_fabd, Add1ArgType),
4364  NEONMAP1(vabds_f32, aarch64_sisd_fabd, Add1ArgType),
4365  NEONMAP1(vabsd_s64, aarch64_neon_abs, Add1ArgType),
4366  NEONMAP1(vaddlv_s32, aarch64_neon_saddlv, AddRetType | Add1ArgType),
4367  NEONMAP1(vaddlv_u32, aarch64_neon_uaddlv, AddRetType | Add1ArgType),
4368  NEONMAP1(vaddlvq_s32, aarch64_neon_saddlv, AddRetType | Add1ArgType),
4369  NEONMAP1(vaddlvq_u32, aarch64_neon_uaddlv, AddRetType | Add1ArgType),
4370  NEONMAP1(vaddv_f32, aarch64_neon_faddv, AddRetType | Add1ArgType),
4371  NEONMAP1(vaddv_s32, aarch64_neon_saddv, AddRetType | Add1ArgType),
4372  NEONMAP1(vaddv_u32, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4373  NEONMAP1(vaddvq_f32, aarch64_neon_faddv, AddRetType | Add1ArgType),
4374  NEONMAP1(vaddvq_f64, aarch64_neon_faddv, AddRetType | Add1ArgType),
4375  NEONMAP1(vaddvq_s32, aarch64_neon_saddv, AddRetType | Add1ArgType),
4376  NEONMAP1(vaddvq_s64, aarch64_neon_saddv, AddRetType | Add1ArgType),
4377  NEONMAP1(vaddvq_u32, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4378  NEONMAP1(vaddvq_u64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4379  NEONMAP1(vcaged_f64, aarch64_neon_facge, AddRetType | Add1ArgType),
4380  NEONMAP1(vcages_f32, aarch64_neon_facge, AddRetType | Add1ArgType),
4381  NEONMAP1(vcagtd_f64, aarch64_neon_facgt, AddRetType | Add1ArgType),
4382  NEONMAP1(vcagts_f32, aarch64_neon_facgt, AddRetType | Add1ArgType),
4383  NEONMAP1(vcaled_f64, aarch64_neon_facge, AddRetType | Add1ArgType),
4384  NEONMAP1(vcales_f32, aarch64_neon_facge, AddRetType | Add1ArgType),
4385  NEONMAP1(vcaltd_f64, aarch64_neon_facgt, AddRetType | Add1ArgType),
4386  NEONMAP1(vcalts_f32, aarch64_neon_facgt, AddRetType | Add1ArgType),
4387  NEONMAP1(vcvtad_s64_f64, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4388  NEONMAP1(vcvtad_u64_f64, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4389  NEONMAP1(vcvtas_s32_f32, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4390  NEONMAP1(vcvtas_u32_f32, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4391  NEONMAP1(vcvtd_n_f64_s64, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4392  NEONMAP1(vcvtd_n_f64_u64, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4393  NEONMAP1(vcvtd_n_s64_f64, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4394  NEONMAP1(vcvtd_n_u64_f64, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4395  NEONMAP1(vcvtmd_s64_f64, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4396  NEONMAP1(vcvtmd_u64_f64, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4397  NEONMAP1(vcvtms_s32_f32, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4398  NEONMAP1(vcvtms_u32_f32, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4399  NEONMAP1(vcvtnd_s64_f64, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4400  NEONMAP1(vcvtnd_u64_f64, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4401  NEONMAP1(vcvtns_s32_f32, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4402  NEONMAP1(vcvtns_u32_f32, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4403  NEONMAP1(vcvtpd_s64_f64, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4404  NEONMAP1(vcvtpd_u64_f64, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4405  NEONMAP1(vcvtps_s32_f32, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4406  NEONMAP1(vcvtps_u32_f32, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4407  NEONMAP1(vcvts_n_f32_s32, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4408  NEONMAP1(vcvts_n_f32_u32, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4409  NEONMAP1(vcvts_n_s32_f32, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4410  NEONMAP1(vcvts_n_u32_f32, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4411  NEONMAP1(vcvtxd_f32_f64, aarch64_sisd_fcvtxn, 0),
4412  NEONMAP1(vmaxnmv_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4413  NEONMAP1(vmaxnmvq_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4414  NEONMAP1(vmaxnmvq_f64, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4415  NEONMAP1(vmaxv_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4416  NEONMAP1(vmaxv_s32, aarch64_neon_smaxv, AddRetType | Add1ArgType),
4417  NEONMAP1(vmaxv_u32, aarch64_neon_umaxv, AddRetType | Add1ArgType),
4418  NEONMAP1(vmaxvq_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4419  NEONMAP1(vmaxvq_f64, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4420  NEONMAP1(vmaxvq_s32, aarch64_neon_smaxv, AddRetType | Add1ArgType),
4421  NEONMAP1(vmaxvq_u32, aarch64_neon_umaxv, AddRetType | Add1ArgType),
4422  NEONMAP1(vminnmv_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4423  NEONMAP1(vminnmvq_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4424  NEONMAP1(vminnmvq_f64, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4425  NEONMAP1(vminv_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
4426  NEONMAP1(vminv_s32, aarch64_neon_sminv, AddRetType | Add1ArgType),
4427  NEONMAP1(vminv_u32, aarch64_neon_uminv, AddRetType | Add1ArgType),
4428  NEONMAP1(vminvq_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
4429  NEONMAP1(vminvq_f64, aarch64_neon_fminv, AddRetType | Add1ArgType),
4430  NEONMAP1(vminvq_s32, aarch64_neon_sminv, AddRetType | Add1ArgType),
4431  NEONMAP1(vminvq_u32, aarch64_neon_uminv, AddRetType | Add1ArgType),
4432  NEONMAP1(vmull_p64, aarch64_neon_pmull64, 0),
4433  NEONMAP1(vmulxd_f64, aarch64_neon_fmulx, Add1ArgType),
4434  NEONMAP1(vmulxs_f32, aarch64_neon_fmulx, Add1ArgType),
4435  NEONMAP1(vpaddd_s64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4436  NEONMAP1(vpaddd_u64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4437  NEONMAP1(vpmaxnmqd_f64, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4438  NEONMAP1(vpmaxnms_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4439  NEONMAP1(vpmaxqd_f64, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4440  NEONMAP1(vpmaxs_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4441  NEONMAP1(vpminnmqd_f64, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4442  NEONMAP1(vpminnms_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4443  NEONMAP1(vpminqd_f64, aarch64_neon_fminv, AddRetType | Add1ArgType),
4444  NEONMAP1(vpmins_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
4445  NEONMAP1(vqabsb_s8, aarch64_neon_sqabs, Vectorize1ArgType | Use64BitVectors),
4446  NEONMAP1(vqabsd_s64, aarch64_neon_sqabs, Add1ArgType),
4447  NEONMAP1(vqabsh_s16, aarch64_neon_sqabs, Vectorize1ArgType | Use64BitVectors),
4448  NEONMAP1(vqabss_s32, aarch64_neon_sqabs, Add1ArgType),
4449  NEONMAP1(vqaddb_s8, aarch64_neon_sqadd, Vectorize1ArgType | Use64BitVectors),
4450  NEONMAP1(vqaddb_u8, aarch64_neon_uqadd, Vectorize1ArgType | Use64BitVectors),
4451  NEONMAP1(vqaddd_s64, aarch64_neon_sqadd, Add1ArgType),
4452  NEONMAP1(vqaddd_u64, aarch64_neon_uqadd, Add1ArgType),
4453  NEONMAP1(vqaddh_s16, aarch64_neon_sqadd, Vectorize1ArgType | Use64BitVectors),
4454  NEONMAP1(vqaddh_u16, aarch64_neon_uqadd, Vectorize1ArgType | Use64BitVectors),
4455  NEONMAP1(vqadds_s32, aarch64_neon_sqadd, Add1ArgType),
4456  NEONMAP1(vqadds_u32, aarch64_neon_uqadd, Add1ArgType),
4457  NEONMAP1(vqdmulhh_s16, aarch64_neon_sqdmulh, Vectorize1ArgType | Use64BitVectors),
4458  NEONMAP1(vqdmulhs_s32, aarch64_neon_sqdmulh, Add1ArgType),
4459  NEONMAP1(vqdmullh_s16, aarch64_neon_sqdmull, VectorRet | Use128BitVectors),
4460  NEONMAP1(vqdmulls_s32, aarch64_neon_sqdmulls_scalar, 0),
4461  NEONMAP1(vqmovnd_s64, aarch64_neon_scalar_sqxtn, AddRetType | Add1ArgType),
4462  NEONMAP1(vqmovnd_u64, aarch64_neon_scalar_uqxtn, AddRetType | Add1ArgType),
4463  NEONMAP1(vqmovnh_s16, aarch64_neon_sqxtn, VectorRet | Use64BitVectors),
4464  NEONMAP1(vqmovnh_u16, aarch64_neon_uqxtn, VectorRet | Use64BitVectors),
4465  NEONMAP1(vqmovns_s32, aarch64_neon_sqxtn, VectorRet | Use64BitVectors),
4466  NEONMAP1(vqmovns_u32, aarch64_neon_uqxtn, VectorRet | Use64BitVectors),
4467  NEONMAP1(vqmovund_s64, aarch64_neon_scalar_sqxtun, AddRetType | Add1ArgType),
4468  NEONMAP1(vqmovunh_s16, aarch64_neon_sqxtun, VectorRet | Use64BitVectors),
4469  NEONMAP1(vqmovuns_s32, aarch64_neon_sqxtun, VectorRet | Use64BitVectors),
4470  NEONMAP1(vqnegb_s8, aarch64_neon_sqneg, Vectorize1ArgType | Use64BitVectors),
4471  NEONMAP1(vqnegd_s64, aarch64_neon_sqneg, Add1ArgType),
4472  NEONMAP1(vqnegh_s16, aarch64_neon_sqneg, Vectorize1ArgType | Use64BitVectors),
4473  NEONMAP1(vqnegs_s32, aarch64_neon_sqneg, Add1ArgType),
4474  NEONMAP1(vqrdmulhh_s16, aarch64_neon_sqrdmulh, Vectorize1ArgType | Use64BitVectors),
4475  NEONMAP1(vqrdmulhs_s32, aarch64_neon_sqrdmulh, Add1ArgType),
4476  NEONMAP1(vqrshlb_s8, aarch64_neon_sqrshl, Vectorize1ArgType | Use64BitVectors),
4477  NEONMAP1(vqrshlb_u8, aarch64_neon_uqrshl, Vectorize1ArgType | Use64BitVectors),
4478  NEONMAP1(vqrshld_s64, aarch64_neon_sqrshl, Add1ArgType),
4479  NEONMAP1(vqrshld_u64, aarch64_neon_uqrshl, Add1ArgType),
4480  NEONMAP1(vqrshlh_s16, aarch64_neon_sqrshl, Vectorize1ArgType | Use64BitVectors),
4481  NEONMAP1(vqrshlh_u16, aarch64_neon_uqrshl, Vectorize1ArgType | Use64BitVectors),
4482  NEONMAP1(vqrshls_s32, aarch64_neon_sqrshl, Add1ArgType),
4483  NEONMAP1(vqrshls_u32, aarch64_neon_uqrshl, Add1ArgType),
4484  NEONMAP1(vqrshrnd_n_s64, aarch64_neon_sqrshrn, AddRetType),
4485  NEONMAP1(vqrshrnd_n_u64, aarch64_neon_uqrshrn, AddRetType),
4486  NEONMAP1(vqrshrnh_n_s16, aarch64_neon_sqrshrn, VectorRet | Use64BitVectors),
4487  NEONMAP1(vqrshrnh_n_u16, aarch64_neon_uqrshrn, VectorRet | Use64BitVectors),
4488  NEONMAP1(vqrshrns_n_s32, aarch64_neon_sqrshrn, VectorRet | Use64BitVectors),
4489  NEONMAP1(vqrshrns_n_u32, aarch64_neon_uqrshrn, VectorRet | Use64BitVectors),
4490  NEONMAP1(vqrshrund_n_s64, aarch64_neon_sqrshrun, AddRetType),
4491  NEONMAP1(vqrshrunh_n_s16, aarch64_neon_sqrshrun, VectorRet | Use64BitVectors),
4492  NEONMAP1(vqrshruns_n_s32, aarch64_neon_sqrshrun, VectorRet | Use64BitVectors),
4493  NEONMAP1(vqshlb_n_s8, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4494  NEONMAP1(vqshlb_n_u8, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4495  NEONMAP1(vqshlb_s8, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4496  NEONMAP1(vqshlb_u8, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4497  NEONMAP1(vqshld_s64, aarch64_neon_sqshl, Add1ArgType),
4498  NEONMAP1(vqshld_u64, aarch64_neon_uqshl, Add1ArgType),
4499  NEONMAP1(vqshlh_n_s16, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4500  NEONMAP1(vqshlh_n_u16, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4501  NEONMAP1(vqshlh_s16, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4502  NEONMAP1(vqshlh_u16, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4503  NEONMAP1(vqshls_n_s32, aarch64_neon_sqshl, Add1ArgType),
4504  NEONMAP1(vqshls_n_u32, aarch64_neon_uqshl, Add1ArgType),
4505  NEONMAP1(vqshls_s32, aarch64_neon_sqshl, Add1ArgType),
4506  NEONMAP1(vqshls_u32, aarch64_neon_uqshl, Add1ArgType),
4507  NEONMAP1(vqshlub_n_s8, aarch64_neon_sqshlu, Vectorize1ArgType | Use64BitVectors),
4508  NEONMAP1(vqshluh_n_s16, aarch64_neon_sqshlu, Vectorize1ArgType | Use64BitVectors),
4509  NEONMAP1(vqshlus_n_s32, aarch64_neon_sqshlu, Add1ArgType),
4510  NEONMAP1(vqshrnd_n_s64, aarch64_neon_sqshrn, AddRetType),
4511  NEONMAP1(vqshrnd_n_u64, aarch64_neon_uqshrn, AddRetType),
4512  NEONMAP1(vqshrnh_n_s16, aarch64_neon_sqshrn, VectorRet | Use64BitVectors),
4513  NEONMAP1(vqshrnh_n_u16, aarch64_neon_uqshrn, VectorRet | Use64BitVectors),
4514  NEONMAP1(vqshrns_n_s32, aarch64_neon_sqshrn, VectorRet | Use64BitVectors),
4515  NEONMAP1(vqshrns_n_u32, aarch64_neon_uqshrn, VectorRet | Use64BitVectors),
4516  NEONMAP1(vqshrund_n_s64, aarch64_neon_sqshrun, AddRetType),
4517  NEONMAP1(vqshrunh_n_s16, aarch64_neon_sqshrun, VectorRet | Use64BitVectors),
4518  NEONMAP1(vqshruns_n_s32, aarch64_neon_sqshrun, VectorRet | Use64BitVectors),
4519  NEONMAP1(vqsubb_s8, aarch64_neon_sqsub, Vectorize1ArgType | Use64BitVectors),
4520  NEONMAP1(vqsubb_u8, aarch64_neon_uqsub, Vectorize1ArgType | Use64BitVectors),
4521  NEONMAP1(vqsubd_s64, aarch64_neon_sqsub, Add1ArgType),
4522  NEONMAP1(vqsubd_u64, aarch64_neon_uqsub, Add1ArgType),
4523  NEONMAP1(vqsubh_s16, aarch64_neon_sqsub, Vectorize1ArgType | Use64BitVectors),
4524  NEONMAP1(vqsubh_u16, aarch64_neon_uqsub, Vectorize1ArgType | Use64BitVectors),
4525  NEONMAP1(vqsubs_s32, aarch64_neon_sqsub, Add1ArgType),
4526  NEONMAP1(vqsubs_u32, aarch64_neon_uqsub, Add1ArgType),
4527  NEONMAP1(vrecped_f64, aarch64_neon_frecpe, Add1ArgType),
4528  NEONMAP1(vrecpes_f32, aarch64_neon_frecpe, Add1ArgType),
4529  NEONMAP1(vrecpxd_f64, aarch64_neon_frecpx, Add1ArgType),
4530  NEONMAP1(vrecpxs_f32, aarch64_neon_frecpx, Add1ArgType),
4531  NEONMAP1(vrshld_s64, aarch64_neon_srshl, Add1ArgType),
4532  NEONMAP1(vrshld_u64, aarch64_neon_urshl, Add1ArgType),
4533  NEONMAP1(vrsqrted_f64, aarch64_neon_frsqrte, Add1ArgType),
4534  NEONMAP1(vrsqrtes_f32, aarch64_neon_frsqrte, Add1ArgType),
4535  NEONMAP1(vrsqrtsd_f64, aarch64_neon_frsqrts, Add1ArgType),
4536  NEONMAP1(vrsqrtss_f32, aarch64_neon_frsqrts, Add1ArgType),
4537  NEONMAP1(vsha1cq_u32, aarch64_crypto_sha1c, 0),
4538  NEONMAP1(vsha1h_u32, aarch64_crypto_sha1h, 0),
4539  NEONMAP1(vsha1mq_u32, aarch64_crypto_sha1m, 0),
4540  NEONMAP1(vsha1pq_u32, aarch64_crypto_sha1p, 0),
4541  NEONMAP1(vshld_s64, aarch64_neon_sshl, Add1ArgType),
4542  NEONMAP1(vshld_u64, aarch64_neon_ushl, Add1ArgType),
4543  NEONMAP1(vslid_n_s64, aarch64_neon_vsli, Vectorize1ArgType),
4544  NEONMAP1(vslid_n_u64, aarch64_neon_vsli, Vectorize1ArgType),
4545  NEONMAP1(vsqaddb_u8, aarch64_neon_usqadd, Vectorize1ArgType | Use64BitVectors),
4546  NEONMAP1(vsqaddd_u64, aarch64_neon_usqadd, Add1ArgType),
4547  NEONMAP1(vsqaddh_u16, aarch64_neon_usqadd, Vectorize1ArgType | Use64BitVectors),
4548  NEONMAP1(vsqadds_u32, aarch64_neon_usqadd, Add1ArgType),
4549  NEONMAP1(vsrid_n_s64, aarch64_neon_vsri, Vectorize1ArgType),
4550  NEONMAP1(vsrid_n_u64, aarch64_neon_vsri, Vectorize1ArgType),
4551  NEONMAP1(vuqaddb_s8, aarch64_neon_suqadd, Vectorize1ArgType | Use64BitVectors),
4552  NEONMAP1(vuqaddd_s64, aarch64_neon_suqadd, Add1ArgType),
4553  NEONMAP1(vuqaddh_s16, aarch64_neon_suqadd, Vectorize1ArgType | Use64BitVectors),
4554  NEONMAP1(vuqadds_s32, aarch64_neon_suqadd, Add1ArgType),
4555  // FP16 scalar intrinisics go here.
4556  NEONMAP1(vabdh_f16, aarch64_sisd_fabd, Add1ArgType),
4557  NEONMAP1(vcvtah_s32_f16, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4558  NEONMAP1(vcvtah_s64_f16, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4559  NEONMAP1(vcvtah_u32_f16, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4560  NEONMAP1(vcvtah_u64_f16, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4561  NEONMAP1(vcvth_n_f16_s32, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4562  NEONMAP1(vcvth_n_f16_s64, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4563  NEONMAP1(vcvth_n_f16_u32, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4564  NEONMAP1(vcvth_n_f16_u64, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4565  NEONMAP1(vcvth_n_s32_f16, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4566  NEONMAP1(vcvth_n_s64_f16, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4567  NEONMAP1(vcvth_n_u32_f16, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4568  NEONMAP1(vcvth_n_u64_f16, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4569  NEONMAP1(vcvtmh_s32_f16, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4570  NEONMAP1(vcvtmh_s64_f16, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4571  NEONMAP1(vcvtmh_u32_f16, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4572  NEONMAP1(vcvtmh_u64_f16, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4573  NEONMAP1(vcvtnh_s32_f16, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4574  NEONMAP1(vcvtnh_s64_f16, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4575  NEONMAP1(vcvtnh_u32_f16, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4576  NEONMAP1(vcvtnh_u64_f16, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4577  NEONMAP1(vcvtph_s32_f16, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4578  NEONMAP1(vcvtph_s64_f16, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4579  NEONMAP1(vcvtph_u32_f16, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4580  NEONMAP1(vcvtph_u64_f16, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4581  NEONMAP1(vmulxh_f16, aarch64_neon_fmulx, Add1ArgType),
4582  NEONMAP1(vrecpeh_f16, aarch64_neon_frecpe, Add1ArgType),
4583  NEONMAP1(vrecpxh_f16, aarch64_neon_frecpx, Add1ArgType),
4584  NEONMAP1(vrsqrteh_f16, aarch64_neon_frsqrte, Add1ArgType),
4585  NEONMAP1(vrsqrtsh_f16, aarch64_neon_frsqrts, Add1ArgType),
4586 };
4587 
4588 #undef NEONMAP0
4589 #undef NEONMAP1
4590 #undef NEONMAP2
4591 
4593 
4596 
4597 
4598 static const NeonIntrinsicInfo *
4600  unsigned BuiltinID, bool &MapProvenSorted) {
4601 
4602 #ifndef NDEBUG
4603  if (!MapProvenSorted) {
4604  assert(std::is_sorted(std::begin(IntrinsicMap), std::end(IntrinsicMap)));
4605  MapProvenSorted = true;
4606  }
4607 #endif
4608 
4609  const NeonIntrinsicInfo *Builtin =
4610  std::lower_bound(IntrinsicMap.begin(), IntrinsicMap.end(), BuiltinID);
4611 
4612  if (Builtin != IntrinsicMap.end() && Builtin->BuiltinID == BuiltinID)
4613  return Builtin;
4614 
4615  return nullptr;
4616 }
4617 
4618 Function *CodeGenFunction::LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
4619  unsigned Modifier,
4620  llvm::Type *ArgType,
4621  const CallExpr *E) {
4622  int VectorSize = 0;
4623  if (Modifier & Use64BitVectors)
4624  VectorSize = 64;
4625  else if (Modifier & Use128BitVectors)
4626  VectorSize = 128;
4627 
4628  // Return type.
4630  if (Modifier & AddRetType) {
4631  llvm::Type *Ty = ConvertType(E->getCallReturnType(getContext()));
4632  if (Modifier & VectorizeRetType)
4633  Ty = llvm::VectorType::get(
4634  Ty, VectorSize ? VectorSize / Ty->getPrimitiveSizeInBits() : 1);
4635 
4636  Tys.push_back(Ty);
4637  }
4638 
4639  // Arguments.
4640  if (Modifier & VectorizeArgTypes) {
4641  int Elts = VectorSize ? VectorSize / ArgType->getPrimitiveSizeInBits() : 1;
4642  ArgType = llvm::VectorType::get(ArgType, Elts);
4643  }
4644 
4645  if (Modifier & (Add1ArgType | Add2ArgTypes))
4646  Tys.push_back(ArgType);
4647 
4648  if (Modifier & Add2ArgTypes)
4649  Tys.push_back(ArgType);
4650 
4651  if (Modifier & InventFloatType)
4652  Tys.push_back(FloatTy);
4653 
4654  return CGM.getIntrinsic(IntrinsicID, Tys);
4655 }
4656 
4658  const NeonIntrinsicInfo &SISDInfo,
4660  const CallExpr *E) {
4661  unsigned BuiltinID = SISDInfo.BuiltinID;
4662  unsigned int Int = SISDInfo.LLVMIntrinsic;
4663  unsigned Modifier = SISDInfo.TypeModifier;
4664  const char *s = SISDInfo.NameHint;
4665 
4666  switch (BuiltinID) {
4667  case NEON::BI__builtin_neon_vcled_s64:
4668  case NEON::BI__builtin_neon_vcled_u64:
4669  case NEON::BI__builtin_neon_vcles_f32:
4670  case NEON::BI__builtin_neon_vcled_f64:
4671  case NEON::BI__builtin_neon_vcltd_s64:
4672  case NEON::BI__builtin_neon_vcltd_u64:
4673  case NEON::BI__builtin_neon_vclts_f32:
4674  case NEON::BI__builtin_neon_vcltd_f64:
4675  case NEON::BI__builtin_neon_vcales_f32:
4676  case NEON::BI__builtin_neon_vcaled_f64:
4677  case NEON::BI__builtin_neon_vcalts_f32:
4678  case NEON::BI__builtin_neon_vcaltd_f64:
4679  // Only one direction of comparisons actually exist, cmle is actually a cmge
4680  // with swapped operands. The table gives us the right intrinsic but we
4681  // still need to do the swap.
4682  std::swap(Ops[0], Ops[1]);
4683  break;
4684  }
4685 
4686  assert(Int && "Generic code assumes a valid intrinsic");
4687 
4688  // Determine the type(s) of this overloaded AArch64 intrinsic.
4689  const Expr *Arg = E->getArg(0);
4690  llvm::Type *ArgTy = CGF.ConvertType(Arg->getType());
4691  Function *F = CGF.LookupNeonLLVMIntrinsic(Int, Modifier, ArgTy, E);
4692 
4693  int j = 0;
4694  ConstantInt *C0 = ConstantInt::get(CGF.SizeTy, 0);
4695  for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
4696  ai != ae; ++ai, ++j) {
4697  llvm::Type *ArgTy = ai->getType();
4698  if (Ops[j]->getType()->getPrimitiveSizeInBits() ==
4699  ArgTy->getPrimitiveSizeInBits())
4700  continue;
4701 
4702  assert(ArgTy->isVectorTy() && !Ops[j]->getType()->isVectorTy());
4703  // The constant argument to an _n_ intrinsic always has Int32Ty, so truncate
4704  // it before inserting.
4705  Ops[j] =
4706  CGF.Builder.CreateTruncOrBitCast(Ops[j], ArgTy->getVectorElementType());
4707  Ops[j] =
4708  CGF.Builder.CreateInsertElement(UndefValue::get(ArgTy), Ops[j], C0);
4709  }
4710 
4711  Value *Result = CGF.EmitNeonCall(F, Ops, s);
4712  llvm::Type *ResultType = CGF.ConvertType(E->getType());
4713  if (ResultType->getPrimitiveSizeInBits() <
4714  Result->getType()->getPrimitiveSizeInBits())
4715  return CGF.Builder.CreateExtractElement(Result, C0);
4716 
4717  return CGF.Builder.CreateBitCast(Result, ResultType, s);
4718 }
4719 
4721  unsigned BuiltinID, unsigned LLVMIntrinsic, unsigned AltLLVMIntrinsic,
4722  const char *NameHint, unsigned Modifier, const CallExpr *E,
4723  SmallVectorImpl<llvm::Value *> &Ops, Address PtrOp0, Address PtrOp1,
4724  llvm::Triple::ArchType Arch) {
4725  // Get the last argument, which specifies the vector type.
4726  llvm::APSInt NeonTypeConst;
4727  const Expr *Arg = E->getArg(E->getNumArgs() - 1);
4728  if (!Arg->isIntegerConstantExpr(NeonTypeConst, getContext()))
4729  return nullptr;
4730 
4731  // Determine the type of this overloaded NEON intrinsic.
4732  NeonTypeFlags Type(NeonTypeConst.getZExtValue());
4733  bool Usgn = Type.isUnsigned();
4734  bool Quad = Type.isQuad();
4735  const bool HasLegalHalfType = getTarget().hasLegalHalfType();
4736 
4737  llvm::VectorType *VTy = GetNeonType(this, Type, HasLegalHalfType);
4738  llvm::Type *Ty = VTy;
4739  if (!Ty)
4740  return nullptr;
4741 
4742  auto getAlignmentValue32 = [&](Address addr) -> Value* {
4743  return Builder.getInt32(addr.getAlignment().getQuantity());
4744  };
4745 
4746  unsigned Int = LLVMIntrinsic;
4747  if ((Modifier & UnsignedAlts) && !Usgn)
4748  Int = AltLLVMIntrinsic;
4749 
4750  switch (BuiltinID) {
4751  default: break;
4752  case NEON::BI__builtin_neon_vabs_v:
4753  case NEON::BI__builtin_neon_vabsq_v:
4754  if (VTy->getElementType()->isFloatingPointTy())
4755  return EmitNeonCall(CGM.getIntrinsic(Intrinsic::fabs, Ty), Ops, "vabs");
4756  return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Ty), Ops, "vabs");
4757  case NEON::BI__builtin_neon_vaddhn_v: {
4758  llvm::VectorType *SrcTy =
4759  llvm::VectorType::getExtendedElementVectorType(VTy);
4760 
4761  // %sum = add <4 x i32> %lhs, %rhs
4762  Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
4763  Ops[1] = Builder.CreateBitCast(Ops[1], SrcTy);
4764  Ops[0] = Builder.CreateAdd(Ops[0], Ops[1], "vaddhn");
4765 
4766  // %high = lshr <4 x i32> %sum, <i32 16, i32 16, i32 16, i32 16>
4767  Constant *ShiftAmt =
4768  ConstantInt::get(SrcTy, SrcTy->getScalarSizeInBits() / 2);
4769  Ops[0] = Builder.CreateLShr(Ops[0], ShiftAmt, "vaddhn");
4770 
4771  // %res = trunc <4 x i32> %high to <4 x i16>
4772  return Builder.CreateTrunc(Ops[0], VTy, "vaddhn");
4773  }
4774  case NEON::BI__builtin_neon_vcale_v:
4775  case NEON::BI__builtin_neon_vcaleq_v:
4776  case NEON::BI__builtin_neon_vcalt_v:
4777  case NEON::BI__builtin_neon_vcaltq_v:
4778  std::swap(Ops[0], Ops[1]);
4779  LLVM_FALLTHROUGH;
4780  case NEON::BI__builtin_neon_vcage_v:
4781  case NEON::BI__builtin_neon_vcageq_v:
4782  case NEON::BI__builtin_neon_vcagt_v:
4783  case NEON::BI__builtin_neon_vcagtq_v: {
4784  llvm::Type *Ty;
4785  switch (VTy->getScalarSizeInBits()) {
4786  default: llvm_unreachable("unexpected type");
4787  case 32:
4788  Ty = FloatTy;
4789  break;
4790  case 64:
4791  Ty = DoubleTy;
4792  break;
4793  case 16:
4794  Ty = HalfTy;
4795  break;
4796  }
4797  llvm::Type *VecFlt = llvm::VectorType::get(Ty, VTy->getNumElements());
4798  llvm::Type *Tys[] = { VTy, VecFlt };
4799  Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
4800  return EmitNeonCall(F, Ops, NameHint);
4801  }
4802  case NEON::BI__builtin_neon_vceqz_v:
4803  case NEON::BI__builtin_neon_vceqzq_v:
4804  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OEQ,
4805  ICmpInst::ICMP_EQ, "vceqz");
4806  case NEON::BI__builtin_neon_vcgez_v:
4807  case NEON::BI__builtin_neon_vcgezq_v:
4808  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OGE,
4809  ICmpInst::ICMP_SGE, "vcgez");
4810  case NEON::BI__builtin_neon_vclez_v:
4811  case NEON::BI__builtin_neon_vclezq_v:
4812  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OLE,
4813  ICmpInst::ICMP_SLE, "vclez");
4814  case NEON::BI__builtin_neon_vcgtz_v:
4815  case NEON::BI__builtin_neon_vcgtzq_v:
4816  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OGT,
4817  ICmpInst::ICMP_SGT, "vcgtz");
4818  case NEON::BI__builtin_neon_vcltz_v:
4819  case NEON::BI__builtin_neon_vcltzq_v:
4820  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OLT,
4821  ICmpInst::ICMP_SLT, "vcltz");
4822  case NEON::BI__builtin_neon_vclz_v:
4823  case NEON::BI__builtin_neon_vclzq_v:
4824  // We generate target-independent intrinsic, which needs a second argument
4825  // for whether or not clz of zero is undefined; on ARM it isn't.
4826  Ops.push_back(Builder.getInt1(getTarget().isCLZForZeroUndef()));
4827  break;
4828  case NEON::BI__builtin_neon_vcvt_f32_v:
4829  case NEON::BI__builtin_neon_vcvtq_f32_v:
4830  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
4831  Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, Quad),
4832  HasLegalHalfType);
4833  return Usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
4834  : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
4835  case NEON::BI__builtin_neon_vcvt_f16_v:
4836  case NEON::BI__builtin_neon_vcvtq_f16_v:
4837  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
4838  Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float16, false, Quad),
4839  HasLegalHalfType);
4840  return Usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
4841  : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
4842  case NEON::BI__builtin_neon_vcvt_n_f16_v:
4843  case NEON::BI__builtin_neon_vcvt_n_f32_v:
4844  case NEON::BI__builtin_neon_vcvt_n_f64_v:
4845  case NEON::BI__builtin_neon_vcvtq_n_f16_v:
4846  case NEON::BI__builtin_neon_vcvtq_n_f32_v:
4847  case NEON::BI__builtin_neon_vcvtq_n_f64_v: {
4848  llvm::Type *Tys[2] = { GetFloatNeonType(this, Type), Ty };
4849  Int = Usgn ? LLVMIntrinsic : AltLLVMIntrinsic;
4850  Function *F = CGM.getIntrinsic(Int, Tys);
4851  return EmitNeonCall(F, Ops, "vcvt_n");
4852  }
4853  case NEON::BI__builtin_neon_vcvt_n_s16_v:
4854  case NEON::BI__builtin_neon_vcvt_n_s32_v:
4855  case NEON::BI__builtin_neon_vcvt_n_u16_v:
4856  case NEON::BI__builtin_neon_vcvt_n_u32_v:
4857  case NEON::BI__builtin_neon_vcvt_n_s64_v:
4858  case NEON::BI__builtin_neon_vcvt_n_u64_v:
4859  case NEON::BI__builtin_neon_vcvtq_n_s16_v:
4860  case NEON::BI__builtin_neon_vcvtq_n_s32_v:
4861  case NEON::BI__builtin_neon_vcvtq_n_u16_v:
4862  case NEON::BI__builtin_neon_vcvtq_n_u32_v:
4863  case NEON::BI__builtin_neon_vcvtq_n_s64_v:
4864  case NEON::BI__builtin_neon_vcvtq_n_u64_v: {
4865  llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
4866  Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
4867  return EmitNeonCall(F, Ops, "vcvt_n");
4868  }
4869  case NEON::BI__builtin_neon_vcvt_s32_v:
4870  case NEON::BI__builtin_neon_vcvt_u32_v:
4871  case NEON::BI__builtin_neon_vcvt_s64_v:
4872  case NEON::BI__builtin_neon_vcvt_u64_v:
4873  case NEON::BI__builtin_neon_vcvt_s16_v:
4874  case NEON::BI__builtin_neon_vcvt_u16_v:
4875  case NEON::BI__builtin_neon_vcvtq_s32_v:
4876  case NEON::BI__builtin_neon_vcvtq_u32_v:
4877  case NEON::BI__builtin_neon_vcvtq_s64_v:
4878  case NEON::BI__builtin_neon_vcvtq_u64_v:
4879  case NEON::BI__builtin_neon_vcvtq_s16_v:
4880  case NEON::BI__builtin_neon_vcvtq_u16_v: {
4881  Ops[0] = Builder.CreateBitCast(Ops[0], GetFloatNeonType(this, Type));
4882  return Usgn ? Builder.CreateFPToUI(Ops[0], Ty, "vcvt")
4883  : Builder.CreateFPToSI(Ops[0], Ty, "vcvt");
4884  }
4885  case NEON::BI__builtin_neon_vcvta_s16_v:
4886  case NEON::BI__builtin_neon_vcvta_s32_v:
4887  case NEON::BI__builtin_neon_vcvta_s64_v:
4888  case NEON::BI__builtin_neon_vcvta_u16_v:
4889  case NEON::BI__builtin_neon_vcvta_u32_v:
4890  case NEON::BI__builtin_neon_vcvta_u64_v:
4891  case NEON::BI__builtin_neon_vcvtaq_s16_v:
4892  case NEON::BI__builtin_neon_vcvtaq_s32_v:
4893  case NEON::BI__builtin_neon_vcvtaq_s64_v:
4894  case NEON::BI__builtin_neon_vcvtaq_u16_v:
4895  case NEON::BI__builtin_neon_vcvtaq_u32_v:
4896  case NEON::BI__builtin_neon_vcvtaq_u64_v:
4897  case NEON::BI__builtin_neon_vcvtn_s16_v:
4898  case NEON::BI__builtin_neon_vcvtn_s32_v:
4899  case NEON::BI__builtin_neon_vcvtn_s64_v:
4900  case NEON::BI__builtin_neon_vcvtn_u16_v:
4901  case NEON::BI__builtin_neon_vcvtn_u32_v:
4902  case NEON::BI__builtin_neon_vcvtn_u64_v:
4903  case NEON::BI__builtin_neon_vcvtnq_s16_v:
4904  case NEON::BI__builtin_neon_vcvtnq_s32_v:
4905  case NEON::BI__builtin_neon_vcvtnq_s64_v:
4906  case NEON::BI__builtin_neon_vcvtnq_u16_v:
4907  case NEON::BI__builtin_neon_vcvtnq_u32_v:
4908  case NEON::BI__builtin_neon_vcvtnq_u64_v:
4909  case NEON::BI__builtin_neon_vcvtp_s16_v:
4910  case NEON::BI__builtin_neon_vcvtp_s32_v:
4911  case NEON::BI__builtin_neon_vcvtp_s64_v:
4912  case NEON::BI__builtin_neon_vcvtp_u16_v:
4913  case NEON::BI__builtin_neon_vcvtp_u32_v:
4914  case NEON::BI__builtin_neon_vcvtp_u64_v:
4915  case NEON::BI__builtin_neon_vcvtpq_s16_v:
4916  case NEON::BI__builtin_neon_vcvtpq_s32_v:
4917  case NEON::BI__builtin_neon_vcvtpq_s64_v:
4918  case NEON::BI__builtin_neon_vcvtpq_u16_v:
4919  case NEON::BI__builtin_neon_vcvtpq_u32_v:
4920  case NEON::BI__builtin_neon_vcvtpq_u64_v:
4921  case NEON::BI__builtin_neon_vcvtm_s16_v:
4922  case NEON::BI__builtin_neon_vcvtm_s32_v:
4923  case NEON::BI__builtin_neon_vcvtm_s64_v:
4924  case NEON::BI__builtin_neon_vcvtm_u16_v:
4925  case NEON::BI__builtin_neon_vcvtm_u32_v:
4926  case NEON::BI__builtin_neon_vcvtm_u64_v:
4927  case NEON::BI__builtin_neon_vcvtmq_s16_v:
4928  case NEON::BI__builtin_neon_vcvtmq_s32_v:
4929  case NEON::BI__builtin_neon_vcvtmq_s64_v:
4930  case NEON::BI__builtin_neon_vcvtmq_u16_v:
4931  case NEON::BI__builtin_neon_vcvtmq_u32_v:
4932  case NEON::BI__builtin_neon_vcvtmq_u64_v: {
4933  llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
4934  return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, NameHint);
4935  }
4936  case NEON::BI__builtin_neon_vext_v:
4937  case NEON::BI__builtin_neon_vextq_v: {
4938  int CV = cast<ConstantInt>(Ops[2])->getSExtValue();
4939  SmallVector<uint32_t, 16> Indices;
4940  for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
4941  Indices.push_back(i+CV);
4942 
4943  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
4944  Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
4945  return Builder.CreateShuffleVector(Ops[0], Ops[1], Indices, "vext");
4946  }
4947  case NEON::BI__builtin_neon_vfma_v:
4948  case NEON::BI__builtin_neon_vfmaq_v: {
4949  Value *F = CGM.getIntrinsic(Intrinsic::fma, Ty);
4950  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
4951  Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
4952  Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
4953 
4954  // NEON intrinsic puts accumulator first, unlike the LLVM fma.
4955  return Builder.CreateCall(F, {Ops[1], Ops[2], Ops[0]});
4956  }
4957  case NEON::BI__builtin_neon_vld1_v:
4958  case NEON::BI__builtin_neon_vld1q_v: {
4959  llvm::Type *Tys[] = {Ty, Int8PtrTy};
4960  Ops.push_back(getAlignmentValue32(PtrOp0));
4961  return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, "vld1");
4962  }
4963  case NEON::BI__builtin_neon_vld1_x2_v:
4964  case NEON::BI__builtin_neon_vld1q_x2_v:
4965  case NEON::BI__builtin_neon_vld1_x3_v:
4966  case NEON::BI__builtin_neon_vld1q_x3_v:
4967  case NEON::BI__builtin_neon_vld1_x4_v:
4968  case NEON::BI__builtin_neon_vld1q_x4_v: {
4969  llvm::Type *PTy = llvm::PointerType::getUnqual(VTy->getVectorElementType());
4970  Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
4971  llvm::Type *Tys[2] = { VTy, PTy };
4972  Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
4973  Ops[1] = Builder.CreateCall(F, Ops[1], "vld1xN");
4974  Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
4975  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
4976  return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
4977  }
4978  case NEON::BI__builtin_neon_vld2_v:
4979  case NEON::BI__builtin_neon_vld2q_v:
4980  case NEON::BI__builtin_neon_vld3_v:
4981  case NEON::BI__builtin_neon_vld3q_v:
4982  case NEON::BI__builtin_neon_vld4_v:
4983  case NEON::BI__builtin_neon_vld4q_v: {
4984  llvm::Type *Tys[] = {Ty, Int8PtrTy};
4985  Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
4986  Value *Align = getAlignmentValue32(PtrOp1);
4987  Ops[1] = Builder.CreateCall(F, {Ops[1], Align}, NameHint);
4988  Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
4989  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
4990  return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
4991  }
4992  case NEON::BI__builtin_neon_vld1_dup_v:
4993  case NEON::BI__builtin_neon_vld1q_dup_v: {
4994  Value *V = UndefValue::get(Ty);
4995  Ty = llvm::PointerType::getUnqual(VTy->getElementType());
4996  PtrOp0 = Builder.CreateBitCast(PtrOp0, Ty);
4997  LoadInst *Ld = Builder.CreateLoad(PtrOp0);
4998  llvm::Constant *CI = ConstantInt::get(SizeTy, 0);
4999  Ops[0] = Builder.CreateInsertElement(V, Ld, CI);
5000  return EmitNeonSplat(Ops[0], CI);
5001  }
5002  case NEON::BI__builtin_neon_vld2_lane_v:
5003  case NEON::BI__builtin_neon_vld2q_lane_v:
5004  case NEON::BI__builtin_neon_vld3_lane_v:
5005  case NEON::BI__builtin_neon_vld3q_lane_v:
5006  case NEON::BI__builtin_neon_vld4_lane_v:
5007  case NEON::BI__builtin_neon_vld4q_lane_v: {
5008  llvm::Type *Tys[] = {Ty, Int8PtrTy};
5009  Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
5010  for (unsigned I = 2; I < Ops.size() - 1; ++I)
5011  Ops[I] = Builder.CreateBitCast(Ops[I], Ty);
5012  Ops.push_back(getAlignmentValue32(PtrOp1));
5013  Ops[1] = Builder.CreateCall(F, makeArrayRef(Ops).slice(1), NameHint);
5014  Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
5015  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
5016  return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
5017  }
5018  case NEON::BI__builtin_neon_vmovl_v: {
5019  llvm::Type *DTy =llvm::VectorType::getTruncatedElementVectorType(VTy);
5020  Ops[0] = Builder.CreateBitCast(Ops[0], DTy);
5021  if (Usgn)
5022  return Builder.CreateZExt(Ops[0], Ty, "vmovl");
5023  return Builder.CreateSExt(Ops[0], Ty, "vmovl");
5024  }
5025  case NEON::BI__builtin_neon_vmovn_v: {
5026  llvm::Type *QTy = llvm::VectorType::getExtendedElementVectorType(VTy);
5027  Ops[0] = Builder.CreateBitCast(Ops[0], QTy);
5028  return Builder.CreateTrunc(Ops[0], Ty, "vmovn");
5029  }
5030  case NEON::BI__builtin_neon_vmull_v:
5031  // FIXME: the integer vmull operations could be emitted in terms of pure
5032  // LLVM IR (2 exts followed by a mul). Unfortunately LLVM has a habit of
5033  // hoisting the exts outside loops. Until global ISel comes along that can
5034  // see through such movement this leads to bad CodeGen. So we need an
5035  // intrinsic for now.
5036  Int = Usgn ? Intrinsic::arm_neon_vmullu : Intrinsic::arm_neon_vmulls;
5037  Int = Type.isPoly() ? (unsigned)Intrinsic::arm_neon_vmullp : Int;
5038  return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmull");
5039  case NEON::BI__builtin_neon_vpadal_v:
5040  case NEON::BI__builtin_neon_vpadalq_v: {
5041  // The source operand type has twice as many elements of half the size.
5042  unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
5043  llvm::Type *EltTy =
5044  llvm::IntegerType::get(getLLVMContext(), EltBits / 2);
5045  llvm::Type *NarrowTy =
5046  llvm::VectorType::get(EltTy, VTy->getNumElements() * 2);
5047  llvm::Type *Tys[2] = { Ty, NarrowTy };
5048  return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, NameHint);
5049  }
5050  case NEON::BI__builtin_neon_vpaddl_v:
5051  case NEON::BI__builtin_neon_vpaddlq_v: {
5052  // The source operand type has twice as many elements of half the size.
5053  unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
5054  llvm::Type *EltTy = llvm::IntegerType::get(getLLVMContext(), EltBits / 2);
5055  llvm::Type *NarrowTy =
5056  llvm::VectorType::get(EltTy, VTy->getNumElements() * 2);
5057  llvm::Type *Tys[2] = { Ty, NarrowTy };
5058  return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vpaddl");
5059  }
5060  case NEON::BI__builtin_neon_vqdmlal_v:
5061  case NEON::BI__builtin_neon_vqdmlsl_v: {
5062  SmallVector<Value *, 2> MulOps(Ops.begin() + 1, Ops.end());
5063  Ops[1] =
5064  EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Ty), MulOps, "vqdmlal");
5065  Ops.resize(2);
5066  return EmitNeonCall(CGM.getIntrinsic(AltLLVMIntrinsic, Ty), Ops, NameHint);
5067  }
5068  case NEON::BI__builtin_neon_vqshl_n_v:
5069  case NEON::BI__builtin_neon_vqshlq_n_v:
5070  return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshl_n",
5071  1, false);
5072  case NEON::BI__builtin_neon_vqshlu_n_v:
5073  case NEON::BI__builtin_neon_vqshluq_n_v:
5074  return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshlu_n",
5075  1, false);
5076  case NEON::BI__builtin_neon_vrecpe_v:
5077  case NEON::BI__builtin_neon_vrecpeq_v:
5078  case NEON::BI__builtin_neon_vrsqrte_v:
5079  case NEON::BI__builtin_neon_vrsqrteq_v:
5080  Int = Ty->isFPOrFPVectorTy() ? LLVMIntrinsic : AltLLVMIntrinsic;
5081  return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, NameHint);
5082 
5083  case NEON::BI__builtin_neon_vrshr_n_v:
5084  case NEON::BI__builtin_neon_vrshrq_n_v:
5085  return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrshr_n",
5086  1, true);
5087  case NEON::BI__builtin_neon_vshl_n_v:
5088  case NEON::BI__builtin_neon_vshlq_n_v:
5089  Ops[1] = EmitNeonShiftVector(Ops[1], Ty, false);
5090  return Builder.CreateShl(Builder.CreateBitCast(Ops[0],Ty), Ops[1],
5091  "vshl_n");
5092  case NEON::BI__builtin_neon_vshll_n_v: {
5093  llvm::Type *SrcTy = llvm::VectorType::getTruncatedElementVectorType(VTy);
5094  Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
5095  if (Usgn)
5096  Ops[0] = Builder.CreateZExt(Ops[0], VTy);
5097  else
5098  Ops[0] = Builder.CreateSExt(Ops[0], VTy);
5099  Ops[1] = EmitNeonShiftVector(Ops[1], VTy, false);
5100  return Builder.CreateShl(Ops[0], Ops[1], "vshll_n");
5101  }
5102  case NEON::BI__builtin_neon_vshrn_n_v: {
5103  llvm::Type *SrcTy = llvm::VectorType::getExtendedElementVectorType(VTy);
5104  Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
5105  Ops[1] = EmitNeonShiftVector(Ops[1], SrcTy, false);
5106  if (Usgn)
5107  Ops[0] = Builder.CreateLShr(Ops[0], Ops[1]);
5108  else
5109  Ops[0] = Builder.CreateAShr(Ops[0], Ops[1]);
5110  return Builder.CreateTrunc(Ops[0], Ty, "vshrn_n");
5111  }
5112  case NEON::BI__builtin_neon_vshr_n_v:
5113  case NEON::BI__builtin_neon_vshrq_n_v:
5114  return EmitNeonRShiftImm(Ops[0], Ops[1], Ty, Usgn, "vshr_n");
5115  case NEON::BI__builtin_neon_vst1_v:
5116  case NEON::BI__builtin_neon_vst1q_v:
5117  case NEON::BI__builtin_neon_vst2_v:
5118  case NEON::BI__builtin_neon_vst2q_v:
5119  case NEON::BI__builtin_neon_vst3_v:
5120  case NEON::BI__builtin_neon_vst3q_v:
5121  case NEON::BI__builtin_neon_vst4_v:
5122  case NEON::BI__builtin_neon_vst4q_v:
5123  case NEON::BI__builtin_neon_vst2_lane_v:
5124  case NEON::BI__builtin_neon_vst2q_lane_v:
5125  case NEON::BI__builtin_neon_vst3_lane_v:
5126  case NEON::BI__builtin_neon_vst3q_lane_v:
5127  case NEON::BI__builtin_neon_vst4_lane_v:
5128  case NEON::BI__builtin_neon_vst4q_lane_v: {
5129  llvm::Type *Tys[] = {Int8PtrTy, Ty};
5130  Ops.push_back(getAlignmentValue32(PtrOp0));
5131  return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "");
5132  }
5133  case NEON::BI__builtin_neon_vst1_x2_v:
5134  case NEON::BI__builtin_neon_vst1q_x2_v:
5135  case NEON::BI__builtin_neon_vst1_x3_v:
5136  case NEON::BI__builtin_neon_vst1q_x3_v:
5137  case NEON::BI__builtin_neon_vst1_x4_v:
5138  case NEON::BI__builtin_neon_vst1q_x4_v: {
5139  llvm::Type *PTy = llvm::PointerType::getUnqual(VTy->getVectorElementType());
5140  // TODO: Currently in AArch32 mode the pointer operand comes first, whereas
5141  // in AArch64 it comes last. We may want to stick to one or another.
5142  if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) {
5143  llvm::Type *Tys[2] = { VTy, PTy };
5144  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
5145  return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, "");
5146  }
5147  llvm::Type *Tys[2] = { PTy, VTy };
5148  return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, "");
5149  }
5150  case NEON::BI__builtin_neon_vsubhn_v: {
5151  llvm::VectorType *SrcTy =
5152  llvm::VectorType::getExtendedElementVectorType(VTy);
5153 
5154  // %sum = add <4 x i32> %lhs, %rhs
5155  Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
5156  Ops[1] = Builder.CreateBitCast(Ops[1], SrcTy);
5157  Ops[0] = Builder.CreateSub(Ops[0], Ops[1], "vsubhn");
5158 
5159  // %high = lshr <4 x i32> %sum, <i32 16, i32 16, i32 16, i32 16>
5160  Constant *ShiftAmt =
5161  ConstantInt::get(SrcTy, SrcTy->getScalarSizeInBits() / 2);
5162  Ops[0] = Builder.CreateLShr(Ops[0], ShiftAmt, "vsubhn");
5163 
5164  // %res = trunc <4 x i32> %high to <4 x i16>
5165  return Builder.CreateTrunc(Ops[0], VTy, "vsubhn");
5166  }
5167  case NEON::BI__builtin_neon_vtrn_v:
5168  case NEON::BI__builtin_neon_vtrnq_v: {
5169  Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
5170  Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
5171  Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
5172  Value *SV = nullptr;
5173 
5174  for (unsigned vi = 0; vi != 2; ++vi) {
5175  SmallVector<uint32_t, 16> Indices;
5176  for (unsigned i = 0, e = VTy->getNumElements(); i != e; i += 2) {
5177  Indices.push_back(i+vi);
5178  Indices.push_back(i+e+vi);
5179  }
5180  Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
5181  SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vtrn");
5182  SV = Builder.CreateDefaultAlignedStore(SV, Addr);
5183  }
5184  return SV;
5185  }
5186  case NEON::BI__builtin_neon_vtst_v:
5187  case NEON::BI__builtin_neon_vtstq_v: {
5188  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
5189  Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
5190  Ops[0] = Builder.CreateAnd(Ops[0], Ops[1]);
5191  Ops[0] = Builder.CreateICmp(ICmpInst::ICMP_NE, Ops[0],
5192  ConstantAggregateZero::get(Ty));
5193  return Builder.CreateSExt(Ops[0], Ty, <