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