clang  5.0.0
CGExprCXX.cpp
Go to the documentation of this file.
1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code dealing with code generation of C++ expressions
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Intrinsics.h"
23 
24 using namespace clang;
25 using namespace CodeGen;
26 
27 namespace {
28 struct MemberCallInfo {
29  RequiredArgs ReqArgs;
30  // Number of prefix arguments for the call. Ignores the `this` pointer.
31  unsigned PrefixSize;
32 };
33 }
34 
35 static MemberCallInfo
37  llvm::Value *This, llvm::Value *ImplicitParam,
38  QualType ImplicitParamTy, const CallExpr *CE,
39  CallArgList &Args, CallArgList *RtlArgs) {
40  assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
41  isa<CXXOperatorCallExpr>(CE));
42  assert(MD->isInstance() &&
43  "Trying to emit a member or operator call expr on a static method!");
44  ASTContext &C = CGF.getContext();
45 
46  // Push the this ptr.
47  const CXXRecordDecl *RD =
49  Args.add(RValue::get(This),
50  RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
51 
52  // If there is an implicit parameter (e.g. VTT), emit it.
53  if (ImplicitParam) {
54  Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
55  }
56 
57  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
58  RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
59  unsigned PrefixSize = Args.size() - 1;
60 
61  // And the rest of the call args.
62  if (RtlArgs) {
63  // Special case: if the caller emitted the arguments right-to-left already
64  // (prior to emitting the *this argument), we're done. This happens for
65  // assignment operators.
66  Args.addFrom(*RtlArgs);
67  } else if (CE) {
68  // Special case: skip first argument of CXXOperatorCall (it is "this").
69  unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
70  CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
71  CE->getDirectCallee());
72  } else {
73  assert(
74  FPT->getNumParams() == 0 &&
75  "No CallExpr specified for function with non-zero number of arguments");
76  }
77  return {required, PrefixSize};
78 }
79 
81  const CXXMethodDecl *MD, const CGCallee &Callee,
82  ReturnValueSlot ReturnValue,
83  llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
84  const CallExpr *CE, CallArgList *RtlArgs) {
85  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
86  CallArgList Args;
87  MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
88  *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
89  auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
90  Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
91  return EmitCall(FnInfo, Callee, ReturnValue, Args);
92 }
93 
95  const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
96  llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
98  CallArgList Args;
99  commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
100  ImplicitParamTy, CE, Args, nullptr);
102  Callee, ReturnValueSlot(), Args);
103 }
104 
106  const CXXPseudoDestructorExpr *E) {
107  QualType DestroyedType = E->getDestroyedType();
108  if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
109  // Automatic Reference Counting:
110  // If the pseudo-expression names a retainable object with weak or
111  // strong lifetime, the object shall be released.
112  Expr *BaseExpr = E->getBase();
113  Address BaseValue = Address::invalid();
114  Qualifiers BaseQuals;
115 
116  // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
117  if (E->isArrow()) {
118  BaseValue = EmitPointerWithAlignment(BaseExpr);
119  const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
120  BaseQuals = PTy->getPointeeType().getQualifiers();
121  } else {
122  LValue BaseLV = EmitLValue(BaseExpr);
123  BaseValue = BaseLV.getAddress();
124  QualType BaseTy = BaseExpr->getType();
125  BaseQuals = BaseTy.getQualifiers();
126  }
127 
128  switch (DestroyedType.getObjCLifetime()) {
132  break;
133 
136  DestroyedType.isVolatileQualified()),
138  break;
139 
141  EmitARCDestroyWeak(BaseValue);
142  break;
143  }
144  } else {
145  // C++ [expr.pseudo]p1:
146  // The result shall only be used as the operand for the function call
147  // operator (), and the result of such a call has type void. The only
148  // effect is the evaluation of the postfix-expression before the dot or
149  // arrow.
150  EmitIgnoredExpr(E->getBase());
151  }
152 
153  return RValue::get(nullptr);
154 }
155 
156 static CXXRecordDecl *getCXXRecord(const Expr *E) {
157  QualType T = E->getType();
158  if (const PointerType *PTy = T->getAs<PointerType>())
159  T = PTy->getPointeeType();
160  const RecordType *Ty = T->castAs<RecordType>();
161  return cast<CXXRecordDecl>(Ty->getDecl());
162 }
163 
164 // Note: This function also emit constructor calls to support a MSVC
165 // extensions allowing explicit constructor function call.
167  ReturnValueSlot ReturnValue) {
168  const Expr *callee = CE->getCallee()->IgnoreParens();
169 
170  if (isa<BinaryOperator>(callee))
171  return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
172 
173  const MemberExpr *ME = cast<MemberExpr>(callee);
174  const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
175 
176  if (MD->isStatic()) {
177  // The method is static, emit it as we would a regular call.
179  return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
180  ReturnValue);
181  }
182 
183  bool HasQualifier = ME->hasQualifier();
184  NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
185  bool IsArrow = ME->isArrow();
186  const Expr *Base = ME->getBase();
187 
189  CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
190 }
191 
193  const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
194  bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
195  const Expr *Base) {
196  assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
197 
198  // Compute the object pointer.
199  bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
200 
201  const CXXMethodDecl *DevirtualizedMethod = nullptr;
202  if (CanUseVirtualCall &&
203  MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
204  const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
205  DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
206  assert(DevirtualizedMethod);
207  const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
208  const Expr *Inner = Base->ignoreParenBaseCasts();
209  if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
211  // If the return types are not the same, this might be a case where more
212  // code needs to run to compensate for it. For example, the derived
213  // method might return a type that inherits form from the return
214  // type of MD and has a prefix.
215  // For now we just avoid devirtualizing these covariant cases.
216  DevirtualizedMethod = nullptr;
217  else if (getCXXRecord(Inner) == DevirtualizedClass)
218  // If the class of the Inner expression is where the dynamic method
219  // is defined, build the this pointer from it.
220  Base = Inner;
221  else if (getCXXRecord(Base) != DevirtualizedClass) {
222  // If the method is defined in a class that is not the best dynamic
223  // one or the one of the full expression, we would have to build
224  // a derived-to-base cast to compute the correct this pointer, but
225  // we don't have support for that yet, so do a virtual call.
226  DevirtualizedMethod = nullptr;
227  }
228  }
229 
230  // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
231  // operator before the LHS.
232  CallArgList RtlArgStorage;
233  CallArgList *RtlArgs = nullptr;
234  if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
235  if (OCE->isAssignmentOp()) {
236  RtlArgs = &RtlArgStorage;
237  EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
238  drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
239  /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
240  }
241  }
242 
243  Address This = Address::invalid();
244  if (IsArrow)
245  This = EmitPointerWithAlignment(Base);
246  else
247  This = EmitLValue(Base).getAddress();
248 
249 
250  if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
251  if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
252  if (isa<CXXConstructorDecl>(MD) &&
253  cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
254  return RValue::get(nullptr);
255 
256  if (!MD->getParent()->mayInsertExtraPadding()) {
258  // We don't like to generate the trivial copy/move assignment operator
259  // when it isn't necessary; just produce the proper effect here.
260  LValue RHS = isa<CXXOperatorCallExpr>(CE)
262  (*RtlArgs)[0].RV.getScalarVal(),
263  (*(CE->arg_begin() + 1))->getType())
264  : EmitLValue(*CE->arg_begin());
265  EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
266  return RValue::get(This.getPointer());
267  }
268 
269  if (isa<CXXConstructorDecl>(MD) &&
270  cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
271  // Trivial move and copy ctor are the same.
272  assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
273  Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
274  EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
275  return RValue::get(This.getPointer());
276  }
277  llvm_unreachable("unknown trivial member function");
278  }
279  }
280 
281  // Compute the function type we're calling.
282  const CXXMethodDecl *CalleeDecl =
283  DevirtualizedMethod ? DevirtualizedMethod : MD;
284  const CGFunctionInfo *FInfo = nullptr;
285  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
287  Dtor, StructorType::Complete);
288  else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
290  Ctor, StructorType::Complete);
291  else
292  FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
293 
294  llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
295 
296  // C++11 [class.mfct.non-static]p2:
297  // If a non-static member function of a class X is called for an object that
298  // is not of type X, or of a type derived from X, the behavior is undefined.
299  SourceLocation CallLoc;
300  ASTContext &C = getContext();
301  if (CE)
302  CallLoc = CE->getExprLoc();
303 
304  SanitizerSet SkippedChecks;
305  if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
306  auto *IOA = CMCE->getImplicitObjectArgument();
307  bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
308  if (IsImplicitObjectCXXThis)
309  SkippedChecks.set(SanitizerKind::Alignment, true);
310  if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
311  SkippedChecks.set(SanitizerKind::Null, true);
312  }
314  isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
316  CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
317  /*Alignment=*/CharUnits::Zero(), SkippedChecks);
318 
319  // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
320  // 'CalleeDecl' instead.
321 
322  // C++ [class.virtual]p12:
323  // Explicit qualification with the scope operator (5.1) suppresses the
324  // virtual call mechanism.
325  //
326  // We also don't emit a virtual call if the base expression has a record type
327  // because then we know what the type is.
328  bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
329 
330  if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
331  assert(CE->arg_begin() == CE->arg_end() &&
332  "Destructor shouldn't have explicit parameters");
333  assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
334  if (UseVirtualCall) {
336  *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
337  } else {
338  CGCallee Callee;
339  if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
340  Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
341  else if (!DevirtualizedMethod)
342  Callee = CGCallee::forDirect(
344  Dtor);
345  else {
346  const CXXDestructorDecl *DDtor =
347  cast<CXXDestructorDecl>(DevirtualizedMethod);
348  Callee = CGCallee::forDirect(
350  DDtor);
351  }
353  CalleeDecl, Callee, ReturnValue, This.getPointer(),
354  /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
355  }
356  return RValue::get(nullptr);
357  }
358 
359  CGCallee Callee;
360  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
361  Callee = CGCallee::forDirect(
363  Ctor);
364  } else if (UseVirtualCall) {
365  Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
366  CE->getLocStart());
367  } else {
368  if (SanOpts.has(SanitizerKind::CFINVCall) &&
369  MD->getParent()->isDynamicClass()) {
370  llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
372  CE->getLocStart());
373  }
374 
375  if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
376  Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
377  else if (!DevirtualizedMethod)
378  Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
379  else {
380  Callee = CGCallee::forDirect(
381  CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
382  DevirtualizedMethod);
383  }
384  }
385 
386  if (MD->isVirtual()) {
388  *this, CalleeDecl, This, UseVirtualCall);
389  }
390 
392  CalleeDecl, Callee, ReturnValue, This.getPointer(),
393  /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
394 }
395 
396 RValue
398  ReturnValueSlot ReturnValue) {
399  const BinaryOperator *BO =
400  cast<BinaryOperator>(E->getCallee()->IgnoreParens());
401  const Expr *BaseExpr = BO->getLHS();
402  const Expr *MemFnExpr = BO->getRHS();
403 
404  const MemberPointerType *MPT =
405  MemFnExpr->getType()->castAs<MemberPointerType>();
406 
407  const FunctionProtoType *FPT =
409  const CXXRecordDecl *RD =
410  cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
411 
412  // Emit the 'this' pointer.
413  Address This = Address::invalid();
414  if (BO->getOpcode() == BO_PtrMemI)
415  This = EmitPointerWithAlignment(BaseExpr);
416  else
417  This = EmitLValue(BaseExpr).getAddress();
418 
419  EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
420  QualType(MPT->getClass(), 0));
421 
422  // Get the member function pointer.
423  llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
424 
425  // Ask the ABI to load the callee. Note that This is modified.
426  llvm::Value *ThisPtrForCall = nullptr;
427  CGCallee Callee =
429  ThisPtrForCall, MemFnPtr, MPT);
430 
431  CallArgList Args;
432 
433  QualType ThisType =
434  getContext().getPointerType(getContext().getTagDeclType(RD));
435 
436  // Push the this ptr.
437  Args.add(RValue::get(ThisPtrForCall), ThisType);
438 
439  RequiredArgs required =
440  RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
441 
442  // And the rest of the call args
443  EmitCallArgs(Args, FPT, E->arguments());
444  return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
445  /*PrefixSize=*/0),
446  Callee, ReturnValue, Args);
447 }
448 
449 RValue
451  const CXXMethodDecl *MD,
452  ReturnValueSlot ReturnValue) {
453  assert(MD->isInstance() &&
454  "Trying to emit a member call expr on a static method!");
456  E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
457  /*IsArrow=*/false, E->getArg(0));
458 }
459 
461  ReturnValueSlot ReturnValue) {
462  return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
463 }
464 
466  Address DestPtr,
467  const CXXRecordDecl *Base) {
468  if (Base->isEmpty())
469  return;
470 
471  DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
472 
473  const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
474  CharUnits NVSize = Layout.getNonVirtualSize();
475 
476  // We cannot simply zero-initialize the entire base sub-object if vbptrs are
477  // present, they are initialized by the most derived class before calling the
478  // constructor.
480  Stores.emplace_back(CharUnits::Zero(), NVSize);
481 
482  // Each store is split by the existence of a vbptr.
483  CharUnits VBPtrWidth = CGF.getPointerSize();
484  std::vector<CharUnits> VBPtrOffsets =
485  CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
486  for (CharUnits VBPtrOffset : VBPtrOffsets) {
487  // Stop before we hit any virtual base pointers located in virtual bases.
488  if (VBPtrOffset >= NVSize)
489  break;
490  std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
491  CharUnits LastStoreOffset = LastStore.first;
492  CharUnits LastStoreSize = LastStore.second;
493 
494  CharUnits SplitBeforeOffset = LastStoreOffset;
495  CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
496  assert(!SplitBeforeSize.isNegative() && "negative store size!");
497  if (!SplitBeforeSize.isZero())
498  Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
499 
500  CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
501  CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
502  assert(!SplitAfterSize.isNegative() && "negative store size!");
503  if (!SplitAfterSize.isZero())
504  Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
505  }
506 
507  // If the type contains a pointer to data member we can't memset it to zero.
508  // Instead, create a null constant and copy it to the destination.
509  // TODO: there are other patterns besides zero that we can usefully memset,
510  // like -1, which happens to be the pattern used by member-pointers.
511  // TODO: isZeroInitializable can be over-conservative in the case where a
512  // virtual base contains a member pointer.
513  llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
514  if (!NullConstantForBase->isNullValue()) {
515  llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
516  CGF.CGM.getModule(), NullConstantForBase->getType(),
517  /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
518  NullConstantForBase, Twine());
519 
520  CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
521  DestPtr.getAlignment());
522  NullVariable->setAlignment(Align.getQuantity());
523 
524  Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
525 
526  // Get and call the appropriate llvm.memcpy overload.
527  for (std::pair<CharUnits, CharUnits> Store : Stores) {
528  CharUnits StoreOffset = Store.first;
529  CharUnits StoreSize = Store.second;
530  llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
531  CGF.Builder.CreateMemCpy(
532  CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
533  CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
534  StoreSizeVal);
535  }
536 
537  // Otherwise, just memset the whole thing to zero. This is legal
538  // because in LLVM, all default initializers (other than the ones we just
539  // handled above) are guaranteed to have a bit pattern of all zeros.
540  } else {
541  for (std::pair<CharUnits, CharUnits> Store : Stores) {
542  CharUnits StoreOffset = Store.first;
543  CharUnits StoreSize = Store.second;
544  llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
545  CGF.Builder.CreateMemSet(
546  CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
547  CGF.Builder.getInt8(0), StoreSizeVal);
548  }
549  }
550 }
551 
552 void
554  AggValueSlot Dest) {
555  assert(!Dest.isIgnored() && "Must have a destination!");
556  const CXXConstructorDecl *CD = E->getConstructor();
557 
558  // If we require zero initialization before (or instead of) calling the
559  // constructor, as can be the case with a non-user-provided default
560  // constructor, emit the zero initialization now, unless destination is
561  // already zeroed.
562  if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
563  switch (E->getConstructionKind()) {
567  break;
571  CD->getParent());
572  break;
573  }
574  }
575 
576  // If this is a call to a trivial default constructor, do nothing.
577  if (CD->isTrivial() && CD->isDefaultConstructor())
578  return;
579 
580  // Elide the constructor if we're constructing from a temporary.
581  // The temporary check is required because Sema sets this on NRVO
582  // returns.
583  if (getLangOpts().ElideConstructors && E->isElidable()) {
584  assert(getContext().hasSameUnqualifiedType(E->getType(),
585  E->getArg(0)->getType()));
586  if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
587  EmitAggExpr(E->getArg(0), Dest);
588  return;
589  }
590  }
591 
592  if (const ArrayType *arrayType
593  = getContext().getAsArrayType(E->getType())) {
594  EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
595  } else {
597  bool ForVirtualBase = false;
598  bool Delegating = false;
599 
600  switch (E->getConstructionKind()) {
602  // We should be emitting a constructor; GlobalDecl will assert this
603  Type = CurGD.getCtorType();
604  Delegating = true;
605  break;
606 
608  Type = Ctor_Complete;
609  break;
610 
612  ForVirtualBase = true;
613  // fall-through
614 
616  Type = Ctor_Base;
617  }
618 
619  // Call the constructor.
620  EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
621  Dest.getAddress(), E);
622  }
623 }
624 
626  const Expr *Exp) {
627  if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
628  Exp = E->getSubExpr();
629  assert(isa<CXXConstructExpr>(Exp) &&
630  "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
631  const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
632  const CXXConstructorDecl *CD = E->getConstructor();
633  RunCleanupsScope Scope(*this);
634 
635  // If we require zero initialization before (or instead of) calling the
636  // constructor, as can be the case with a non-user-provided default
637  // constructor, emit the zero initialization now.
638  // FIXME. Do I still need this for a copy ctor synthesis?
640  EmitNullInitialization(Dest, E->getType());
641 
642  assert(!getContext().getAsConstantArrayType(E->getType())
643  && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
644  EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
645 }
646 
648  const CXXNewExpr *E) {
649  if (!E->isArray())
650  return CharUnits::Zero();
651 
652  // No cookie is required if the operator new[] being used is the
653  // reserved placement operator new[].
655  return CharUnits::Zero();
656 
657  return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
658 }
659 
661  const CXXNewExpr *e,
662  unsigned minElements,
663  llvm::Value *&numElements,
664  llvm::Value *&sizeWithoutCookie) {
666 
667  if (!e->isArray()) {
668  CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
669  sizeWithoutCookie
670  = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
671  return sizeWithoutCookie;
672  }
673 
674  // The width of size_t.
675  unsigned sizeWidth = CGF.SizeTy->getBitWidth();
676 
677  // Figure out the cookie size.
678  llvm::APInt cookieSize(sizeWidth,
679  CalculateCookiePadding(CGF, e).getQuantity());
680 
681  // Emit the array size expression.
682  // We multiply the size of all dimensions for NumElements.
683  // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
684  numElements = CGF.CGM.EmitConstantExpr(e->getArraySize(),
685  CGF.getContext().getSizeType(), &CGF);
686  if (!numElements)
687  numElements = CGF.EmitScalarExpr(e->getArraySize());
688  assert(isa<llvm::IntegerType>(numElements->getType()));
689 
690  // The number of elements can be have an arbitrary integer type;
691  // essentially, we need to multiply it by a constant factor, add a
692  // cookie size, and verify that the result is representable as a
693  // size_t. That's just a gloss, though, and it's wrong in one
694  // important way: if the count is negative, it's an error even if
695  // the cookie size would bring the total size >= 0.
696  bool isSigned
698  llvm::IntegerType *numElementsType
699  = cast<llvm::IntegerType>(numElements->getType());
700  unsigned numElementsWidth = numElementsType->getBitWidth();
701 
702  // Compute the constant factor.
703  llvm::APInt arraySizeMultiplier(sizeWidth, 1);
704  while (const ConstantArrayType *CAT
705  = CGF.getContext().getAsConstantArrayType(type)) {
706  type = CAT->getElementType();
707  arraySizeMultiplier *= CAT->getSize();
708  }
709 
710  CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
711  llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
712  typeSizeMultiplier *= arraySizeMultiplier;
713 
714  // This will be a size_t.
715  llvm::Value *size;
716 
717  // If someone is doing 'new int[42]' there is no need to do a dynamic check.
718  // Don't bloat the -O0 code.
719  if (llvm::ConstantInt *numElementsC =
720  dyn_cast<llvm::ConstantInt>(numElements)) {
721  const llvm::APInt &count = numElementsC->getValue();
722 
723  bool hasAnyOverflow = false;
724 
725  // If 'count' was a negative number, it's an overflow.
726  if (isSigned && count.isNegative())
727  hasAnyOverflow = true;
728 
729  // We want to do all this arithmetic in size_t. If numElements is
730  // wider than that, check whether it's already too big, and if so,
731  // overflow.
732  else if (numElementsWidth > sizeWidth &&
733  numElementsWidth - sizeWidth > count.countLeadingZeros())
734  hasAnyOverflow = true;
735 
736  // Okay, compute a count at the right width.
737  llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
738 
739  // If there is a brace-initializer, we cannot allocate fewer elements than
740  // there are initializers. If we do, that's treated like an overflow.
741  if (adjustedCount.ult(minElements))
742  hasAnyOverflow = true;
743 
744  // Scale numElements by that. This might overflow, but we don't
745  // care because it only overflows if allocationSize does, too, and
746  // if that overflows then we shouldn't use this.
747  numElements = llvm::ConstantInt::get(CGF.SizeTy,
748  adjustedCount * arraySizeMultiplier);
749 
750  // Compute the size before cookie, and track whether it overflowed.
751  bool overflow;
752  llvm::APInt allocationSize
753  = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
754  hasAnyOverflow |= overflow;
755 
756  // Add in the cookie, and check whether it's overflowed.
757  if (cookieSize != 0) {
758  // Save the current size without a cookie. This shouldn't be
759  // used if there was overflow.
760  sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
761 
762  allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
763  hasAnyOverflow |= overflow;
764  }
765 
766  // On overflow, produce a -1 so operator new will fail.
767  if (hasAnyOverflow) {
768  size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
769  } else {
770  size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
771  }
772 
773  // Otherwise, we might need to use the overflow intrinsics.
774  } else {
775  // There are up to five conditions we need to test for:
776  // 1) if isSigned, we need to check whether numElements is negative;
777  // 2) if numElementsWidth > sizeWidth, we need to check whether
778  // numElements is larger than something representable in size_t;
779  // 3) if minElements > 0, we need to check whether numElements is smaller
780  // than that.
781  // 4) we need to compute
782  // sizeWithoutCookie := numElements * typeSizeMultiplier
783  // and check whether it overflows; and
784  // 5) if we need a cookie, we need to compute
785  // size := sizeWithoutCookie + cookieSize
786  // and check whether it overflows.
787 
788  llvm::Value *hasOverflow = nullptr;
789 
790  // If numElementsWidth > sizeWidth, then one way or another, we're
791  // going to have to do a comparison for (2), and this happens to
792  // take care of (1), too.
793  if (numElementsWidth > sizeWidth) {
794  llvm::APInt threshold(numElementsWidth, 1);
795  threshold <<= sizeWidth;
796 
797  llvm::Value *thresholdV
798  = llvm::ConstantInt::get(numElementsType, threshold);
799 
800  hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
801  numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
802 
803  // Otherwise, if we're signed, we want to sext up to size_t.
804  } else if (isSigned) {
805  if (numElementsWidth < sizeWidth)
806  numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
807 
808  // If there's a non-1 type size multiplier, then we can do the
809  // signedness check at the same time as we do the multiply
810  // because a negative number times anything will cause an
811  // unsigned overflow. Otherwise, we have to do it here. But at least
812  // in this case, we can subsume the >= minElements check.
813  if (typeSizeMultiplier == 1)
814  hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
815  llvm::ConstantInt::get(CGF.SizeTy, minElements));
816 
817  // Otherwise, zext up to size_t if necessary.
818  } else if (numElementsWidth < sizeWidth) {
819  numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
820  }
821 
822  assert(numElements->getType() == CGF.SizeTy);
823 
824  if (minElements) {
825  // Don't allow allocation of fewer elements than we have initializers.
826  if (!hasOverflow) {
827  hasOverflow = CGF.Builder.CreateICmpULT(numElements,
828  llvm::ConstantInt::get(CGF.SizeTy, minElements));
829  } else if (numElementsWidth > sizeWidth) {
830  // The other existing overflow subsumes this check.
831  // We do an unsigned comparison, since any signed value < -1 is
832  // taken care of either above or below.
833  hasOverflow = CGF.Builder.CreateOr(hasOverflow,
834  CGF.Builder.CreateICmpULT(numElements,
835  llvm::ConstantInt::get(CGF.SizeTy, minElements)));
836  }
837  }
838 
839  size = numElements;
840 
841  // Multiply by the type size if necessary. This multiplier
842  // includes all the factors for nested arrays.
843  //
844  // This step also causes numElements to be scaled up by the
845  // nested-array factor if necessary. Overflow on this computation
846  // can be ignored because the result shouldn't be used if
847  // allocation fails.
848  if (typeSizeMultiplier != 1) {
849  llvm::Value *umul_with_overflow
850  = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
851 
852  llvm::Value *tsmV =
853  llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
854  llvm::Value *result =
855  CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
856 
857  llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
858  if (hasOverflow)
859  hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
860  else
861  hasOverflow = overflowed;
862 
863  size = CGF.Builder.CreateExtractValue(result, 0);
864 
865  // Also scale up numElements by the array size multiplier.
866  if (arraySizeMultiplier != 1) {
867  // If the base element type size is 1, then we can re-use the
868  // multiply we just did.
869  if (typeSize.isOne()) {
870  assert(arraySizeMultiplier == typeSizeMultiplier);
871  numElements = size;
872 
873  // Otherwise we need a separate multiply.
874  } else {
875  llvm::Value *asmV =
876  llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
877  numElements = CGF.Builder.CreateMul(numElements, asmV);
878  }
879  }
880  } else {
881  // numElements doesn't need to be scaled.
882  assert(arraySizeMultiplier == 1);
883  }
884 
885  // Add in the cookie size if necessary.
886  if (cookieSize != 0) {
887  sizeWithoutCookie = size;
888 
889  llvm::Value *uadd_with_overflow
890  = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
891 
892  llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
893  llvm::Value *result =
894  CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
895 
896  llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
897  if (hasOverflow)
898  hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
899  else
900  hasOverflow = overflowed;
901 
902  size = CGF.Builder.CreateExtractValue(result, 0);
903  }
904 
905  // If we had any possibility of dynamic overflow, make a select to
906  // overwrite 'size' with an all-ones value, which should cause
907  // operator new to throw.
908  if (hasOverflow)
909  size = CGF.Builder.CreateSelect(hasOverflow,
910  llvm::Constant::getAllOnesValue(CGF.SizeTy),
911  size);
912  }
913 
914  if (cookieSize == 0)
915  sizeWithoutCookie = size;
916  else
917  assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
918 
919  return size;
920 }
921 
922 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
923  QualType AllocType, Address NewPtr) {
924  // FIXME: Refactor with EmitExprAsInit.
925  switch (CGF.getEvaluationKind(AllocType)) {
926  case TEK_Scalar:
927  CGF.EmitScalarInit(Init, nullptr,
928  CGF.MakeAddrLValue(NewPtr, AllocType), false);
929  return;
930  case TEK_Complex:
931  CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
932  /*isInit*/ true);
933  return;
934  case TEK_Aggregate: {
935  AggValueSlot Slot
936  = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
940  CGF.EmitAggExpr(Init, Slot);
941  return;
942  }
943  }
944  llvm_unreachable("bad evaluation kind");
945 }
946 
948  const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
949  Address BeginPtr, llvm::Value *NumElements,
950  llvm::Value *AllocSizeWithoutCookie) {
951  // If we have a type with trivial initialization and no initializer,
952  // there's nothing to do.
953  if (!E->hasInitializer())
954  return;
955 
956  Address CurPtr = BeginPtr;
957 
958  unsigned InitListElements = 0;
959 
960  const Expr *Init = E->getInitializer();
961  Address EndOfInit = Address::invalid();
962  QualType::DestructionKind DtorKind = ElementType.isDestructedType();
964  llvm::Instruction *CleanupDominator = nullptr;
965 
966  CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
967  CharUnits ElementAlign =
968  BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
969 
970  // Attempt to perform zero-initialization using memset.
971  auto TryMemsetInitialization = [&]() -> bool {
972  // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
973  // we can initialize with a memset to -1.
974  if (!CGM.getTypes().isZeroInitializable(ElementType))
975  return false;
976 
977  // Optimization: since zero initialization will just set the memory
978  // to all zeroes, generate a single memset to do it in one shot.
979 
980  // Subtract out the size of any elements we've already initialized.
981  auto *RemainingSize = AllocSizeWithoutCookie;
982  if (InitListElements) {
983  // We know this can't overflow; we check this when doing the allocation.
984  auto *InitializedSize = llvm::ConstantInt::get(
985  RemainingSize->getType(),
986  getContext().getTypeSizeInChars(ElementType).getQuantity() *
987  InitListElements);
988  RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
989  }
990 
991  // Create the memset.
992  Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
993  return true;
994  };
995 
996  // If the initializer is an initializer list, first do the explicit elements.
997  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
998  // Initializing from a (braced) string literal is a special case; the init
999  // list element does not initialize a (single) array element.
1000  if (ILE->isStringLiteralInit()) {
1001  // Initialize the initial portion of length equal to that of the string
1002  // literal. The allocation must be for at least this much; we emitted a
1003  // check for that earlier.
1004  AggValueSlot Slot =
1005  AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1009  EmitAggExpr(ILE->getInit(0), Slot);
1010 
1011  // Move past these elements.
1012  InitListElements =
1013  cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1014  ->getSize().getZExtValue();
1015  CurPtr =
1016  Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1017  Builder.getSize(InitListElements),
1018  "string.init.end"),
1019  CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1020  ElementSize));
1021 
1022  // Zero out the rest, if any remain.
1023  llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1024  if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1025  bool OK = TryMemsetInitialization();
1026  (void)OK;
1027  assert(OK && "couldn't memset character type?");
1028  }
1029  return;
1030  }
1031 
1032  InitListElements = ILE->getNumInits();
1033 
1034  // If this is a multi-dimensional array new, we will initialize multiple
1035  // elements with each init list element.
1036  QualType AllocType = E->getAllocatedType();
1037  if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1038  AllocType->getAsArrayTypeUnsafe())) {
1039  ElementTy = ConvertTypeForMem(AllocType);
1040  CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1041  InitListElements *= getContext().getConstantArrayElementCount(CAT);
1042  }
1043 
1044  // Enter a partial-destruction Cleanup if necessary.
1045  if (needsEHCleanup(DtorKind)) {
1046  // In principle we could tell the Cleanup where we are more
1047  // directly, but the control flow can get so varied here that it
1048  // would actually be quite complex. Therefore we go through an
1049  // alloca.
1050  EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1051  "array.init.end");
1052  CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1053  pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1054  ElementType, ElementAlign,
1055  getDestroyer(DtorKind));
1056  Cleanup = EHStack.stable_begin();
1057  }
1058 
1059  CharUnits StartAlign = CurPtr.getAlignment();
1060  for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1061  // Tell the cleanup that it needs to destroy up to this
1062  // element. TODO: some of these stores can be trivially
1063  // observed to be unnecessary.
1064  if (EndOfInit.isValid()) {
1065  auto FinishedPtr =
1066  Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1067  Builder.CreateStore(FinishedPtr, EndOfInit);
1068  }
1069  // FIXME: If the last initializer is an incomplete initializer list for
1070  // an array, and we have an array filler, we can fold together the two
1071  // initialization loops.
1072  StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1073  ILE->getInit(i)->getType(), CurPtr);
1074  CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1075  Builder.getSize(1),
1076  "array.exp.next"),
1077  StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1078  }
1079 
1080  // The remaining elements are filled with the array filler expression.
1081  Init = ILE->getArrayFiller();
1082 
1083  // Extract the initializer for the individual array elements by pulling
1084  // out the array filler from all the nested initializer lists. This avoids
1085  // generating a nested loop for the initialization.
1086  while (Init && Init->getType()->isConstantArrayType()) {
1087  auto *SubILE = dyn_cast<InitListExpr>(Init);
1088  if (!SubILE)
1089  break;
1090  assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1091  Init = SubILE->getArrayFiller();
1092  }
1093 
1094  // Switch back to initializing one base element at a time.
1095  CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1096  }
1097 
1098  // If all elements have already been initialized, skip any further
1099  // initialization.
1100  llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1101  if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1102  // If there was a Cleanup, deactivate it.
1103  if (CleanupDominator)
1104  DeactivateCleanupBlock(Cleanup, CleanupDominator);
1105  return;
1106  }
1107 
1108  assert(Init && "have trailing elements to initialize but no initializer");
1109 
1110  // If this is a constructor call, try to optimize it out, and failing that
1111  // emit a single loop to initialize all remaining elements.
1112  if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1113  CXXConstructorDecl *Ctor = CCE->getConstructor();
1114  if (Ctor->isTrivial()) {
1115  // If new expression did not specify value-initialization, then there
1116  // is no initialization.
1117  if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1118  return;
1119 
1120  if (TryMemsetInitialization())
1121  return;
1122  }
1123 
1124  // Store the new Cleanup position for irregular Cleanups.
1125  //
1126  // FIXME: Share this cleanup with the constructor call emission rather than
1127  // having it create a cleanup of its own.
1128  if (EndOfInit.isValid())
1129  Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1130 
1131  // Emit a constructor call loop to initialize the remaining elements.
1132  if (InitListElements)
1133  NumElements = Builder.CreateSub(
1134  NumElements,
1135  llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1136  EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1137  CCE->requiresZeroInitialization());
1138  return;
1139  }
1140 
1141  // If this is value-initialization, we can usually use memset.
1142  ImplicitValueInitExpr IVIE(ElementType);
1143  if (isa<ImplicitValueInitExpr>(Init)) {
1144  if (TryMemsetInitialization())
1145  return;
1146 
1147  // Switch to an ImplicitValueInitExpr for the element type. This handles
1148  // only one case: multidimensional array new of pointers to members. In
1149  // all other cases, we already have an initializer for the array element.
1150  Init = &IVIE;
1151  }
1152 
1153  // At this point we should have found an initializer for the individual
1154  // elements of the array.
1155  assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1156  "got wrong type of element to initialize");
1157 
1158  // If we have an empty initializer list, we can usually use memset.
1159  if (auto *ILE = dyn_cast<InitListExpr>(Init))
1160  if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1161  return;
1162 
1163  // If we have a struct whose every field is value-initialized, we can
1164  // usually use memset.
1165  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1166  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1167  if (RType->getDecl()->isStruct()) {
1168  unsigned NumElements = 0;
1169  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1170  NumElements = CXXRD->getNumBases();
1171  for (auto *Field : RType->getDecl()->fields())
1172  if (!Field->isUnnamedBitfield())
1173  ++NumElements;
1174  // FIXME: Recurse into nested InitListExprs.
1175  if (ILE->getNumInits() == NumElements)
1176  for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1177  if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1178  --NumElements;
1179  if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1180  return;
1181  }
1182  }
1183  }
1184 
1185  // Create the loop blocks.
1186  llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1187  llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1188  llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1189 
1190  // Find the end of the array, hoisted out of the loop.
1191  llvm::Value *EndPtr =
1192  Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1193 
1194  // If the number of elements isn't constant, we have to now check if there is
1195  // anything left to initialize.
1196  if (!ConstNum) {
1197  llvm::Value *IsEmpty =
1198  Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1199  Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1200  }
1201 
1202  // Enter the loop.
1203  EmitBlock(LoopBB);
1204 
1205  // Set up the current-element phi.
1206  llvm::PHINode *CurPtrPhi =
1207  Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1208  CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1209 
1210  CurPtr = Address(CurPtrPhi, ElementAlign);
1211 
1212  // Store the new Cleanup position for irregular Cleanups.
1213  if (EndOfInit.isValid())
1214  Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1215 
1216  // Enter a partial-destruction Cleanup if necessary.
1217  if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1219  ElementType, ElementAlign,
1220  getDestroyer(DtorKind));
1221  Cleanup = EHStack.stable_begin();
1222  CleanupDominator = Builder.CreateUnreachable();
1223  }
1224 
1225  // Emit the initializer into this element.
1226  StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
1227 
1228  // Leave the Cleanup if we entered one.
1229  if (CleanupDominator) {
1230  DeactivateCleanupBlock(Cleanup, CleanupDominator);
1231  CleanupDominator->eraseFromParent();
1232  }
1233 
1234  // Advance to the next element by adjusting the pointer type as necessary.
1235  llvm::Value *NextPtr =
1236  Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1237  "array.next");
1238 
1239  // Check whether we've gotten to the end of the array and, if so,
1240  // exit the loop.
1241  llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1242  Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1243  CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1244 
1245  EmitBlock(ContBB);
1246 }
1247 
1249  QualType ElementType, llvm::Type *ElementTy,
1250  Address NewPtr, llvm::Value *NumElements,
1251  llvm::Value *AllocSizeWithoutCookie) {
1252  ApplyDebugLocation DL(CGF, E);
1253  if (E->isArray())
1254  CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1255  AllocSizeWithoutCookie);
1256  else if (const Expr *Init = E->getInitializer())
1257  StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
1258 }
1259 
1260 /// Emit a call to an operator new or operator delete function, as implicitly
1261 /// created by new-expressions and delete-expressions.
1263  const FunctionDecl *CalleeDecl,
1264  const FunctionProtoType *CalleeType,
1265  const CallArgList &Args) {
1266  llvm::Instruction *CallOrInvoke;
1267  llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1268  CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
1269  RValue RV =
1271  Args, CalleeType, /*chainCall=*/false),
1272  Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1273 
1274  /// C++1y [expr.new]p10:
1275  /// [In a new-expression,] an implementation is allowed to omit a call
1276  /// to a replaceable global allocation function.
1277  ///
1278  /// We model such elidable calls with the 'builtin' attribute.
1279  llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1280  if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1281  Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1282  // FIXME: Add addAttribute to CallSite.
1283  if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1284  CI->addAttribute(llvm::AttributeList::FunctionIndex,
1285  llvm::Attribute::Builtin);
1286  else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1287  II->addAttribute(llvm::AttributeList::FunctionIndex,
1288  llvm::Attribute::Builtin);
1289  else
1290  llvm_unreachable("unexpected kind of call instruction");
1291  }
1292 
1293  return RV;
1294 }
1295 
1297  const Expr *Arg,
1298  bool IsDelete) {
1299  CallArgList Args;
1300  const Stmt *ArgS = Arg;
1301  EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1302  // Find the allocation or deallocation function that we're calling.
1303  ASTContext &Ctx = getContext();
1304  DeclarationName Name = Ctx.DeclarationNames
1305  .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1306  for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1307  if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1308  if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1309  return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1310  llvm_unreachable("predeclared global operator new/delete is missing");
1311 }
1312 
1313 static std::pair<bool, bool>
1315  auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1316 
1317  // The first argument is always a void*.
1318  ++AI;
1319 
1320  // Figure out what other parameters we should be implicitly passing.
1321  bool PassSize = false;
1322  bool PassAlignment = false;
1323 
1324  if (AI != AE && (*AI)->isIntegerType()) {
1325  PassSize = true;
1326  ++AI;
1327  }
1328 
1329  if (AI != AE && (*AI)->isAlignValT()) {
1330  PassAlignment = true;
1331  ++AI;
1332  }
1333 
1334  assert(AI == AE && "unexpected usual deallocation function parameter");
1335  return {PassSize, PassAlignment};
1336 }
1337 
1338 namespace {
1339  /// A cleanup to call the given 'operator delete' function upon abnormal
1340  /// exit from a new expression. Templated on a traits type that deals with
1341  /// ensuring that the arguments dominate the cleanup if necessary.
1342  template<typename Traits>
1343  class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1344  /// Type used to hold llvm::Value*s.
1345  typedef typename Traits::ValueTy ValueTy;
1346  /// Type used to hold RValues.
1347  typedef typename Traits::RValueTy RValueTy;
1348  struct PlacementArg {
1349  RValueTy ArgValue;
1350  QualType ArgType;
1351  };
1352 
1353  unsigned NumPlacementArgs : 31;
1354  unsigned PassAlignmentToPlacementDelete : 1;
1355  const FunctionDecl *OperatorDelete;
1356  ValueTy Ptr;
1357  ValueTy AllocSize;
1358  CharUnits AllocAlign;
1359 
1360  PlacementArg *getPlacementArgs() {
1361  return reinterpret_cast<PlacementArg *>(this + 1);
1362  }
1363 
1364  public:
1365  static size_t getExtraSize(size_t NumPlacementArgs) {
1366  return NumPlacementArgs * sizeof(PlacementArg);
1367  }
1368 
1369  CallDeleteDuringNew(size_t NumPlacementArgs,
1370  const FunctionDecl *OperatorDelete, ValueTy Ptr,
1371  ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1372  CharUnits AllocAlign)
1373  : NumPlacementArgs(NumPlacementArgs),
1374  PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1375  OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1376  AllocAlign(AllocAlign) {}
1377 
1378  void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1379  assert(I < NumPlacementArgs && "index out of range");
1380  getPlacementArgs()[I] = {Arg, Type};
1381  }
1382 
1383  void Emit(CodeGenFunction &CGF, Flags flags) override {
1384  const FunctionProtoType *FPT =
1385  OperatorDelete->getType()->getAs<FunctionProtoType>();
1386  CallArgList DeleteArgs;
1387 
1388  // The first argument is always a void*.
1389  DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1390 
1391  // Figure out what other parameters we should be implicitly passing.
1392  bool PassSize = false;
1393  bool PassAlignment = false;
1394  if (NumPlacementArgs) {
1395  // A placement deallocation function is implicitly passed an alignment
1396  // if the placement allocation function was, but is never passed a size.
1397  PassAlignment = PassAlignmentToPlacementDelete;
1398  } else {
1399  // For a non-placement new-expression, 'operator delete' can take a
1400  // size and/or an alignment if it has the right parameters.
1401  std::tie(PassSize, PassAlignment) =
1403  }
1404 
1405  // The second argument can be a std::size_t (for non-placement delete).
1406  if (PassSize)
1407  DeleteArgs.add(Traits::get(CGF, AllocSize),
1408  CGF.getContext().getSizeType());
1409 
1410  // The next (second or third) argument can be a std::align_val_t, which
1411  // is an enum whose underlying type is std::size_t.
1412  // FIXME: Use the right type as the parameter type. Note that in a call
1413  // to operator delete(size_t, ...), we may not have it available.
1414  if (PassAlignment)
1415  DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1416  CGF.SizeTy, AllocAlign.getQuantity())),
1417  CGF.getContext().getSizeType());
1418 
1419  // Pass the rest of the arguments, which must match exactly.
1420  for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1421  auto Arg = getPlacementArgs()[I];
1422  DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1423  }
1424 
1425  // Call 'operator delete'.
1426  EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1427  }
1428  };
1429 }
1430 
1431 /// Enter a cleanup to call 'operator delete' if the initializer in a
1432 /// new-expression throws.
1434  const CXXNewExpr *E,
1435  Address NewPtr,
1436  llvm::Value *AllocSize,
1437  CharUnits AllocAlign,
1438  const CallArgList &NewArgs) {
1439  unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1440 
1441  // If we're not inside a conditional branch, then the cleanup will
1442  // dominate and we can do the easier (and more efficient) thing.
1443  if (!CGF.isInConditionalBranch()) {
1444  struct DirectCleanupTraits {
1445  typedef llvm::Value *ValueTy;
1446  typedef RValue RValueTy;
1447  static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1448  static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1449  };
1450 
1451  typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1452 
1453  DirectCleanup *Cleanup = CGF.EHStack
1454  .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1455  E->getNumPlacementArgs(),
1456  E->getOperatorDelete(),
1457  NewPtr.getPointer(),
1458  AllocSize,
1459  E->passAlignment(),
1460  AllocAlign);
1461  for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1462  auto &Arg = NewArgs[I + NumNonPlacementArgs];
1463  Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1464  }
1465 
1466  return;
1467  }
1468 
1469  // Otherwise, we need to save all this stuff.
1472  DominatingValue<RValue>::saved_type SavedAllocSize =
1473  DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1474 
1475  struct ConditionalCleanupTraits {
1476  typedef DominatingValue<RValue>::saved_type ValueTy;
1477  typedef DominatingValue<RValue>::saved_type RValueTy;
1478  static RValue get(CodeGenFunction &CGF, ValueTy V) {
1479  return V.restore(CGF);
1480  }
1481  };
1482  typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1483 
1484  ConditionalCleanup *Cleanup = CGF.EHStack
1485  .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1486  E->getNumPlacementArgs(),
1487  E->getOperatorDelete(),
1488  SavedNewPtr,
1489  SavedAllocSize,
1490  E->passAlignment(),
1491  AllocAlign);
1492  for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1493  auto &Arg = NewArgs[I + NumNonPlacementArgs];
1494  Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1495  Arg.Ty);
1496  }
1497 
1498  CGF.initFullExprCleanup();
1499 }
1500 
1502  // The element type being allocated.
1504 
1505  // 1. Build a call to the allocation function.
1506  FunctionDecl *allocator = E->getOperatorNew();
1507 
1508  // If there is a brace-initializer, cannot allocate fewer elements than inits.
1509  unsigned minElements = 0;
1510  if (E->isArray() && E->hasInitializer()) {
1511  const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1512  if (ILE && ILE->isStringLiteralInit())
1513  minElements =
1514  cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1515  ->getSize().getZExtValue();
1516  else if (ILE)
1517  minElements = ILE->getNumInits();
1518  }
1519 
1520  llvm::Value *numElements = nullptr;
1521  llvm::Value *allocSizeWithoutCookie = nullptr;
1522  llvm::Value *allocSize =
1523  EmitCXXNewAllocSize(*this, E, minElements, numElements,
1524  allocSizeWithoutCookie);
1525  CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
1526 
1527  // Emit the allocation call. If the allocator is a global placement
1528  // operator, just "inline" it directly.
1529  Address allocation = Address::invalid();
1530  CallArgList allocatorArgs;
1531  if (allocator->isReservedGlobalPlacementOperator()) {
1532  assert(E->getNumPlacementArgs() == 1);
1533  const Expr *arg = *E->placement_arguments().begin();
1534 
1535  LValueBaseInfo BaseInfo;
1536  allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1537 
1538  // The pointer expression will, in many cases, be an opaque void*.
1539  // In these cases, discard the computed alignment and use the
1540  // formal alignment of the allocated type.
1541  if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1542  allocation = Address(allocation.getPointer(), allocAlign);
1543 
1544  // Set up allocatorArgs for the call to operator delete if it's not
1545  // the reserved global operator.
1546  if (E->getOperatorDelete() &&
1548  allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1549  allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1550  }
1551 
1552  } else {
1553  const FunctionProtoType *allocatorType =
1554  allocator->getType()->castAs<FunctionProtoType>();
1555  unsigned ParamsToSkip = 0;
1556 
1557  // The allocation size is the first argument.
1558  QualType sizeType = getContext().getSizeType();
1559  allocatorArgs.add(RValue::get(allocSize), sizeType);
1560  ++ParamsToSkip;
1561 
1562  if (allocSize != allocSizeWithoutCookie) {
1563  CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1564  allocAlign = std::max(allocAlign, cookieAlign);
1565  }
1566 
1567  // The allocation alignment may be passed as the second argument.
1568  if (E->passAlignment()) {
1569  QualType AlignValT = sizeType;
1570  if (allocatorType->getNumParams() > 1) {
1571  AlignValT = allocatorType->getParamType(1);
1572  assert(getContext().hasSameUnqualifiedType(
1573  AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1574  sizeType) &&
1575  "wrong type for alignment parameter");
1576  ++ParamsToSkip;
1577  } else {
1578  // Corner case, passing alignment to 'operator new(size_t, ...)'.
1579  assert(allocator->isVariadic() && "can't pass alignment to allocator");
1580  }
1581  allocatorArgs.add(
1582  RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1583  AlignValT);
1584  }
1585 
1586  // FIXME: Why do we not pass a CalleeDecl here?
1587  EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1588  /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1589 
1590  RValue RV =
1591  EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1592 
1593  // If this was a call to a global replaceable allocation function that does
1594  // not take an alignment argument, the allocator is known to produce
1595  // storage that's suitably aligned for any object that fits, up to a known
1596  // threshold. Otherwise assume it's suitably aligned for the allocated type.
1597  CharUnits allocationAlign = allocAlign;
1598  if (!E->passAlignment() &&
1600  unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1601  Target.getNewAlign(), getContext().getTypeSize(allocType)));
1602  allocationAlign = std::max(
1603  allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1604  }
1605 
1606  allocation = Address(RV.getScalarVal(), allocationAlign);
1607  }
1608 
1609  // Emit a null check on the allocation result if the allocation
1610  // function is allowed to return null (because it has a non-throwing
1611  // exception spec or is the reserved placement new) and we have an
1612  // interesting initializer.
1613  bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
1614  (!allocType.isPODType(getContext()) || E->hasInitializer());
1615 
1616  llvm::BasicBlock *nullCheckBB = nullptr;
1617  llvm::BasicBlock *contBB = nullptr;
1618 
1619  // The null-check means that the initializer is conditionally
1620  // evaluated.
1621  ConditionalEvaluation conditional(*this);
1622 
1623  if (nullCheck) {
1624  conditional.begin(*this);
1625 
1626  nullCheckBB = Builder.GetInsertBlock();
1627  llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1628  contBB = createBasicBlock("new.cont");
1629 
1630  llvm::Value *isNull =
1631  Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1632  Builder.CreateCondBr(isNull, contBB, notNullBB);
1633  EmitBlock(notNullBB);
1634  }
1635 
1636  // If there's an operator delete, enter a cleanup to call it if an
1637  // exception is thrown.
1638  EHScopeStack::stable_iterator operatorDeleteCleanup;
1639  llvm::Instruction *cleanupDominator = nullptr;
1640  if (E->getOperatorDelete() &&
1642  EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1643  allocatorArgs);
1644  operatorDeleteCleanup = EHStack.stable_begin();
1645  cleanupDominator = Builder.CreateUnreachable();
1646  }
1647 
1648  assert((allocSize == allocSizeWithoutCookie) ==
1649  CalculateCookiePadding(*this, E).isZero());
1650  if (allocSize != allocSizeWithoutCookie) {
1651  assert(E->isArray());
1652  allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1653  numElements,
1654  E, allocType);
1655  }
1656 
1657  llvm::Type *elementTy = ConvertTypeForMem(allocType);
1658  Address result = Builder.CreateElementBitCast(allocation, elementTy);
1659 
1660  // Passing pointer through invariant.group.barrier to avoid propagation of
1661  // vptrs information which may be included in previous type.
1662  // To not break LTO with different optimizations levels, we do it regardless
1663  // of optimization level.
1664  if (CGM.getCodeGenOpts().StrictVTablePointers &&
1665  allocator->isReservedGlobalPlacementOperator())
1666  result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1667  result.getAlignment());
1668 
1669  EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1670  allocSizeWithoutCookie);
1671  if (E->isArray()) {
1672  // NewPtr is a pointer to the base element type. If we're
1673  // allocating an array of arrays, we'll need to cast back to the
1674  // array pointer type.
1675  llvm::Type *resultType = ConvertTypeForMem(E->getType());
1676  if (result.getType() != resultType)
1677  result = Builder.CreateBitCast(result, resultType);
1678  }
1679 
1680  // Deactivate the 'operator delete' cleanup if we finished
1681  // initialization.
1682  if (operatorDeleteCleanup.isValid()) {
1683  DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1684  cleanupDominator->eraseFromParent();
1685  }
1686 
1687  llvm::Value *resultPtr = result.getPointer();
1688  if (nullCheck) {
1689  conditional.end(*this);
1690 
1691  llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1692  EmitBlock(contBB);
1693 
1694  llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1695  PHI->addIncoming(resultPtr, notNullBB);
1696  PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1697  nullCheckBB);
1698 
1699  resultPtr = PHI;
1700  }
1701 
1702  return resultPtr;
1703 }
1704 
1706  llvm::Value *Ptr, QualType DeleteTy,
1707  llvm::Value *NumElements,
1708  CharUnits CookieSize) {
1709  assert((!NumElements && CookieSize.isZero()) ||
1710  DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1711 
1712  const FunctionProtoType *DeleteFTy =
1713  DeleteFD->getType()->getAs<FunctionProtoType>();
1714 
1715  CallArgList DeleteArgs;
1716 
1717  std::pair<bool, bool> PassSizeAndAlign =
1719 
1720  auto ParamTypeIt = DeleteFTy->param_type_begin();
1721 
1722  // Pass the pointer itself.
1723  QualType ArgTy = *ParamTypeIt++;
1724  llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1725  DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1726 
1727  // Pass the size if the delete function has a size_t parameter.
1728  if (PassSizeAndAlign.first) {
1729  QualType SizeType = *ParamTypeIt++;
1730  CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1731  llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1732  DeleteTypeSize.getQuantity());
1733 
1734  // For array new, multiply by the number of elements.
1735  if (NumElements)
1736  Size = Builder.CreateMul(Size, NumElements);
1737 
1738  // If there is a cookie, add the cookie size.
1739  if (!CookieSize.isZero())
1740  Size = Builder.CreateAdd(
1741  Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1742 
1743  DeleteArgs.add(RValue::get(Size), SizeType);
1744  }
1745 
1746  // Pass the alignment if the delete function has an align_val_t parameter.
1747  if (PassSizeAndAlign.second) {
1748  QualType AlignValType = *ParamTypeIt++;
1749  CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1750  getContext().getTypeAlignIfKnown(DeleteTy));
1751  llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1752  DeleteTypeAlign.getQuantity());
1753  DeleteArgs.add(RValue::get(Align), AlignValType);
1754  }
1755 
1756  assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1757  "unknown parameter to usual delete function");
1758 
1759  // Emit the call to delete.
1760  EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1761 }
1762 
1763 namespace {
1764  /// Calls the given 'operator delete' on a single object.
1765  struct CallObjectDelete final : EHScopeStack::Cleanup {
1766  llvm::Value *Ptr;
1767  const FunctionDecl *OperatorDelete;
1768  QualType ElementType;
1769 
1770  CallObjectDelete(llvm::Value *Ptr,
1771  const FunctionDecl *OperatorDelete,
1772  QualType ElementType)
1773  : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1774 
1775  void Emit(CodeGenFunction &CGF, Flags flags) override {
1776  CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1777  }
1778  };
1779 }
1780 
1781 void
1783  llvm::Value *CompletePtr,
1784  QualType ElementType) {
1785  EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1786  OperatorDelete, ElementType);
1787 }
1788 
1789 /// Emit the code for deleting a single object.
1791  const CXXDeleteExpr *DE,
1792  Address Ptr,
1793  QualType ElementType) {
1794  // C++11 [expr.delete]p3:
1795  // If the static type of the object to be deleted is different from its
1796  // dynamic type, the static type shall be a base class of the dynamic type
1797  // of the object to be deleted and the static type shall have a virtual
1798  // destructor or the behavior is undefined.
1800  DE->getExprLoc(), Ptr.getPointer(),
1801  ElementType);
1802 
1803  // Find the destructor for the type, if applicable. If the
1804  // destructor is virtual, we'll just emit the vcall and return.
1805  const CXXDestructorDecl *Dtor = nullptr;
1806  if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1807  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1808  if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1809  Dtor = RD->getDestructor();
1810 
1811  if (Dtor->isVirtual()) {
1812  CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1813  Dtor);
1814  return;
1815  }
1816  }
1817  }
1818 
1819  // Make sure that we call delete even if the dtor throws.
1820  // This doesn't have to a conditional cleanup because we're going
1821  // to pop it off in a second.
1822  const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1823  CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1824  Ptr.getPointer(),
1825  OperatorDelete, ElementType);
1826 
1827  if (Dtor)
1829  /*ForVirtualBase=*/false,
1830  /*Delegating=*/false,
1831  Ptr);
1832  else if (auto Lifetime = ElementType.getObjCLifetime()) {
1833  switch (Lifetime) {
1834  case Qualifiers::OCL_None:
1837  break;
1838 
1841  break;
1842 
1843  case Qualifiers::OCL_Weak:
1844  CGF.EmitARCDestroyWeak(Ptr);
1845  break;
1846  }
1847  }
1848 
1849  CGF.PopCleanupBlock();
1850 }
1851 
1852 namespace {
1853  /// Calls the given 'operator delete' on an array of objects.
1854  struct CallArrayDelete final : EHScopeStack::Cleanup {
1855  llvm::Value *Ptr;
1856  const FunctionDecl *OperatorDelete;
1857  llvm::Value *NumElements;
1858  QualType ElementType;
1859  CharUnits CookieSize;
1860 
1861  CallArrayDelete(llvm::Value *Ptr,
1862  const FunctionDecl *OperatorDelete,
1863  llvm::Value *NumElements,
1864  QualType ElementType,
1865  CharUnits CookieSize)
1866  : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1867  ElementType(ElementType), CookieSize(CookieSize) {}
1868 
1869  void Emit(CodeGenFunction &CGF, Flags flags) override {
1870  CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1871  CookieSize);
1872  }
1873  };
1874 }
1875 
1876 /// Emit the code for deleting an array of objects.
1878  const CXXDeleteExpr *E,
1879  Address deletedPtr,
1880  QualType elementType) {
1881  llvm::Value *numElements = nullptr;
1882  llvm::Value *allocatedPtr = nullptr;
1883  CharUnits cookieSize;
1884  CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1885  numElements, allocatedPtr, cookieSize);
1886 
1887  assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1888 
1889  // Make sure that we call delete even if one of the dtors throws.
1890  const FunctionDecl *operatorDelete = E->getOperatorDelete();
1891  CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1892  allocatedPtr, operatorDelete,
1893  numElements, elementType,
1894  cookieSize);
1895 
1896  // Destroy the elements.
1897  if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1898  assert(numElements && "no element count for a type with a destructor!");
1899 
1900  CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1901  CharUnits elementAlign =
1902  deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1903 
1904  llvm::Value *arrayBegin = deletedPtr.getPointer();
1905  llvm::Value *arrayEnd =
1906  CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1907 
1908  // Note that it is legal to allocate a zero-length array, and we
1909  // can never fold the check away because the length should always
1910  // come from a cookie.
1911  CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1912  CGF.getDestroyer(dtorKind),
1913  /*checkZeroLength*/ true,
1914  CGF.needsEHCleanup(dtorKind));
1915  }
1916 
1917  // Pop the cleanup block.
1918  CGF.PopCleanupBlock();
1919 }
1920 
1922  const Expr *Arg = E->getArgument();
1923  Address Ptr = EmitPointerWithAlignment(Arg);
1924 
1925  // Null check the pointer.
1926  llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1927  llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1928 
1929  llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
1930 
1931  Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1932  EmitBlock(DeleteNotNull);
1933 
1934  // We might be deleting a pointer to array. If so, GEP down to the
1935  // first non-array element.
1936  // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1937  QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1938  if (DeleteTy->isConstantArrayType()) {
1939  llvm::Value *Zero = Builder.getInt32(0);
1941 
1942  GEP.push_back(Zero); // point at the outermost array
1943 
1944  // For each layer of array type we're pointing at:
1945  while (const ConstantArrayType *Arr
1946  = getContext().getAsConstantArrayType(DeleteTy)) {
1947  // 1. Unpeel the array type.
1948  DeleteTy = Arr->getElementType();
1949 
1950  // 2. GEP to the first element of the array.
1951  GEP.push_back(Zero);
1952  }
1953 
1954  Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
1955  Ptr.getAlignment());
1956  }
1957 
1958  assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
1959 
1960  if (E->isArrayForm()) {
1961  EmitArrayDelete(*this, E, Ptr, DeleteTy);
1962  } else {
1963  EmitObjectDelete(*this, E, Ptr, DeleteTy);
1964  }
1965 
1966  EmitBlock(DeleteEnd);
1967 }
1968 
1969 static bool isGLValueFromPointerDeref(const Expr *E) {
1970  E = E->IgnoreParens();
1971 
1972  if (const auto *CE = dyn_cast<CastExpr>(E)) {
1973  if (!CE->getSubExpr()->isGLValue())
1974  return false;
1975  return isGLValueFromPointerDeref(CE->getSubExpr());
1976  }
1977 
1978  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1979  return isGLValueFromPointerDeref(OVE->getSourceExpr());
1980 
1981  if (const auto *BO = dyn_cast<BinaryOperator>(E))
1982  if (BO->getOpcode() == BO_Comma)
1983  return isGLValueFromPointerDeref(BO->getRHS());
1984 
1985  if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1986  return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1987  isGLValueFromPointerDeref(ACO->getFalseExpr());
1988 
1989  // C++11 [expr.sub]p1:
1990  // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1991  if (isa<ArraySubscriptExpr>(E))
1992  return true;
1993 
1994  if (const auto *UO = dyn_cast<UnaryOperator>(E))
1995  if (UO->getOpcode() == UO_Deref)
1996  return true;
1997 
1998  return false;
1999 }
2000 
2002  llvm::Type *StdTypeInfoPtrTy) {
2003  // Get the vtable pointer.
2004  Address ThisPtr = CGF.EmitLValue(E).getAddress();
2005 
2006  // C++ [expr.typeid]p2:
2007  // If the glvalue expression is obtained by applying the unary * operator to
2008  // a pointer and the pointer is a null pointer value, the typeid expression
2009  // throws the std::bad_typeid exception.
2010  //
2011  // However, this paragraph's intent is not clear. We choose a very generous
2012  // interpretation which implores us to consider comma operators, conditional
2013  // operators, parentheses and other such constructs.
2014  QualType SrcRecordTy = E->getType();
2016  isGLValueFromPointerDeref(E), SrcRecordTy)) {
2017  llvm::BasicBlock *BadTypeidBlock =
2018  CGF.createBasicBlock("typeid.bad_typeid");
2019  llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2020 
2021  llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2022  CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2023 
2024  CGF.EmitBlock(BadTypeidBlock);
2025  CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2026  CGF.EmitBlock(EndBlock);
2027  }
2028 
2029  return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2030  StdTypeInfoPtrTy);
2031 }
2032 
2034  llvm::Type *StdTypeInfoPtrTy =
2035  ConvertType(E->getType())->getPointerTo();
2036 
2037  if (E->isTypeOperand()) {
2038  llvm::Constant *TypeInfo =
2040  return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2041  }
2042 
2043  // C++ [expr.typeid]p2:
2044  // When typeid is applied to a glvalue expression whose type is a
2045  // polymorphic class type, the result refers to a std::type_info object
2046  // representing the type of the most derived object (that is, the dynamic
2047  // type) to which the glvalue refers.
2048  if (E->isPotentiallyEvaluated())
2049  return EmitTypeidFromVTable(*this, E->getExprOperand(),
2050  StdTypeInfoPtrTy);
2051 
2052  QualType OperandTy = E->getExprOperand()->getType();
2054  StdTypeInfoPtrTy);
2055 }
2056 
2058  QualType DestTy) {
2059  llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2060  if (DestTy->isPointerType())
2061  return llvm::Constant::getNullValue(DestLTy);
2062 
2063  /// C++ [expr.dynamic.cast]p9:
2064  /// A failed cast to reference type throws std::bad_cast
2065  if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2066  return nullptr;
2067 
2068  CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2069  return llvm::UndefValue::get(DestLTy);
2070 }
2071 
2073  const CXXDynamicCastExpr *DCE) {
2074  CGM.EmitExplicitCastExprType(DCE, this);
2075  QualType DestTy = DCE->getTypeAsWritten();
2076 
2077  if (DCE->isAlwaysNull())
2078  if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2079  return T;
2080 
2081  QualType SrcTy = DCE->getSubExpr()->getType();
2082 
2083  // C++ [expr.dynamic.cast]p7:
2084  // If T is "pointer to cv void," then the result is a pointer to the most
2085  // derived object pointed to by v.
2086  const PointerType *DestPTy = DestTy->getAs<PointerType>();
2087 
2088  bool isDynamicCastToVoid;
2089  QualType SrcRecordTy;
2090  QualType DestRecordTy;
2091  if (DestPTy) {
2092  isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2093  SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2094  DestRecordTy = DestPTy->getPointeeType();
2095  } else {
2096  isDynamicCastToVoid = false;
2097  SrcRecordTy = SrcTy;
2098  DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2099  }
2100 
2101  assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2102 
2103  // C++ [expr.dynamic.cast]p4:
2104  // If the value of v is a null pointer value in the pointer case, the result
2105  // is the null pointer value of type T.
2106  bool ShouldNullCheckSrcValue =
2108  SrcRecordTy);
2109 
2110  llvm::BasicBlock *CastNull = nullptr;
2111  llvm::BasicBlock *CastNotNull = nullptr;
2112  llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2113 
2114  if (ShouldNullCheckSrcValue) {
2115  CastNull = createBasicBlock("dynamic_cast.null");
2116  CastNotNull = createBasicBlock("dynamic_cast.notnull");
2117 
2118  llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2119  Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2120  EmitBlock(CastNotNull);
2121  }
2122 
2123  llvm::Value *Value;
2124  if (isDynamicCastToVoid) {
2125  Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2126  DestTy);
2127  } else {
2128  assert(DestRecordTy->isRecordType() &&
2129  "destination type must be a record type!");
2130  Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2131  DestTy, DestRecordTy, CastEnd);
2132  CastNotNull = Builder.GetInsertBlock();
2133  }
2134 
2135  if (ShouldNullCheckSrcValue) {
2136  EmitBranch(CastEnd);
2137 
2138  EmitBlock(CastNull);
2139  EmitBranch(CastEnd);
2140  }
2141 
2142  EmitBlock(CastEnd);
2143 
2144  if (ShouldNullCheckSrcValue) {
2145  llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2146  PHI->addIncoming(Value, CastNotNull);
2147  PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2148 
2149  Value = PHI;
2150  }
2151 
2152  return Value;
2153 }
2154 
2156  RunCleanupsScope Scope(*this);
2157  LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
2158 
2161  e = E->capture_init_end();
2162  i != e; ++i, ++CurField) {
2163  // Emit initialization
2164  LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2165  if (CurField->hasCapturedVLAType()) {
2166  auto VAT = CurField->getCapturedVLAType();
2167  EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2168  } else {
2169  EmitInitializerForField(*CurField, LV, *i);
2170  }
2171  }
2172 }
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:52
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2474
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:281
virtual llvm::Value * EmitVirtualDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType, Address This, const CXXMemberCallExpr *CE)=0
Emit the ABI-specific virtual destructor call.
bool isNegative() const
isNegative - Test whether the quantity is less than zero.
Definition: CharUnits.h:125
unsigned getNumInits() const
Definition: Expr.h:3878
virtual void EmitBadTypeidCall(CodeGenFunction &CGF)=0
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty)
BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making indirect call to virtual...
Definition: CGCXX.cpp:292
Complete object ctor.
Definition: ABI.h:26
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2224
llvm::iterator_range< arg_iterator > placement_arguments()
Definition: ExprCXX.h:1938
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:1451
A (possibly-)qualified type.
Definition: Type.h:616
bool isConstantArrayType() const
Definition: Type.h:5754
static RValue EmitNewDeleteCall(CodeGenFunction &CGF, const FunctionDecl *CalleeDecl, const FunctionProtoType *CalleeType, const CallArgList &Args)
Emit a call to an operator new or operator delete function, as implicitly created by new-expressions ...
Definition: CGExprCXX.cpp:1262
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2005
llvm::Type * ConvertTypeForMem(QualType T)
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2275
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1350
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1054
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:64
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1246
llvm::Module & getModule() const
void EmitARCDestroyWeak(Address addr)
void @objc_destroyWeak(i8** addr) Essentially objc_storeWeak(addr, nil).
Definition: CGObjC.cpp:2298
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:119
Stmt - This represents one statement.
Definition: Stmt.h:60
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
virtual Address adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD, Address This, bool VirtualCall)
Perform ABI-specific "this" argument adjustment required prior to a call of a virtual function...
Definition: CGCXXABI.h:337
void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, llvm::Type *ElementTy, Address NewPtr, llvm::Value *NumElements, llvm::Value *AllocSizeWithoutCookie)
Definition: CGExprCXX.cpp:947
llvm::ConstantInt * getSize(CharUnits N)
Definition: CGBuilder.h:61
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
virtual bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy)=0
Checking the 'this' pointer for a constructor call.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name...
Definition: Expr.h:2503
bool isRecordType() const
Definition: Type.h:5769
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
Address getAddress() const
Definition: CGValue.h:346
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, QualType Type, CharUnits Alignment=CharUnits::Zero(), SanitizerSet SkippedChecks=SanitizerSet())
Emit a check that V is the address of storage of the appropriate size and alignment for an object of ...
Definition: CGExpr.cpp:578
virtual bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr, QualType SrcRecordTy)=0
bool hasDefinition() const
Definition: DeclCXX.h:702
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition: StoreRef.h:26
QualType getPointeeType() const
Definition: Type.h:2461
The base class of the type hierarchy.
Definition: Type.h:1303
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition: CGExpr.cpp:1749
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
QualType getRecordType(const RecordDecl *Decl) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2497
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1177
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:166
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
const LangOptions & getLangOpts() const
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference...
Definition: CGExpr.cpp:3739
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2329
Expr * ignoreParenBaseCasts() LLVM_READONLY
Ignore parentheses and derived-to-base casts.
Definition: Expr.cpp:2469
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:1772
static llvm::Value * EmitCXXNewAllocSize(CodeGenFunction &CGF, const CXXNewExpr *e, unsigned minElements, llvm::Value *&numElements, llvm::Value *&sizeWithoutCookie)
Definition: CGExprCXX.cpp:660
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition: ExprCXX.h:1646
static saved_type save(CodeGenFunction &CGF, type value)
Definition: EHScopeStack.h:60
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:52
const Expr * getCallee() const
Definition: Expr.h:2246
static std::pair< bool, bool > shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT)
Definition: CGExprCXX.cpp:1314
T * pushCleanupWithExtra(CleanupKind Kind, size_t N, As...A)
Push a cleanup with non-constant storage requirements on the stack.
Definition: EHScopeStack.h:305
field_iterator field_begin() const
Definition: Decl.cpp:3912
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1924
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition: CGBuilder.h:227
const CGFunctionInfo & arrangeCXXStructorDeclaration(const CXXMethodDecl *MD, StructorType Type)
Definition: CGCall.cpp:288
static MemberCallInfo commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args, CallArgList *RtlArgs)
Definition: CGExprCXX.cpp:36
IsZeroed_t isZeroed() const
Definition: CGValue.h:602
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:460
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:2920
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:1793
RValue EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, const CGCallee &Callee, ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *E, CallArgList *RtlArgs)
Definition: CGExprCXX.cpp:80
bool isVoidType() const
Definition: Type.h:5906
The collection of all-type qualifiers we support.
Definition: Type.h:118
unsigned getNumParams() const
Definition: Type.h:3338
An object to manage conditionally-evaluated expressions.
llvm::Value * EmitCXXNewExpr(const CXXNewExpr *E)
Definition: CGExprCXX.cpp:1501
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1225
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
Definition: CGExprCXX.cpp:2072
void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, Address This, Address Src, const CXXConstructExpr *E)
Definition: CGClass.cpp:2201
llvm::Constant * getAddrOfCXXStructor(const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
Definition: CGCXX.cpp:240
QualType getReturnType() const
Definition: Decl.h:2106
static llvm::Value * EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, llvm::Type *StdTypeInfoPtrTy)
Definition: CGExprCXX.cpp:2001
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr...
Definition: ExprCXX.cpp:44
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
A metaprogramming class for ensuring that a value will dominate an arbitrary position in a function...
Definition: EHScopeStack.h:66
Expr * getSubExpr()
Definition: Expr.h:2753
bool hasStrongOrWeakObjCLifetime() const
Definition: Type.h:1036
void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, Address This, const CXXConstructExpr *E)
Definition: CGClass.cpp:1947
Expr * getLHS() const
Definition: Expr.h:3011
void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init)
Definition: CGClass.cpp:655
virtual RValue EmitCUDAKernelCallExpr(CodeGenFunction &CGF, const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue)
Describes an C or C++ initializer list.
Definition: Expr.h:3848
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:590
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
pushRegularPartialArrayCleanup - Push an EH cleanup to destroy already-constructed elements of the gi...
Definition: CGDecl.cpp:1721
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
Expr * getArraySize()
Definition: ExprCXX.h:1873
bool isAlwaysNull() const
isAlwaysNull - Return whether the result of the dynamic_cast is proven to always be null...
Definition: ExprCXX.cpp:584
Base object ctor.
Definition: ABI.h:27
Address CreateElementBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Cast the element type of the given address to a different type, preserving information like the align...
Definition: CGBuilder.h:150
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise)
Destroy a __strong variable.
Definition: CGObjC.cpp:2122
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2018
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with '::operator new(size_t)' is g...
Definition: TargetInfo.h:382
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:1914
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition: ExprCXX.h:1660
Expr * getInitializer()
The initializer of this new-expression.
Definition: ExprCXX.h:1910
Expr * getExprOperand() const
Definition: ExprCXX.h:645
virtual llvm::Value * EmitDynamicCastCall(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd)=0
virtual llvm::Value * EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value, QualType SrcRecordTy, QualType DestTy)=0
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2967
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind...
RecordDecl * getDecl() const
Definition: Type.h:3793
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:252
void EmitAggregateAssign(Address DestPtr, Address SrcPtr, QualType EltTy)
EmitAggregateCopy - Emit an aggregate assignment.
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2555
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:2893
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, QualType AllocType, Address NewPtr)
Definition: CGExprCXX.cpp:922
void initFullExprCleanup()
Set up the last cleaup that was pushed as a conditional full-expression cleanup.
Definition: CGCleanup.cpp:284
void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, QualType DeleteTy, llvm::Value *NumElements=nullptr, CharUnits CookieSize=CharUnits())
Definition: CGExprCXX.cpp:1705
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition: CGExpr.cpp:157
static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, Address DestPtr, const CXXRecordDecl *Base)
Definition: CGExprCXX.cpp:465
AlignmentSource getAlignmentSource() const
Definition: CGValue.h:157
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1519
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
Definition: CGCall.cpp:263
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:90
bool isArrow() const
Determine whether this pseudo-destructor expression was written using an '->' (otherwise, it used a '.
Definition: ExprCXX.h:2177
bool isValid() const
Definition: Address.h:36
detail::InMemoryDirectory::const_iterator I
QualType getType() const
Definition: Decl.h:589
CXXMethodDecl * getCorrespondingMethodInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find the method in RD that corresponds to this one.
Definition: DeclCXX.cpp:1576
This object can be modified without requiring retains or releases.
Definition: Type.h:139
arg_iterator arg_end()
Definition: Expr.h:2306
Checking the 'this' pointer for a call to a non-static member function.
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6091
EnumDecl * getDecl() const
Definition: Type.h:3816
bool isUnion() const
Definition: Decl.h:3028
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2037
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
Definition: CGExprCXX.cpp:553
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2113
void addFrom(const CallArgList &other)
Add all the arguments from another CallArgList to this one.
Definition: CGCall.h:214
QualType getParamType(unsigned i) const
Definition: Type.h:3339
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3129
virtual CharUnits GetArrayCookieSize(const CXXNewExpr *expr)
Returns the extra size required in order to store the array cookie for the given new-expression.
Definition: CGCXXABI.cpp:165
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1028
param_type_iterator param_type_begin() const
Definition: Type.h:3468
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:38
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:1869
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:414
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called...
Definition: ExprCXX.h:1267
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1760
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition: CGClass.cpp:2474
static TypeEvaluationKind getEvaluationKind(QualType T)
hasAggregateLLVMType - Return true if the specified AST type will map into an aggregate LLVM type or ...
llvm::Value * getPointer() const
Definition: Address.h:38
Expr - This represents one expression.
Definition: Expr.h:105
static Address invalid()
Definition: Address.h:35
bool isInstance() const
Definition: DeclCXX.h:1930
static void EnterNewDeleteCleanup(CodeGenFunction &CGF, const CXXNewExpr *E, Address NewPtr, llvm::Value *AllocSize, CharUnits AllocAlign, const CallArgList &NewArgs)
Enter a cleanup to call 'operator delete' if the initializer in a new-expression throws.
Definition: CGExprCXX.cpp:1433
CGCXXABI & getCXXABI() const
virtual void ReadArrayCookie(CodeGenFunction &CGF, Address Ptr, const CXXDeleteExpr *expr, QualType ElementType, llvm::Value *&NumElements, llvm::Value *&AllocPtr, CharUnits &CookieSize)
Reads the array cookie associated with the given pointer, if it has one.
Definition: CGCXXABI.cpp:205
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
Definition: CGExprCXX.cpp:105
void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, llvm::Value *CompletePtr, QualType ElementType)
Definition: CGExprCXX.cpp:1782
void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
bool isVirtual() const
Definition: DeclCXX.h:1947
void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, const ArrayType *ArrayTy, Address ArrayPtr, const CXXConstructExpr *E, bool ZeroInitialization=false)
EmitCXXAggrConstructorCall - Emit a loop to call a particular constructor for each of several members...
Definition: CGClass.cpp:1818
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:125
SourceLocation getExprLoc() const LLVM_READONLY
Definition: ExprCXX.h:161
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2551
CharUnits getNonVirtualAlignment() const
getNonVirtualSize - Get the non-virtual alignment (in chars) of an object, which is the alignment of ...
Definition: RecordLayout.h:197
virtual bool EmitBadCastCall(CodeGenFunction &CGF)=0
ConstructionKind getConstructionKind() const
Determine whether this constructor is actually constructing a base class (rather than a complete obje...
Definition: ExprCXX.h:1274
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:207
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:379
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
A class for recording the number of arguments that a function signature requires. ...
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2684
bool shouldNullCheckAllocation(const ASTContext &Ctx) const
True if the allocation result needs to be null-checked.
Definition: ExprCXX.cpp:154
QualType getAllocatedType() const
Definition: ExprCXX.h:1841
void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest)
Definition: CGExprCXX.cpp:2155
RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, const Expr *Base)
Definition: CGExprCXX.cpp:192
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition: CGExpr.cpp:896
static void EmitObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType)
Emit the code for deleting a single object.
Definition: CGExprCXX.cpp:1790
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:274
llvm::Value * EmitCastToVoidPtr(llvm::Value *value)
Emit a cast to void* in the appropriate address space.
Definition: CGExpr.cpp:49
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, QualType elementType, CharUnits elementAlign, Destroyer *destroyer, bool checkZeroLength, bool useEHCleanup)
emitArrayDestroy - Destroys all the elements of the given array, beginning from last to first...
Definition: CGDecl.cpp:1566
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
forAddr - Make a slot for an aggregate value.
Definition: CGValue.h:517
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:29
The l-value was considered opaque, so the alignment was determined from a type.
Expr * getArgument()
Definition: ExprCXX.h:2039
bool isArray() const
Definition: ExprCXX.h:1872
bool isArrayForm() const
Definition: ExprCXX.h:2026
There is no lifetime qualification on this type.
Definition: Type.h:135
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:305
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:59
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:146
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:3959
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
Definition: CGExprCXX.cpp:2033
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
Try to emit the given expression as a constant; returns 0 if the expression cannot be emitted as a co...
ASTContext & getContext() const
Encodes a location in the source.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3810
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Release the given object.
Definition: CGObjC.cpp:2090
virtual llvm::Value * EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy, Address ThisPtr, llvm::Type *StdTypeInfoPtrTy)=0
A saved depth on the scope stack.
Definition: EHScopeStack.h:107
static CXXRecordDecl * getCXXRecord(const Expr *E)
Definition: CGExprCXX.cpp:156
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1780
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:136
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
Definition: CGCleanup.cpp:1230
An aggregate value slot.
Definition: CGValue.h:456
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:617
static void EmitArrayDelete(CodeGenFunction &CGF, const CXXDeleteExpr *E, Address deletedPtr, QualType elementType)
Emit the code for deleting an array of objects.
Definition: CGExprCXX.cpp:1877
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
const CXXRecordDecl * getBestDynamicClassType() const
For an expression of class type or pointer to class type, return the most derived class decl the expr...
Definition: Expr.cpp:63
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
llvm::Constant * EmitNullConstantForBase(const CXXRecordDecl *Record)
Return a null constant appropriate for zero-initializing a base class with the given type...
SanitizerSet SanOpts
Sanitizers enabled for this function.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2235
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
bool hasInitializer() const
Whether this new-expression has any initializer at all.
Definition: ExprCXX.h:1900
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition: CharUnits.h:197
const CodeGenOptions & getCodeGenOpts() const
arg_range arguments()
Definition: Expr.h:2300
virtual void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE, Address Ptr, QualType ElementType, const CXXDestructorDecl *Dtor)=0
An aligned address.
Definition: Address.h:25
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6105
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1507
All available information about a concrete callee.
Definition: CGCall.h:66
Complete object dtor.
Definition: ABI.h:36
RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:397
Assigning into this object requires a lifetime extension.
Definition: Type.h:152
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:5559
RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, const Expr *Arg, bool IsDelete)
Definition: CGExprCXX.cpp:1296
bool passAlignment() const
Indicates whether the required alignment should be implicitly passed to the allocation function...
Definition: ExprCXX.h:1924
bool isDynamicClass() const
Definition: DeclCXX.h:715
CXXCtorType
C++ constructor types.
Definition: ABI.h:25
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
QualType getPointeeType() const
Definition: Type.h:2238
virtual Address InitializeArrayCookie(CodeGenFunction &CGF, Address NewPtr, llvm::Value *NumElements, const CXXNewExpr *expr, QualType ElementType)
Initialize the array cookie for the given allocation.
Definition: CGCXXABI.cpp:176
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
! Language semantics require right-to-left evaluation.
bool isArrow() const
Definition: Expr.h:2573
QualType getType() const
Definition: Expr.h:127
static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, const CXXNewExpr *E)
Definition: CGExprCXX.cpp:647
CGFunctionInfo - Class to encapsulate the information about a function definition.
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:67
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This)
Definition: CGClass.cpp:2302
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition: ExprCXX.cpp:59
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:1992
StringRef Name
Definition: USRFinder.cpp:123
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1216
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1437
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:2126
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type...
Definition: Expr.cpp:2593
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
param_type_iterator param_type_end() const
Definition: Type.h:3471
unsigned getNumPlacementArgs() const
Definition: ExprCXX.h:1880
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2442
void EmitAggregateCopy(Address DestPtr, Address SrcPtr, QualType EltTy, bool isVolatile=false, bool isAssignment=false)
EmitAggregateCopy - Emit an aggregate copy.
Definition: CGExprAgg.cpp:1561
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2263
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:1557
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type. ...
Definition: CGExprAgg.cpp:1539
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition: CGExpr.cpp:880
static llvm::Value * EmitDynamicCastToNull(CodeGenFunction &CGF, QualType DestTy)
Definition: CGExprCXX.cpp:2057
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3784
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:1867
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:1634
QualType getCanonicalType() const
Definition: Type.h:5528
arg_iterator arg_begin()
Definition: Expr.h:2305
Represents a call to a CUDA kernel function.
Definition: ExprCXX.h:175
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3226
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1326
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:50
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition: CGDecl.cpp:705
Address getAddress() const
Definition: CGValue.h:577
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1303
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2360
void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp)
Definition: CGExprCXX.cpp:625
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1240
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:1909
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:436
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:189
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
static bool isGLValueFromPointerDeref(const Expr *E)
Definition: CGExprCXX.cpp:1969
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
Expr * getBase() const
Definition: Expr.h:2468
const Type * getClass() const
Definition: Type.h:2475
Reading or writing from this object requires a barrier call.
Definition: Type.h:149
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2378
Represents a C++ struct/union/class.
Definition: DeclCXX.h:267
virtual const CXXRecordDecl * getThisArgumentTypeForMethod(const CXXMethodDecl *MD)
Get the type of the implicit "this" parameter used by a method.
Definition: CGCXXABI.h:329
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block, taking care to avoid creation of branches from dummy blocks.
Definition: CGStmt.cpp:456
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset...
Definition: CharUnits.h:190
Opcode getOpcode() const
Definition: Expr.h:3008
static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, Address NewPtr, llvm::Value *NumElements, llvm::Value *AllocSizeWithoutCookie)
Definition: CGExprCXX.cpp:1248
llvm::Type * ConvertType(QualType T)
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:2488
LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo=LValueBaseInfo(AlignmentSource::Type))
void EmitCXXDeleteExpr(const CXXDeleteExpr *E)
Definition: CGExprCXX.cpp:1921
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1082
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:2661
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
virtual CGCallee EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E, Address This, llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr, const MemberPointerType *MPT)
Load a member function from an object and a member function pointer.
Definition: CGCXXABI.cpp:47
void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, CFITypeCheckKind TCK, SourceLocation Loc)
EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
Definition: CGClass.cpp:2544
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2206
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
Definition: CGExpr.cpp:1023
Expr * getRHS() const
Definition: Expr.h:3013
bool isStringLiteralInit() const
Definition: Expr.cpp:1865
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression...
Definition: ExprCXX.h:1672
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional, const FunctionDecl *FD)
Compute the arguments required by the given formal prototype, given that there may be some additional...
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments...
Definition: CGCall.cpp:593
virtual std::vector< CharUnits > getVBPtrOffsets(const CXXRecordDecl *RD)
Gets the offsets of all the virtual base pointers in a given class.
Definition: CGCXXABI.cpp:302
LValue - This represents an lvalue references.
Definition: CGValue.h:171
An abstract representation of regular/ObjC call/message targets.
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:147
virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc)=0
Build a virtual function pointer in the ABI-specific way.
QualType getDestroyedType() const
Retrieve the type being destroyed.
Definition: ExprCXX.cpp:214
bool isTypeOperand() const
Definition: ExprCXX.h:628
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue)
Definition: CGExprCXX.cpp:450
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:331
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:182
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:658
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
Definition: CGCleanup.cpp:640
bool isIgnored() const
Definition: CGValue.h:581
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2553
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4549
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition: ExprCXX.cpp:978
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy already-constructed elements of the ...
Definition: CGDecl.cpp:1704
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::Instruction **callOrInvoke=nullptr)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3695
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2368
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5516
bool isPointerType() const
Definition: Type.h:5712
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3139
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1519