clang  5.0.0
CGClass.cpp
Go to the documentation of this file.
1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
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 C++ code generation of classes
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGBlocks.h"
15 #include "CGCXXABI.h"
16 #include "CGDebugInfo.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
20 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtCXX.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/Transforms/Utils/SanitizerStats.h"
30 
31 using namespace clang;
32 using namespace CodeGen;
33 
34 /// Return the best known alignment for an unknown pointer to a
35 /// particular class.
37  if (!RD->isCompleteDefinition())
38  return CharUnits::One(); // Hopefully won't be used anywhere.
39 
40  auto &layout = getContext().getASTRecordLayout(RD);
41 
42  // If the class is final, then we know that the pointer points to an
43  // object of that type and can use the full alignment.
44  if (RD->hasAttr<FinalAttr>()) {
45  return layout.getAlignment();
46 
47  // Otherwise, we have to assume it could be a subclass.
48  } else {
49  return layout.getNonVirtualAlignment();
50  }
51 }
52 
53 /// Return the best known alignment for a pointer to a virtual base,
54 /// given the alignment of a pointer to the derived class.
56  const CXXRecordDecl *derivedClass,
57  const CXXRecordDecl *vbaseClass) {
58  // The basic idea here is that an underaligned derived pointer might
59  // indicate an underaligned base pointer.
60 
61  assert(vbaseClass->isCompleteDefinition());
62  auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
63  CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
64 
65  return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
66  expectedVBaseAlign);
67 }
68 
71  const CXXRecordDecl *baseDecl,
72  CharUnits expectedTargetAlign) {
73  // If the base is an incomplete type (which is, alas, possible with
74  // member pointers), be pessimistic.
75  if (!baseDecl->isCompleteDefinition())
76  return std::min(actualBaseAlign, expectedTargetAlign);
77 
78  auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
79  CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
80 
81  // If the class is properly aligned, assume the target offset is, too.
82  //
83  // This actually isn't necessarily the right thing to do --- if the
84  // class is a complete object, but it's only properly aligned for a
85  // base subobject, then the alignments of things relative to it are
86  // probably off as well. (Note that this requires the alignment of
87  // the target to be greater than the NV alignment of the derived
88  // class.)
89  //
90  // However, our approach to this kind of under-alignment can only
91  // ever be best effort; after all, we're never going to propagate
92  // alignments through variables or parameters. Note, in particular,
93  // that constructing a polymorphic type in an address that's less
94  // than pointer-aligned will generally trap in the constructor,
95  // unless we someday add some sort of attribute to change the
96  // assumed alignment of 'this'. So our goal here is pretty much
97  // just to allow the user to explicitly say that a pointer is
98  // under-aligned and then safely access its fields and vtables.
99  if (actualBaseAlign >= expectedBaseAlign) {
100  return expectedTargetAlign;
101  }
102 
103  // Otherwise, we might be offset by an arbitrary multiple of the
104  // actual alignment. The correct adjustment is to take the min of
105  // the two alignments.
106  return std::min(actualBaseAlign, expectedTargetAlign);
107 }
108 
110  assert(CurFuncDecl && "loading 'this' without a func declaration?");
111  assert(isa<CXXMethodDecl>(CurFuncDecl));
112 
113  // Lazily compute CXXThisAlignment.
114  if (CXXThisAlignment.isZero()) {
115  // Just use the best known alignment for the parent.
116  // TODO: if we're currently emitting a complete-object ctor/dtor,
117  // we can always use the complete-object alignment.
118  auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
119  CXXThisAlignment = CGM.getClassPointerAlignment(RD);
120  }
121 
122  return Address(LoadCXXThis(), CXXThisAlignment);
123 }
124 
125 /// Emit the address of a field using a member data pointer.
126 ///
127 /// \param E Only used for emergency diagnostics
128 Address
130  llvm::Value *memberPtr,
131  const MemberPointerType *memberPtrType,
132  LValueBaseInfo *BaseInfo) {
133  // Ask the ABI to compute the actual address.
134  llvm::Value *ptr =
135  CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
136  memberPtr, memberPtrType);
137 
138  QualType memberType = memberPtrType->getPointeeType();
139  CharUnits memberAlign = getNaturalTypeAlignment(memberType, BaseInfo);
140  memberAlign =
142  memberPtrType->getClass()->getAsCXXRecordDecl(),
143  memberAlign);
144  return Address(ptr, memberAlign);
145 }
146 
148  const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
151 
152  const ASTContext &Context = getContext();
153  const CXXRecordDecl *RD = DerivedClass;
154 
155  for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
156  const CXXBaseSpecifier *Base = *I;
157  assert(!Base->isVirtual() && "Should not see virtual bases here!");
158 
159  // Get the layout.
160  const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
161 
162  const CXXRecordDecl *BaseDecl =
163  cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
164 
165  // Add the offset.
166  Offset += Layout.getBaseClassOffset(BaseDecl);
167 
168  RD = BaseDecl;
169  }
170 
171  return Offset;
172 }
173 
174 llvm::Constant *
178  assert(PathBegin != PathEnd && "Base path should not be empty!");
179 
180  CharUnits Offset =
181  computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
182  if (Offset.isZero())
183  return nullptr;
184 
186  Types.ConvertType(getContext().getPointerDiffType());
187 
188  return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
189 }
190 
191 /// Gets the address of a direct base class within a complete object.
192 /// This should only be used for (1) non-virtual bases or (2) virtual bases
193 /// when the type is known to be complete (e.g. in complete destructors).
194 ///
195 /// The object pointed to by 'This' is assumed to be non-null.
196 Address
198  const CXXRecordDecl *Derived,
199  const CXXRecordDecl *Base,
200  bool BaseIsVirtual) {
201  // 'this' must be a pointer (in some address space) to Derived.
202  assert(This.getElementType() == ConvertType(Derived));
203 
204  // Compute the offset of the virtual base.
206  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
207  if (BaseIsVirtual)
208  Offset = Layout.getVBaseClassOffset(Base);
209  else
210  Offset = Layout.getBaseClassOffset(Base);
211 
212  // Shift and cast down to the base type.
213  // TODO: for complete types, this should be possible with a GEP.
214  Address V = This;
215  if (!Offset.isZero()) {
217  V = Builder.CreateConstInBoundsByteGEP(V, Offset);
218  }
220 
221  return V;
222 }
223 
224 static Address
226  CharUnits nonVirtualOffset,
227  llvm::Value *virtualOffset,
228  const CXXRecordDecl *derivedClass,
229  const CXXRecordDecl *nearestVBase) {
230  // Assert that we have something to do.
231  assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
232 
233  // Compute the offset from the static and dynamic components.
234  llvm::Value *baseOffset;
235  if (!nonVirtualOffset.isZero()) {
236  baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
237  nonVirtualOffset.getQuantity());
238  if (virtualOffset) {
239  baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
240  }
241  } else {
242  baseOffset = virtualOffset;
243  }
244 
245  // Apply the base offset.
246  llvm::Value *ptr = addr.getPointer();
247  ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
248  ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
249 
250  // If we have a virtual component, the alignment of the result will
251  // be relative only to the known alignment of that vbase.
252  CharUnits alignment;
253  if (virtualOffset) {
254  assert(nearestVBase && "virtual offset without vbase?");
255  alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
256  derivedClass, nearestVBase);
257  } else {
258  alignment = addr.getAlignment();
259  }
260  alignment = alignment.alignmentAtOffset(nonVirtualOffset);
261 
262  return Address(ptr, alignment);
263 }
264 
266  Address Value, const CXXRecordDecl *Derived,
268  CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
269  SourceLocation Loc) {
270  assert(PathBegin != PathEnd && "Base path should not be empty!");
271 
272  CastExpr::path_const_iterator Start = PathBegin;
273  const CXXRecordDecl *VBase = nullptr;
274 
275  // Sema has done some convenient canonicalization here: if the
276  // access path involved any virtual steps, the conversion path will
277  // *start* with a step down to the correct virtual base subobject,
278  // and hence will not require any further steps.
279  if ((*Start)->isVirtual()) {
280  VBase =
281  cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
282  ++Start;
283  }
284 
285  // Compute the static offset of the ultimate destination within its
286  // allocating subobject (the virtual base, if there is one, or else
287  // the "complete" object that we see).
289  VBase ? VBase : Derived, Start, PathEnd);
290 
291  // If there's a virtual step, we can sometimes "devirtualize" it.
292  // For now, that's limited to when the derived type is final.
293  // TODO: "devirtualize" this for accesses to known-complete objects.
294  if (VBase && Derived->hasAttr<FinalAttr>()) {
295  const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
296  CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
297  NonVirtualOffset += vBaseOffset;
298  VBase = nullptr; // we no longer have a virtual step
299  }
300 
301  // Get the base pointer type.
302  llvm::Type *BasePtrTy =
303  ConvertType((PathEnd[-1])->getType())->getPointerTo();
304 
305  QualType DerivedTy = getContext().getRecordType(Derived);
306  CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
307 
308  // If the static offset is zero and we don't have a virtual step,
309  // just do a bitcast; null checks are unnecessary.
310  if (NonVirtualOffset.isZero() && !VBase) {
311  if (sanitizePerformTypeCheck()) {
312  SanitizerSet SkippedChecks;
313  SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
314  EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
315  DerivedTy, DerivedAlign, SkippedChecks);
316  }
317  return Builder.CreateBitCast(Value, BasePtrTy);
318  }
319 
320  llvm::BasicBlock *origBB = nullptr;
321  llvm::BasicBlock *endBB = nullptr;
322 
323  // Skip over the offset (and the vtable load) if we're supposed to
324  // null-check the pointer.
325  if (NullCheckValue) {
326  origBB = Builder.GetInsertBlock();
327  llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
328  endBB = createBasicBlock("cast.end");
329 
330  llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
331  Builder.CreateCondBr(isNull, endBB, notNullBB);
332  EmitBlock(notNullBB);
333  }
334 
335  if (sanitizePerformTypeCheck()) {
336  SanitizerSet SkippedChecks;
337  SkippedChecks.set(SanitizerKind::Null, true);
339  Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
340  }
341 
342  // Compute the virtual offset.
343  llvm::Value *VirtualOffset = nullptr;
344  if (VBase) {
345  VirtualOffset =
346  CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
347  }
348 
349  // Apply both offsets.
350  Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
351  VirtualOffset, Derived, VBase);
352 
353  // Cast to the destination type.
354  Value = Builder.CreateBitCast(Value, BasePtrTy);
355 
356  // Build a phi if we needed a null check.
357  if (NullCheckValue) {
358  llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
359  Builder.CreateBr(endBB);
360  EmitBlock(endBB);
361 
362  llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
363  PHI->addIncoming(Value.getPointer(), notNullBB);
364  PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
365  Value = Address(PHI, Value.getAlignment());
366  }
367 
368  return Value;
369 }
370 
371 Address
373  const CXXRecordDecl *Derived,
376  bool NullCheckValue) {
377  assert(PathBegin != PathEnd && "Base path should not be empty!");
378 
379  QualType DerivedTy =
380  getContext().getCanonicalType(getContext().getTagDeclType(Derived));
381  llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
382 
383  llvm::Value *NonVirtualOffset =
384  CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
385 
386  if (!NonVirtualOffset) {
387  // No offset, we can just cast back.
388  return Builder.CreateBitCast(BaseAddr, DerivedPtrTy);
389  }
390 
391  llvm::BasicBlock *CastNull = nullptr;
392  llvm::BasicBlock *CastNotNull = nullptr;
393  llvm::BasicBlock *CastEnd = nullptr;
394 
395  if (NullCheckValue) {
396  CastNull = createBasicBlock("cast.null");
397  CastNotNull = createBasicBlock("cast.notnull");
398  CastEnd = createBasicBlock("cast.end");
399 
400  llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
401  Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
402  EmitBlock(CastNotNull);
403  }
404 
405  // Apply the offset.
407  Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
408  "sub.ptr");
409 
410  // Just cast.
411  Value = Builder.CreateBitCast(Value, DerivedPtrTy);
412 
413  // Produce a PHI if we had a null-check.
414  if (NullCheckValue) {
415  Builder.CreateBr(CastEnd);
416  EmitBlock(CastNull);
417  Builder.CreateBr(CastEnd);
418  EmitBlock(CastEnd);
419 
420  llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
421  PHI->addIncoming(Value, CastNotNull);
422  PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
423  Value = PHI;
424  }
425 
426  return Address(Value, CGM.getClassPointerAlignment(Derived));
427 }
428 
430  bool ForVirtualBase,
431  bool Delegating) {
432  if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
433  // This constructor/destructor does not need a VTT parameter.
434  return nullptr;
435  }
436 
437  const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
438  const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
439 
440  llvm::Value *VTT;
441 
442  uint64_t SubVTTIndex;
443 
444  if (Delegating) {
445  // If this is a delegating constructor call, just load the VTT.
446  return LoadCXXVTT();
447  } else if (RD == Base) {
448  // If the record matches the base, this is the complete ctor/dtor
449  // variant calling the base variant in a class with virtual bases.
450  assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
451  "doing no-op VTT offset in base dtor/ctor?");
452  assert(!ForVirtualBase && "Can't have same class as virtual base!");
453  SubVTTIndex = 0;
454  } else {
455  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
456  CharUnits BaseOffset = ForVirtualBase ?
457  Layout.getVBaseClassOffset(Base) :
458  Layout.getBaseClassOffset(Base);
459 
460  SubVTTIndex =
461  CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
462  assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
463  }
464 
466  // A VTT parameter was passed to the constructor, use it.
467  VTT = LoadCXXVTT();
468  VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
469  } else {
470  // We're the complete constructor, so get the VTT by name.
471  VTT = CGM.getVTables().GetAddrOfVTT(RD);
472  VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
473  }
474 
475  return VTT;
476 }
477 
478 namespace {
479  /// Call the destructor for a direct base class.
480  struct CallBaseDtor final : EHScopeStack::Cleanup {
481  const CXXRecordDecl *BaseClass;
482  bool BaseIsVirtual;
483  CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
484  : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
485 
486  void Emit(CodeGenFunction &CGF, Flags flags) override {
487  const CXXRecordDecl *DerivedClass =
488  cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
489 
490  const CXXDestructorDecl *D = BaseClass->getDestructor();
491  Address Addr =
493  DerivedClass, BaseClass,
494  BaseIsVirtual);
495  CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
496  /*Delegating=*/false, Addr);
497  }
498  };
499 
500  /// A visitor which checks whether an initializer uses 'this' in a
501  /// way which requires the vtable to be properly set.
502  struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
504 
505  bool UsesThis;
506 
507  DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
508 
509  // Black-list all explicit and implicit references to 'this'.
510  //
511  // Do we need to worry about external references to 'this' derived
512  // from arbitrary code? If so, then anything which runs arbitrary
513  // external code might potentially access the vtable.
514  void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
515  };
516 } // end anonymous namespace
517 
518 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
519  DynamicThisUseChecker Checker(C);
520  Checker.Visit(Init);
521  return Checker.UsesThis;
522 }
523 
525  const CXXRecordDecl *ClassDecl,
526  CXXCtorInitializer *BaseInit,
527  CXXCtorType CtorType) {
528  assert(BaseInit->isBaseInitializer() &&
529  "Must have base initializer!");
530 
531  Address ThisPtr = CGF.LoadCXXThisAddress();
532 
533  const Type *BaseType = BaseInit->getBaseClass();
534  CXXRecordDecl *BaseClassDecl =
535  cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
536 
537  bool isBaseVirtual = BaseInit->isBaseVirtual();
538 
539  // The base constructor doesn't construct virtual bases.
540  if (CtorType == Ctor_Base && isBaseVirtual)
541  return;
542 
543  // If the initializer for the base (other than the constructor
544  // itself) accesses 'this' in any way, we need to initialize the
545  // vtables.
546  if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
547  CGF.InitializeVTablePointers(ClassDecl);
548 
549  // We can pretend to be a complete class because it only matters for
550  // virtual bases, and we only do virtual bases for complete ctors.
551  Address V =
552  CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
553  BaseClassDecl,
554  isBaseVirtual);
555  AggValueSlot AggSlot =
560 
561  CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
562 
563  if (CGF.CGM.getLangOpts().Exceptions &&
564  !BaseClassDecl->hasTrivialDestructor())
565  CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
566  isBaseVirtual);
567 }
568 
570  auto *CD = dyn_cast<CXXConstructorDecl>(D);
571  if (!(CD && CD->isCopyOrMoveConstructor()) &&
573  return false;
574 
575  // We can emit a memcpy for a trivial copy or move constructor/assignment.
576  if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
577  return true;
578 
579  // We *must* emit a memcpy for a defaulted union copy or move op.
580  if (D->getParent()->isUnion() && D->isDefaulted())
581  return true;
582 
583  return false;
584 }
585 
587  CXXCtorInitializer *MemberInit,
588  LValue &LHS) {
589  FieldDecl *Field = MemberInit->getAnyMember();
590  if (MemberInit->isIndirectMemberInitializer()) {
591  // If we are initializing an anonymous union field, drill down to the field.
592  IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
593  for (const auto *I : IndirectField->chain())
594  LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
595  } else {
596  LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
597  }
598 }
599 
601  const CXXRecordDecl *ClassDecl,
602  CXXCtorInitializer *MemberInit,
603  const CXXConstructorDecl *Constructor,
604  FunctionArgList &Args) {
605  ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
606  assert(MemberInit->isAnyMemberInitializer() &&
607  "Must have member initializer!");
608  assert(MemberInit->getInit() && "Must have initializer!");
609 
610  // non-static data member initializers.
611  FieldDecl *Field = MemberInit->getAnyMember();
612  QualType FieldType = Field->getType();
613 
614  llvm::Value *ThisPtr = CGF.LoadCXXThis();
615  QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
616  LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
617 
618  EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
619 
620  // Special case: if we are in a copy or move constructor, and we are copying
621  // an array of PODs or classes with trivial copy constructors, ignore the
622  // AST and perform the copy we know is equivalent.
623  // FIXME: This is hacky at best... if we had a bit more explicit information
624  // in the AST, we could generalize it more easily.
625  const ConstantArrayType *Array
626  = CGF.getContext().getAsConstantArrayType(FieldType);
627  if (Array && Constructor->isDefaulted() &&
628  Constructor->isCopyOrMoveConstructor()) {
629  QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
630  CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
631  if (BaseElementTy.isPODType(CGF.getContext()) ||
633  unsigned SrcArgIndex =
634  CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
635  llvm::Value *SrcPtr
636  = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
637  LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
638  LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
639 
640  // Copy the aggregate.
641  CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
642  LHS.isVolatileQualified());
643  // Ensure that we destroy the objects if an exception is thrown later in
644  // the constructor.
645  QualType::DestructionKind dtorKind = FieldType.isDestructedType();
646  if (CGF.needsEHCleanup(dtorKind))
647  CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
648  return;
649  }
650  }
651 
652  CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
653 }
654 
656  Expr *Init) {
657  QualType FieldType = Field->getType();
658  switch (getEvaluationKind(FieldType)) {
659  case TEK_Scalar:
660  if (LHS.isSimple()) {
661  EmitExprAsInit(Init, Field, LHS, false);
662  } else {
663  RValue RHS = RValue::get(EmitScalarExpr(Init));
664  EmitStoreThroughLValue(RHS, LHS);
665  }
666  break;
667  case TEK_Complex:
668  EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
669  break;
670  case TEK_Aggregate: {
671  AggValueSlot Slot =
676  EmitAggExpr(Init, Slot);
677  break;
678  }
679  }
680 
681  // Ensure that we destroy this object if an exception is thrown
682  // later in the constructor.
683  QualType::DestructionKind dtorKind = FieldType.isDestructedType();
684  if (needsEHCleanup(dtorKind))
685  pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
686 }
687 
688 /// Checks whether the given constructor is a valid subject for the
689 /// complete-to-base constructor delegation optimization, i.e.
690 /// emitting the complete constructor as a simple call to the base
691 /// constructor.
693  const CXXConstructorDecl *Ctor) {
694 
695  // Currently we disable the optimization for classes with virtual
696  // bases because (1) the addresses of parameter variables need to be
697  // consistent across all initializers but (2) the delegate function
698  // call necessarily creates a second copy of the parameter variable.
699  //
700  // The limiting example (purely theoretical AFAIK):
701  // struct A { A(int &c) { c++; } };
702  // struct B : virtual A {
703  // B(int count) : A(count) { printf("%d\n", count); }
704  // };
705  // ...although even this example could in principle be emitted as a
706  // delegation since the address of the parameter doesn't escape.
707  if (Ctor->getParent()->getNumVBases()) {
708  // TODO: white-list trivial vbase initializers. This case wouldn't
709  // be subject to the restrictions below.
710 
711  // TODO: white-list cases where:
712  // - there are no non-reference parameters to the constructor
713  // - the initializers don't access any non-reference parameters
714  // - the initializers don't take the address of non-reference
715  // parameters
716  // - etc.
717  // If we ever add any of the above cases, remember that:
718  // - function-try-blocks will always blacklist this optimization
719  // - we need to perform the constructor prologue and cleanup in
720  // EmitConstructorBody.
721 
722  return false;
723  }
724 
725  // We also disable the optimization for variadic functions because
726  // it's impossible to "re-pass" varargs.
727  if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
728  return false;
729 
730  // FIXME: Decide if we can do a delegation of a delegating constructor.
731  if (Ctor->isDelegatingConstructor())
732  return false;
733 
734  return true;
735 }
736 
737 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
738 // to poison the extra field paddings inserted under
739 // -fsanitize-address-field-padding=1|2.
742  const CXXRecordDecl *ClassDecl =
743  Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
744  : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
745  if (!ClassDecl->mayInsertExtraPadding()) return;
746 
747  struct SizeAndOffset {
748  uint64_t Size;
749  uint64_t Offset;
750  };
751 
752  unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
753  const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
754 
755  // Populate sizes and offsets of fields.
757  for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
758  SSV[i].Offset =
759  Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
760 
761  size_t NumFields = 0;
762  for (const auto *Field : ClassDecl->fields()) {
763  const FieldDecl *D = Field;
764  std::pair<CharUnits, CharUnits> FieldInfo =
765  Context.getTypeInfoInChars(D->getType());
766  CharUnits FieldSize = FieldInfo.first;
767  assert(NumFields < SSV.size());
768  SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
769  NumFields++;
770  }
771  assert(NumFields == SSV.size());
772  if (SSV.size() <= 1) return;
773 
774  // We will insert calls to __asan_* run-time functions.
775  // LLVM AddressSanitizer pass may decide to inline them later.
776  llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
777  llvm::FunctionType *FTy =
778  llvm::FunctionType::get(CGM.VoidTy, Args, false);
779  llvm::Constant *F = CGM.CreateRuntimeFunction(
780  FTy, Prologue ? "__asan_poison_intra_object_redzone"
781  : "__asan_unpoison_intra_object_redzone");
782 
783  llvm::Value *ThisPtr = LoadCXXThis();
784  ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
785  uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
786  // For each field check if it has sufficient padding,
787  // if so (un)poison it with a call.
788  for (size_t i = 0; i < SSV.size(); i++) {
789  uint64_t AsanAlignment = 8;
790  uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
791  uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
792  uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
793  if (PoisonSize < AsanAlignment || !SSV[i].Size ||
794  (NextField % AsanAlignment) != 0)
795  continue;
796  Builder.CreateCall(
797  F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
798  Builder.getIntN(PtrSize, PoisonSize)});
799  }
800 }
801 
802 /// EmitConstructorBody - Emits the body of the current constructor.
805  const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
806  CXXCtorType CtorType = CurGD.getCtorType();
807 
809  CtorType == Ctor_Complete) &&
810  "can only generate complete ctor for this ABI");
811 
812  // Before we go any further, try the complete->base constructor
813  // delegation optimization.
814  if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
816  EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
817  return;
818  }
819 
820  const FunctionDecl *Definition = nullptr;
821  Stmt *Body = Ctor->getBody(Definition);
822  assert(Definition == Ctor && "emitting wrong constructor body");
823 
824  // Enter the function-try-block before the constructor prologue if
825  // applicable.
826  bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
827  if (IsTryBody)
828  EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
829 
831 
832  RunCleanupsScope RunCleanups(*this);
833 
834  // TODO: in restricted cases, we can emit the vbase initializers of
835  // a complete ctor and then delegate to the base ctor.
836 
837  // Emit the constructor prologue, i.e. the base and member
838  // initializers.
839  EmitCtorPrologue(Ctor, CtorType, Args);
840 
841  // Emit the body of the statement.
842  if (IsTryBody)
843  EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
844  else if (Body)
845  EmitStmt(Body);
846 
847  // Emit any cleanup blocks associated with the member or base
848  // initializers, which includes (along the exceptional path) the
849  // destructors for those members and bases that were fully
850  // constructed.
851  RunCleanups.ForceCleanup();
852 
853  if (IsTryBody)
854  ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
855 }
856 
857 namespace {
858  /// RAII object to indicate that codegen is copying the value representation
859  /// instead of the object representation. Useful when copying a struct or
860  /// class which has uninitialized members and we're only performing
861  /// lvalue-to-rvalue conversion on the object but not its members.
862  class CopyingValueRepresentation {
863  public:
864  explicit CopyingValueRepresentation(CodeGenFunction &CGF)
865  : CGF(CGF), OldSanOpts(CGF.SanOpts) {
866  CGF.SanOpts.set(SanitizerKind::Bool, false);
867  CGF.SanOpts.set(SanitizerKind::Enum, false);
868  }
869  ~CopyingValueRepresentation() {
870  CGF.SanOpts = OldSanOpts;
871  }
872  private:
873  CodeGenFunction &CGF;
874  SanitizerSet OldSanOpts;
875  };
876 } // end anonymous namespace
877 
878 namespace {
879  class FieldMemcpyizer {
880  public:
881  FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
882  const VarDecl *SrcRec)
883  : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
884  RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
885  FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
886  LastFieldOffset(0), LastAddedFieldIndex(0) {}
887 
888  bool isMemcpyableField(FieldDecl *F) const {
889  // Never memcpy fields when we are adding poisoned paddings.
890  if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
891  return false;
892  Qualifiers Qual = F->getType().getQualifiers();
893  if (Qual.hasVolatile() || Qual.hasObjCLifetime())
894  return false;
895  return true;
896  }
897 
898  void addMemcpyableField(FieldDecl *F) {
899  if (!FirstField)
900  addInitialField(F);
901  else
902  addNextField(F);
903  }
904 
905  CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
906  unsigned LastFieldSize =
907  LastField->isBitField() ?
908  LastField->getBitWidthValue(CGF.getContext()) :
909  CGF.getContext().getTypeSize(LastField->getType());
910  uint64_t MemcpySizeBits =
911  LastFieldOffset + LastFieldSize - FirstByteOffset +
912  CGF.getContext().getCharWidth() - 1;
913  CharUnits MemcpySize =
914  CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
915  return MemcpySize;
916  }
917 
918  void emitMemcpy() {
919  // Give the subclass a chance to bail out if it feels the memcpy isn't
920  // worth it (e.g. Hasn't aggregated enough data).
921  if (!FirstField) {
922  return;
923  }
924 
925  uint64_t FirstByteOffset;
926  if (FirstField->isBitField()) {
927  const CGRecordLayout &RL =
928  CGF.getTypes().getCGRecordLayout(FirstField->getParent());
929  const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
930  // FirstFieldOffset is not appropriate for bitfields,
931  // we need to use the storage offset instead.
932  FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
933  } else {
934  FirstByteOffset = FirstFieldOffset;
935  }
936 
937  CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
938  QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
939  Address ThisPtr = CGF.LoadCXXThisAddress();
940  LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
941  LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
942  llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
943  LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
944  LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
945 
946  emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
947  Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
948  MemcpySize);
949  reset();
950  }
951 
952  void reset() {
953  FirstField = nullptr;
954  }
955 
956  protected:
957  CodeGenFunction &CGF;
958  const CXXRecordDecl *ClassDecl;
959 
960  private:
961  void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
962  llvm::PointerType *DPT = DestPtr.getType();
963  llvm::Type *DBP =
964  llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
965  DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
966 
967  llvm::PointerType *SPT = SrcPtr.getType();
968  llvm::Type *SBP =
969  llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
970  SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
971 
972  CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
973  }
974 
975  void addInitialField(FieldDecl *F) {
976  FirstField = F;
977  LastField = F;
978  FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
979  LastFieldOffset = FirstFieldOffset;
980  LastAddedFieldIndex = F->getFieldIndex();
981  }
982 
983  void addNextField(FieldDecl *F) {
984  // For the most part, the following invariant will hold:
985  // F->getFieldIndex() == LastAddedFieldIndex + 1
986  // The one exception is that Sema won't add a copy-initializer for an
987  // unnamed bitfield, which will show up here as a gap in the sequence.
988  assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
989  "Cannot aggregate fields out of order.");
990  LastAddedFieldIndex = F->getFieldIndex();
991 
992  // The 'first' and 'last' fields are chosen by offset, rather than field
993  // index. This allows the code to support bitfields, as well as regular
994  // fields.
995  uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
996  if (FOffset < FirstFieldOffset) {
997  FirstField = F;
998  FirstFieldOffset = FOffset;
999  } else if (FOffset > LastFieldOffset) {
1000  LastField = F;
1001  LastFieldOffset = FOffset;
1002  }
1003  }
1004 
1005  const VarDecl *SrcRec;
1006  const ASTRecordLayout &RecLayout;
1007  FieldDecl *FirstField;
1008  FieldDecl *LastField;
1009  uint64_t FirstFieldOffset, LastFieldOffset;
1010  unsigned LastAddedFieldIndex;
1011  };
1012 
1013  class ConstructorMemcpyizer : public FieldMemcpyizer {
1014  private:
1015  /// Get source argument for copy constructor. Returns null if not a copy
1016  /// constructor.
1017  static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1018  const CXXConstructorDecl *CD,
1019  FunctionArgList &Args) {
1020  if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1021  return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1022  return nullptr;
1023  }
1024 
1025  // Returns true if a CXXCtorInitializer represents a member initialization
1026  // that can be rolled into a memcpy.
1027  bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1028  if (!MemcpyableCtor)
1029  return false;
1030  FieldDecl *Field = MemberInit->getMember();
1031  assert(Field && "No field for member init.");
1032  QualType FieldType = Field->getType();
1033  CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1034 
1035  // Bail out on non-memcpyable, not-trivially-copyable members.
1036  if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
1037  !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1038  FieldType->isReferenceType()))
1039  return false;
1040 
1041  // Bail out on volatile fields.
1042  if (!isMemcpyableField(Field))
1043  return false;
1044 
1045  // Otherwise we're good.
1046  return true;
1047  }
1048 
1049  public:
1050  ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1051  FunctionArgList &Args)
1052  : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1053  ConstructorDecl(CD),
1054  MemcpyableCtor(CD->isDefaulted() &&
1055  CD->isCopyOrMoveConstructor() &&
1056  CGF.getLangOpts().getGC() == LangOptions::NonGC),
1057  Args(Args) { }
1058 
1059  void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1060  if (isMemberInitMemcpyable(MemberInit)) {
1061  AggregatedInits.push_back(MemberInit);
1062  addMemcpyableField(MemberInit->getMember());
1063  } else {
1064  emitAggregatedInits();
1065  EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1066  ConstructorDecl, Args);
1067  }
1068  }
1069 
1070  void emitAggregatedInits() {
1071  if (AggregatedInits.size() <= 1) {
1072  // This memcpy is too small to be worthwhile. Fall back on default
1073  // codegen.
1074  if (!AggregatedInits.empty()) {
1075  CopyingValueRepresentation CVR(CGF);
1076  EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1077  AggregatedInits[0], ConstructorDecl, Args);
1078  AggregatedInits.clear();
1079  }
1080  reset();
1081  return;
1082  }
1083 
1084  pushEHDestructors();
1085  emitMemcpy();
1086  AggregatedInits.clear();
1087  }
1088 
1089  void pushEHDestructors() {
1090  Address ThisPtr = CGF.LoadCXXThisAddress();
1091  QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1092  LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
1093 
1094  for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1095  CXXCtorInitializer *MemberInit = AggregatedInits[i];
1096  QualType FieldType = MemberInit->getAnyMember()->getType();
1097  QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1098  if (!CGF.needsEHCleanup(dtorKind))
1099  continue;
1100  LValue FieldLHS = LHS;
1101  EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1102  CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
1103  }
1104  }
1105 
1106  void finish() {
1107  emitAggregatedInits();
1108  }
1109 
1110  private:
1111  const CXXConstructorDecl *ConstructorDecl;
1112  bool MemcpyableCtor;
1113  FunctionArgList &Args;
1114  SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1115  };
1116 
1117  class AssignmentMemcpyizer : public FieldMemcpyizer {
1118  private:
1119  // Returns the memcpyable field copied by the given statement, if one
1120  // exists. Otherwise returns null.
1121  FieldDecl *getMemcpyableField(Stmt *S) {
1122  if (!AssignmentsMemcpyable)
1123  return nullptr;
1124  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1125  // Recognise trivial assignments.
1126  if (BO->getOpcode() != BO_Assign)
1127  return nullptr;
1128  MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1129  if (!ME)
1130  return nullptr;
1131  FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1132  if (!Field || !isMemcpyableField(Field))
1133  return nullptr;
1134  Stmt *RHS = BO->getRHS();
1135  if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1136  RHS = EC->getSubExpr();
1137  if (!RHS)
1138  return nullptr;
1139  if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
1140  if (ME2->getMemberDecl() == Field)
1141  return Field;
1142  }
1143  return nullptr;
1144  } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1145  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1146  if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
1147  return nullptr;
1148  MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1149  if (!IOA)
1150  return nullptr;
1151  FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1152  if (!Field || !isMemcpyableField(Field))
1153  return nullptr;
1154  MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1155  if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1156  return nullptr;
1157  return Field;
1158  } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1159  FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1160  if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1161  return nullptr;
1162  Expr *DstPtr = CE->getArg(0);
1163  if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1164  DstPtr = DC->getSubExpr();
1165  UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1166  if (!DUO || DUO->getOpcode() != UO_AddrOf)
1167  return nullptr;
1168  MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1169  if (!ME)
1170  return nullptr;
1171  FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1172  if (!Field || !isMemcpyableField(Field))
1173  return nullptr;
1174  Expr *SrcPtr = CE->getArg(1);
1175  if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1176  SrcPtr = SC->getSubExpr();
1177  UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1178  if (!SUO || SUO->getOpcode() != UO_AddrOf)
1179  return nullptr;
1180  MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1181  if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1182  return nullptr;
1183  return Field;
1184  }
1185 
1186  return nullptr;
1187  }
1188 
1189  bool AssignmentsMemcpyable;
1190  SmallVector<Stmt*, 16> AggregatedStmts;
1191 
1192  public:
1193  AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1194  FunctionArgList &Args)
1195  : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1196  AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1197  assert(Args.size() == 2);
1198  }
1199 
1200  void emitAssignment(Stmt *S) {
1201  FieldDecl *F = getMemcpyableField(S);
1202  if (F) {
1203  addMemcpyableField(F);
1204  AggregatedStmts.push_back(S);
1205  } else {
1206  emitAggregatedStmts();
1207  CGF.EmitStmt(S);
1208  }
1209  }
1210 
1211  void emitAggregatedStmts() {
1212  if (AggregatedStmts.size() <= 1) {
1213  if (!AggregatedStmts.empty()) {
1214  CopyingValueRepresentation CVR(CGF);
1215  CGF.EmitStmt(AggregatedStmts[0]);
1216  }
1217  reset();
1218  }
1219 
1220  emitMemcpy();
1221  AggregatedStmts.clear();
1222  }
1223 
1224  void finish() {
1225  emitAggregatedStmts();
1226  }
1227  };
1228 } // end anonymous namespace
1229 
1230 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
1231  const Type *BaseType = BaseInit->getBaseClass();
1232  const auto *BaseClassDecl =
1233  cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
1234  return BaseClassDecl->isDynamicClass();
1235 }
1236 
1237 /// EmitCtorPrologue - This routine generates necessary code to initialize
1238 /// base classes and non-static data members belonging to this constructor.
1240  CXXCtorType CtorType,
1241  FunctionArgList &Args) {
1242  if (CD->isDelegatingConstructor())
1243  return EmitDelegatingCXXConstructorCall(CD, Args);
1244 
1245  const CXXRecordDecl *ClassDecl = CD->getParent();
1246 
1248  E = CD->init_end();
1249 
1250  llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1251  if (ClassDecl->getNumVBases() &&
1253  // The ABIs that don't have constructor variants need to put a branch
1254  // before the virtual base initialization code.
1255  BaseCtorContinueBB =
1256  CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1257  assert(BaseCtorContinueBB);
1258  }
1259 
1260  llvm::Value *const OldThis = CXXThisValue;
1261  // Virtual base initializers first.
1262  for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1263  if (CGM.getCodeGenOpts().StrictVTablePointers &&
1264  CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1266  CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1267  EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1268  }
1269 
1270  if (BaseCtorContinueBB) {
1271  // Complete object handler should continue to the remaining initializers.
1272  Builder.CreateBr(BaseCtorContinueBB);
1273  EmitBlock(BaseCtorContinueBB);
1274  }
1275 
1276  // Then, non-virtual base initializers.
1277  for (; B != E && (*B)->isBaseInitializer(); B++) {
1278  assert(!(*B)->isBaseVirtual());
1279 
1280  if (CGM.getCodeGenOpts().StrictVTablePointers &&
1281  CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1283  CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1284  EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1285  }
1286 
1287  CXXThisValue = OldThis;
1288 
1289  InitializeVTablePointers(ClassDecl);
1290 
1291  // And finally, initialize class members.
1293  ConstructorMemcpyizer CM(*this, CD, Args);
1294  for (; B != E; B++) {
1295  CXXCtorInitializer *Member = (*B);
1296  assert(!Member->isBaseInitializer());
1297  assert(Member->isAnyMemberInitializer() &&
1298  "Delegating initializer on non-delegating constructor");
1299  CM.addMemberInitializer(Member);
1300  }
1301  CM.finish();
1302 }
1303 
1304 static bool
1306 
1307 static bool
1309  const CXXRecordDecl *BaseClassDecl,
1310  const CXXRecordDecl *MostDerivedClassDecl)
1311 {
1312  // If the destructor is trivial we don't have to check anything else.
1313  if (BaseClassDecl->hasTrivialDestructor())
1314  return true;
1315 
1316  if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1317  return false;
1318 
1319  // Check fields.
1320  for (const auto *Field : BaseClassDecl->fields())
1321  if (!FieldHasTrivialDestructorBody(Context, Field))
1322  return false;
1323 
1324  // Check non-virtual bases.
1325  for (const auto &I : BaseClassDecl->bases()) {
1326  if (I.isVirtual())
1327  continue;
1328 
1329  const CXXRecordDecl *NonVirtualBase =
1330  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1331  if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1332  MostDerivedClassDecl))
1333  return false;
1334  }
1335 
1336  if (BaseClassDecl == MostDerivedClassDecl) {
1337  // Check virtual bases.
1338  for (const auto &I : BaseClassDecl->vbases()) {
1339  const CXXRecordDecl *VirtualBase =
1340  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1341  if (!HasTrivialDestructorBody(Context, VirtualBase,
1342  MostDerivedClassDecl))
1343  return false;
1344  }
1345  }
1346 
1347  return true;
1348 }
1349 
1350 static bool
1352  const FieldDecl *Field)
1353 {
1354  QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1355 
1356  const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1357  if (!RT)
1358  return true;
1359 
1360  CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1361 
1362  // The destructor for an implicit anonymous union member is never invoked.
1363  if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1364  return false;
1365 
1366  return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1367 }
1368 
1369 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1370 /// any vtable pointers before calling this destructor.
1372  const CXXDestructorDecl *Dtor) {
1373  const CXXRecordDecl *ClassDecl = Dtor->getParent();
1374  if (!ClassDecl->isDynamicClass())
1375  return true;
1376 
1377  if (!Dtor->hasTrivialBody())
1378  return false;
1379 
1380  // Check the fields.
1381  for (const auto *Field : ClassDecl->fields())
1382  if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
1383  return false;
1384 
1385  return true;
1386 }
1387 
1388 /// EmitDestructorBody - Emits the body of the current destructor.
1390  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1391  CXXDtorType DtorType = CurGD.getDtorType();
1392 
1393  // For an abstract class, non-base destructors are never used (and can't
1394  // be emitted in general, because vbase dtors may not have been validated
1395  // by Sema), but the Itanium ABI doesn't make them optional and Clang may
1396  // in fact emit references to them from other compilations, so emit them
1397  // as functions containing a trap instruction.
1398  if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
1399  llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
1400  TrapCall->setDoesNotReturn();
1401  TrapCall->setDoesNotThrow();
1402  Builder.CreateUnreachable();
1403  Builder.ClearInsertionPoint();
1404  return;
1405  }
1406 
1407  Stmt *Body = Dtor->getBody();
1408  if (Body)
1410 
1411  // The call to operator delete in a deleting destructor happens
1412  // outside of the function-try-block, which means it's always
1413  // possible to delegate the destructor body to the complete
1414  // destructor. Do so.
1415  if (DtorType == Dtor_Deleting) {
1417  EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1418  /*Delegating=*/false, LoadCXXThisAddress());
1419  PopCleanupBlock();
1420  return;
1421  }
1422 
1423  // If the body is a function-try-block, enter the try before
1424  // anything else.
1425  bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1426  if (isTryBody)
1427  EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1429 
1430  // Enter the epilogue cleanups.
1431  RunCleanupsScope DtorEpilogue(*this);
1432 
1433  // If this is the complete variant, just invoke the base variant;
1434  // the epilogue will destruct the virtual bases. But we can't do
1435  // this optimization if the body is a function-try-block, because
1436  // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1437  // always delegate because we might not have a definition in this TU.
1438  switch (DtorType) {
1439  case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
1440  case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1441 
1442  case Dtor_Complete:
1443  assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1444  "can't emit a dtor without a body for non-Microsoft ABIs");
1445 
1446  // Enter the cleanup scopes for virtual bases.
1448 
1449  if (!isTryBody) {
1450  EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1451  /*Delegating=*/false, LoadCXXThisAddress());
1452  break;
1453  }
1454 
1455  // Fallthrough: act like we're in the base variant.
1456  LLVM_FALLTHROUGH;
1457 
1458  case Dtor_Base:
1459  assert(Body);
1460 
1461  // Enter the cleanup scopes for fields and non-virtual bases.
1463 
1464  // Initialize the vtable pointers before entering the body.
1465  if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
1466  // Insert the llvm.invariant.group.barrier intrinsic before initializing
1467  // the vptrs to cancel any previous assumptions we might have made.
1468  if (CGM.getCodeGenOpts().StrictVTablePointers &&
1469  CGM.getCodeGenOpts().OptimizationLevel > 0)
1470  CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
1472  }
1473 
1474  if (isTryBody)
1475  EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1476  else if (Body)
1477  EmitStmt(Body);
1478  else {
1479  assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1480  // nothing to do besides what's in the epilogue
1481  }
1482  // -fapple-kext must inline any call to this dtor into
1483  // the caller's body.
1484  if (getLangOpts().AppleKext)
1485  CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1486 
1487  break;
1488  }
1489 
1490  // Jump out through the epilogue cleanups.
1491  DtorEpilogue.ForceCleanup();
1492 
1493  // Exit the try if applicable.
1494  if (isTryBody)
1495  ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1496 }
1497 
1499  const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1500  const Stmt *RootS = AssignOp->getBody();
1501  assert(isa<CompoundStmt>(RootS) &&
1502  "Body of an implicit assignment operator should be compound stmt.");
1503  const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1504 
1505  LexicalScope Scope(*this, RootCS->getSourceRange());
1506 
1507  incrementProfileCounter(RootCS);
1508  AssignmentMemcpyizer AM(*this, AssignOp, Args);
1509  for (auto *I : RootCS->body())
1510  AM.emitAssignment(I);
1511  AM.finish();
1512 }
1513 
1514 namespace {
1515  /// Call the operator delete associated with the current destructor.
1516  struct CallDtorDelete final : EHScopeStack::Cleanup {
1517  CallDtorDelete() {}
1518 
1519  void Emit(CodeGenFunction &CGF, Flags flags) override {
1520  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1521  const CXXRecordDecl *ClassDecl = Dtor->getParent();
1522  CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1523  CGF.getContext().getTagDeclType(ClassDecl));
1524  }
1525  };
1526 
1527  struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
1528  llvm::Value *ShouldDeleteCondition;
1529 
1530  public:
1531  CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1532  : ShouldDeleteCondition(ShouldDeleteCondition) {
1533  assert(ShouldDeleteCondition != nullptr);
1534  }
1535 
1536  void Emit(CodeGenFunction &CGF, Flags flags) override {
1537  llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1538  llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1539  llvm::Value *ShouldCallDelete
1540  = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1541  CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1542 
1543  CGF.EmitBlock(callDeleteBB);
1544  const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1545  const CXXRecordDecl *ClassDecl = Dtor->getParent();
1546  CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1547  CGF.getContext().getTagDeclType(ClassDecl));
1548  CGF.Builder.CreateBr(continueBB);
1549 
1550  CGF.EmitBlock(continueBB);
1551  }
1552  };
1553 
1554  class DestroyField final : public EHScopeStack::Cleanup {
1555  const FieldDecl *field;
1556  CodeGenFunction::Destroyer *destroyer;
1557  bool useEHCleanupForArray;
1558 
1559  public:
1560  DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1561  bool useEHCleanupForArray)
1562  : field(field), destroyer(destroyer),
1563  useEHCleanupForArray(useEHCleanupForArray) {}
1564 
1565  void Emit(CodeGenFunction &CGF, Flags flags) override {
1566  // Find the address of the field.
1567  Address thisValue = CGF.LoadCXXThisAddress();
1568  QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1569  LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1570  LValue LV = CGF.EmitLValueForField(ThisLV, field);
1571  assert(LV.isSimple());
1572 
1573  CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1574  flags.isForNormalCleanup() && useEHCleanupForArray);
1575  }
1576  };
1577 
1578  static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
1579  CharUnits::QuantityType PoisonSize) {
1580  // Pass in void pointer and size of region as arguments to runtime
1581  // function
1582  llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
1583  llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1584 
1585  llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1586 
1587  llvm::FunctionType *FnType =
1588  llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1589  llvm::Value *Fn =
1590  CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1591  CGF.EmitNounwindRuntimeCall(Fn, Args);
1592  }
1593 
1594  class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
1595  const CXXDestructorDecl *Dtor;
1596 
1597  public:
1598  SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1599 
1600  // Generate function call for handling object poisoning.
1601  // Disables tail call elimination, to prevent the current stack frame
1602  // from disappearing from the stack trace.
1603  void Emit(CodeGenFunction &CGF, Flags flags) override {
1604  const ASTRecordLayout &Layout =
1605  CGF.getContext().getASTRecordLayout(Dtor->getParent());
1606 
1607  // Nothing to poison.
1608  if (Layout.getFieldCount() == 0)
1609  return;
1610 
1611  // Prevent the current stack frame from disappearing from the stack trace.
1612  CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1613 
1614  // Construct pointer to region to begin poisoning, and calculate poison
1615  // size, so that only members declared in this class are poisoned.
1616  ASTContext &Context = CGF.getContext();
1617  unsigned fieldIndex = 0;
1618  int startIndex = -1;
1619  // RecordDecl::field_iterator Field;
1620  for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1621  // Poison field if it is trivial
1622  if (FieldHasTrivialDestructorBody(Context, Field)) {
1623  // Start sanitizing at this field
1624  if (startIndex < 0)
1625  startIndex = fieldIndex;
1626 
1627  // Currently on the last field, and it must be poisoned with the
1628  // current block.
1629  if (fieldIndex == Layout.getFieldCount() - 1) {
1630  PoisonMembers(CGF, startIndex, Layout.getFieldCount());
1631  }
1632  } else if (startIndex >= 0) {
1633  // No longer within a block of memory to poison, so poison the block
1634  PoisonMembers(CGF, startIndex, fieldIndex);
1635  // Re-set the start index
1636  startIndex = -1;
1637  }
1638  fieldIndex += 1;
1639  }
1640  }
1641 
1642  private:
1643  /// \param layoutStartOffset index of the ASTRecordLayout field to
1644  /// start poisoning (inclusive)
1645  /// \param layoutEndOffset index of the ASTRecordLayout field to
1646  /// end poisoning (exclusive)
1647  void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
1648  unsigned layoutEndOffset) {
1649  ASTContext &Context = CGF.getContext();
1650  const ASTRecordLayout &Layout =
1651  Context.getASTRecordLayout(Dtor->getParent());
1652 
1653  llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1654  CGF.SizeTy,
1655  Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1656  .getQuantity());
1657 
1658  llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1659  CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1660  OffsetSizePtr);
1661 
1662  CharUnits::QuantityType PoisonSize;
1663  if (layoutEndOffset >= Layout.getFieldCount()) {
1664  PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1665  Context.toCharUnitsFromBits(
1666  Layout.getFieldOffset(layoutStartOffset))
1667  .getQuantity();
1668  } else {
1669  PoisonSize = Context.toCharUnitsFromBits(
1670  Layout.getFieldOffset(layoutEndOffset) -
1671  Layout.getFieldOffset(layoutStartOffset))
1672  .getQuantity();
1673  }
1674 
1675  if (PoisonSize == 0)
1676  return;
1677 
1678  EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
1679  }
1680  };
1681 
1682  class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
1683  const CXXDestructorDecl *Dtor;
1684 
1685  public:
1686  SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1687 
1688  // Generate function call for handling vtable pointer poisoning.
1689  void Emit(CodeGenFunction &CGF, Flags flags) override {
1690  assert(Dtor->getParent()->isDynamicClass());
1691  (void)Dtor;
1692  ASTContext &Context = CGF.getContext();
1693  // Poison vtable and vtable ptr if they exist for this class.
1694  llvm::Value *VTablePtr = CGF.LoadCXXThis();
1695 
1696  CharUnits::QuantityType PoisonSize =
1697  Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
1698  // Pass in void pointer and size of region as arguments to runtime
1699  // function
1700  EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
1701  }
1702  };
1703 } // end anonymous namespace
1704 
1705 /// \brief Emit all code that comes at the end of class's
1706 /// destructor. This is to call destructors on members and base classes
1707 /// in reverse order of their construction.
1709  CXXDtorType DtorType) {
1710  assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1711  "Should not emit dtor epilogue for non-exported trivial dtor!");
1712 
1713  // The deleting-destructor phase just needs to call the appropriate
1714  // operator delete that Sema picked up.
1715  if (DtorType == Dtor_Deleting) {
1716  assert(DD->getOperatorDelete() &&
1717  "operator delete missing - EnterDtorCleanups");
1718  if (CXXStructorImplicitParamValue) {
1719  // If there is an implicit param to the deleting dtor, it's a boolean
1720  // telling whether we should call delete at the end of the dtor.
1721  EHStack.pushCleanup<CallDtorDeleteConditional>(
1722  NormalAndEHCleanup, CXXStructorImplicitParamValue);
1723  } else {
1724  EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1725  }
1726  return;
1727  }
1728 
1729  const CXXRecordDecl *ClassDecl = DD->getParent();
1730 
1731  // Unions have no bases and do not call field destructors.
1732  if (ClassDecl->isUnion())
1733  return;
1734 
1735  // The complete-destructor phase just destructs all the virtual bases.
1736  if (DtorType == Dtor_Complete) {
1737  // Poison the vtable pointer such that access after the base
1738  // and member destructors are invoked is invalid.
1739  if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1740  SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
1741  ClassDecl->isPolymorphic())
1742  EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1743 
1744  // We push them in the forward order so that they'll be popped in
1745  // the reverse order.
1746  for (const auto &Base : ClassDecl->vbases()) {
1747  CXXRecordDecl *BaseClassDecl
1748  = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1749 
1750  // Ignore trivial destructors.
1751  if (BaseClassDecl->hasTrivialDestructor())
1752  continue;
1753 
1754  EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1755  BaseClassDecl,
1756  /*BaseIsVirtual*/ true);
1757  }
1758 
1759  return;
1760  }
1761 
1762  assert(DtorType == Dtor_Base);
1763  // Poison the vtable pointer if it has no virtual bases, but inherits
1764  // virtual functions.
1765  if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1766  SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
1767  ClassDecl->isPolymorphic())
1768  EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
1769 
1770  // Destroy non-virtual bases.
1771  for (const auto &Base : ClassDecl->bases()) {
1772  // Ignore virtual bases.
1773  if (Base.isVirtual())
1774  continue;
1775 
1776  CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1777 
1778  // Ignore trivial destructors.
1779  if (BaseClassDecl->hasTrivialDestructor())
1780  continue;
1781 
1782  EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1783  BaseClassDecl,
1784  /*BaseIsVirtual*/ false);
1785  }
1786 
1787  // Poison fields such that access after their destructors are
1788  // invoked, and before the base class destructor runs, is invalid.
1789  if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1790  SanOpts.has(SanitizerKind::Memory))
1791  EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
1792 
1793  // Destroy direct fields.
1794  for (const auto *Field : ClassDecl->fields()) {
1795  QualType type = Field->getType();
1796  QualType::DestructionKind dtorKind = type.isDestructedType();
1797  if (!dtorKind) continue;
1798 
1799  // Anonymous union members do not have their destructors called.
1800  const RecordType *RT = type->getAsUnionType();
1801  if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1802 
1803  CleanupKind cleanupKind = getCleanupKind(dtorKind);
1804  EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1805  getDestroyer(dtorKind),
1806  cleanupKind & EHCleanup);
1807  }
1808 }
1809 
1810 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1811 /// constructor for each of several members of an array.
1812 ///
1813 /// \param ctor the constructor to call for each element
1814 /// \param arrayType the type of the array to initialize
1815 /// \param arrayBegin an arrayType*
1816 /// \param zeroInitialize true if each element should be
1817 /// zero-initialized before it is constructed
1819  const CXXConstructorDecl *ctor, const ArrayType *arrayType,
1820  Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
1821  QualType elementType;
1822  llvm::Value *numElements =
1823  emitArrayLength(arrayType, elementType, arrayBegin);
1824 
1825  EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
1826 }
1827 
1828 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1829 /// constructor for each of several members of an array.
1830 ///
1831 /// \param ctor the constructor to call for each element
1832 /// \param numElements the number of elements in the array;
1833 /// may be zero
1834 /// \param arrayBase a T*, where T is the type constructed by ctor
1835 /// \param zeroInitialize true if each element should be
1836 /// zero-initialized before it is constructed
1838  llvm::Value *numElements,
1839  Address arrayBase,
1840  const CXXConstructExpr *E,
1841  bool zeroInitialize) {
1842  // It's legal for numElements to be zero. This can happen both
1843  // dynamically, because x can be zero in 'new A[x]', and statically,
1844  // because of GCC extensions that permit zero-length arrays. There
1845  // are probably legitimate places where we could assume that this
1846  // doesn't happen, but it's not clear that it's worth it.
1847  llvm::BranchInst *zeroCheckBranch = nullptr;
1848 
1849  // Optimize for a constant count.
1850  llvm::ConstantInt *constantCount
1851  = dyn_cast<llvm::ConstantInt>(numElements);
1852  if (constantCount) {
1853  // Just skip out if the constant count is zero.
1854  if (constantCount->isZero()) return;
1855 
1856  // Otherwise, emit the check.
1857  } else {
1858  llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1859  llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1860  zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1861  EmitBlock(loopBB);
1862  }
1863 
1864  // Find the end of the array.
1865  llvm::Value *arrayBegin = arrayBase.getPointer();
1866  llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1867  "arrayctor.end");
1868 
1869  // Enter the loop, setting up a phi for the current location to initialize.
1870  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1871  llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1872  EmitBlock(loopBB);
1873  llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1874  "arrayctor.cur");
1875  cur->addIncoming(arrayBegin, entryBB);
1876 
1877  // Inside the loop body, emit the constructor call on the array element.
1878 
1879  // The alignment of the base, adjusted by the size of a single element,
1880  // provides a conservative estimate of the alignment of every element.
1881  // (This assumes we never start tracking offsetted alignments.)
1882  //
1883  // Note that these are complete objects and so we don't need to
1884  // use the non-virtual size or alignment.
1886  CharUnits eltAlignment =
1887  arrayBase.getAlignment()
1888  .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1889  Address curAddr = Address(cur, eltAlignment);
1890 
1891  // Zero initialize the storage, if requested.
1892  if (zeroInitialize)
1893  EmitNullInitialization(curAddr, type);
1894 
1895  // C++ [class.temporary]p4:
1896  // There are two contexts in which temporaries are destroyed at a different
1897  // point than the end of the full-expression. The first context is when a
1898  // default constructor is called to initialize an element of an array.
1899  // If the constructor has one or more default arguments, the destruction of
1900  // every temporary created in a default argument expression is sequenced
1901  // before the construction of the next array element, if any.
1902 
1903  {
1904  RunCleanupsScope Scope(*this);
1905 
1906  // Evaluate the constructor and its arguments in a regular
1907  // partial-destroy cleanup.
1908  if (getLangOpts().Exceptions &&
1909  !ctor->getParent()->hasTrivialDestructor()) {
1910  Destroyer *destroyer = destroyCXXObject;
1911  pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
1912  *destroyer);
1913  }
1914 
1915  EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1916  /*Delegating=*/false, curAddr, E);
1917  }
1918 
1919  // Go to the next element.
1920  llvm::Value *next =
1921  Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1922  "arrayctor.next");
1923  cur->addIncoming(next, Builder.GetInsertBlock());
1924 
1925  // Check whether that's the end of the loop.
1926  llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1927  llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1928  Builder.CreateCondBr(done, contBB, loopBB);
1929 
1930  // Patch the earlier check to skip over the loop.
1931  if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1932 
1933  EmitBlock(contBB);
1934 }
1935 
1937  Address addr,
1938  QualType type) {
1939  const RecordType *rtype = type->castAs<RecordType>();
1940  const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1941  const CXXDestructorDecl *dtor = record->getDestructor();
1942  assert(!dtor->isTrivial());
1943  CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1944  /*Delegating=*/false, addr);
1945 }
1946 
1948  CXXCtorType Type,
1949  bool ForVirtualBase,
1950  bool Delegating, Address This,
1951  const CXXConstructExpr *E) {
1952  CallArgList Args;
1953 
1954  // Push the this ptr.
1955  Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
1956 
1957  // If this is a trivial constructor, emit a memcpy now before we lose
1958  // the alignment information on the argument.
1959  // FIXME: It would be better to preserve alignment information into CallArg.
1961  assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1962 
1963  const Expr *Arg = E->getArg(0);
1964  QualType SrcTy = Arg->getType();
1965  Address Src = EmitLValue(Arg).getAddress();
1966  QualType DestTy = getContext().getTypeDeclType(D->getParent());
1967  EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
1968  return;
1969  }
1970 
1971  // Add the rest of the user-supplied arguments.
1972  const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1976  EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
1977  /*ParamsToSkip*/ 0, Order);
1978 
1979  EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
1980 }
1981 
1983  const CXXConstructorDecl *Ctor,
1984  CXXCtorType Type, CallArgList &Args) {
1985  // We can't forward a variadic call.
1986  if (Ctor->isVariadic())
1987  return false;
1988 
1990  // If the parameters are callee-cleanup, it's not safe to forward.
1991  for (auto *P : Ctor->parameters())
1992  if (P->getType().isDestructedType())
1993  return false;
1994 
1995  // Likewise if they're inalloca.
1996  const CGFunctionInfo &Info =
1997  CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
1998  if (Info.usesInAlloca())
1999  return false;
2000  }
2001 
2002  // Anything else should be OK.
2003  return true;
2004 }
2005 
2007  CXXCtorType Type,
2008  bool ForVirtualBase,
2009  bool Delegating,
2010  Address This,
2011  CallArgList &Args) {
2012  const CXXRecordDecl *ClassDecl = D->getParent();
2013 
2014  // C++11 [class.mfct.non-static]p2:
2015  // If a non-static member function of a class X is called for an object that
2016  // is not of type X, or of a type derived from X, the behavior is undefined.
2017  // FIXME: Provide a source location here.
2019  This.getPointer(), getContext().getRecordType(ClassDecl));
2020 
2021  if (D->isTrivial() && D->isDefaultConstructor()) {
2022  assert(Args.size() == 1 && "trivial default ctor with args");
2023  return;
2024  }
2025 
2026  // If this is a trivial constructor, just emit what's needed. If this is a
2027  // union copy constructor, we must emit a memcpy, because the AST does not
2028  // model that copy.
2030  assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
2031 
2032  QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
2033  Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
2034  QualType DestTy = getContext().getTypeDeclType(ClassDecl);
2035  EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
2036  return;
2037  }
2038 
2039  bool PassPrototypeArgs = true;
2040  // Check whether we can actually emit the constructor before trying to do so.
2041  if (auto Inherited = D->getInheritedConstructor()) {
2042  PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
2043  if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
2044  EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
2045  Delegating, Args);
2046  return;
2047  }
2048  }
2049 
2050  // Insert any ABI-specific implicit constructor arguments.
2051  CGCXXABI::AddedStructorArgs ExtraArgs =
2052  CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
2053  Delegating, Args);
2054 
2055  // Emit the call.
2056  llvm::Constant *CalleePtr =
2059  Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
2060  CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
2061  EmitCall(Info, Callee, ReturnValueSlot(), Args);
2062 
2063  // Generate vtable assumptions if we're constructing a complete object
2064  // with a vtable. We don't do this for base subobjects for two reasons:
2065  // first, it's incorrect for classes with virtual bases, and second, we're
2066  // about to overwrite the vptrs anyway.
2067  // We also have to make sure if we can refer to vtable:
2068  // - Otherwise we can refer to vtable if it's safe to speculatively emit.
2069  // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
2070  // sure that definition of vtable is not hidden,
2071  // then we are always safe to refer to it.
2072  // FIXME: It looks like InstCombine is very inefficient on dealing with
2073  // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
2074  if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2075  ClassDecl->isDynamicClass() && Type != Ctor_Base &&
2076  CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
2077  CGM.getCodeGenOpts().StrictVTablePointers)
2078  EmitVTableAssumptionLoads(ClassDecl, This);
2079 }
2080 
2082  const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
2083  bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
2084  CallArgList Args;
2085  CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
2086  /*NeedsCopy=*/false);
2087 
2088  // Forward the parameters.
2089  if (InheritedFromVBase &&
2091  // Nothing to do; this construction is not responsible for constructing
2092  // the base class containing the inherited constructor.
2093  // FIXME: Can we just pass undef's for the remaining arguments if we don't
2094  // have constructor variants?
2095  Args.push_back(ThisArg);
2096  } else if (!CXXInheritedCtorInitExprArgs.empty()) {
2097  // The inheriting constructor was inlined; just inject its arguments.
2098  assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
2099  "wrong number of parameters for inherited constructor call");
2100  Args = CXXInheritedCtorInitExprArgs;
2101  Args[0] = ThisArg;
2102  } else {
2103  // The inheriting constructor was not inlined. Emit delegating arguments.
2104  Args.push_back(ThisArg);
2105  const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
2106  assert(OuterCtor->getNumParams() == D->getNumParams());
2107  assert(!OuterCtor->isVariadic() && "should have been inlined");
2108 
2109  for (const auto *Param : OuterCtor->parameters()) {
2110  assert(getContext().hasSameUnqualifiedType(
2111  OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
2112  Param->getType()));
2113  EmitDelegateCallArg(Args, Param, E->getLocation());
2114 
2115  // Forward __attribute__(pass_object_size).
2116  if (Param->hasAttr<PassObjectSizeAttr>()) {
2117  auto *POSParam = SizeArguments[Param];
2118  assert(POSParam && "missing pass_object_size value for forwarding");
2119  EmitDelegateCallArg(Args, POSParam, E->getLocation());
2120  }
2121  }
2122  }
2123 
2124  EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
2125  This, Args);
2126 }
2127 
2129  const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
2130  bool Delegating, CallArgList &Args) {
2131  GlobalDecl GD(Ctor, CtorType);
2133  ApplyInlineDebugLocation DebugScope(*this, GD);
2134 
2135  // Save the arguments to be passed to the inherited constructor.
2136  CXXInheritedCtorInitExprArgs = Args;
2137 
2138  FunctionArgList Params;
2139  QualType RetType = BuildFunctionArgList(CurGD, Params);
2140  FnRetTy = RetType;
2141 
2142  // Insert any ABI-specific implicit constructor arguments.
2143  CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
2144  ForVirtualBase, Delegating, Args);
2145 
2146  // Emit a simplified prolog. We only need to emit the implicit params.
2147  assert(Args.size() >= Params.size() && "too few arguments for call");
2148  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2149  if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
2150  const RValue &RV = Args[I].RV;
2151  assert(!RV.isComplex() && "complex indirect params not supported");
2152  ParamValue Val = RV.isScalar()
2155  EmitParmDecl(*Params[I], Val, I + 1);
2156  }
2157  }
2158 
2159  // Create a return value slot if the ABI implementation wants one.
2160  // FIXME: This is dumb, we should ask the ABI not to try to set the return
2161  // value instead.
2162  if (!RetType->isVoidType())
2163  ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
2164 
2166  CXXThisValue = CXXABIThisValue;
2167 
2168  // Directly emit the constructor initializers.
2169  EmitCtorPrologue(Ctor, CtorType, Params);
2170 }
2171 
2173  llvm::Value *VTableGlobal =
2175  if (!VTableGlobal)
2176  return;
2177 
2178  // We can just use the base offset in the complete class.
2179  CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
2180 
2181  if (!NonVirtualOffset.isZero())
2182  This =
2183  ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
2184  Vptr.VTableClass, Vptr.NearestVBase);
2185 
2186  llvm::Value *VPtrValue =
2187  GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
2188  llvm::Value *Cmp =
2189  Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
2190  Builder.CreateAssumption(Cmp);
2191 }
2192 
2194  Address This) {
2195  if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
2196  for (const VPtr &Vptr : getVTablePointers(ClassDecl))
2197  EmitVTableAssumptionLoad(Vptr, This);
2198 }
2199 
2200 void
2202  Address This, Address Src,
2203  const CXXConstructExpr *E) {
2204  const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
2205 
2206  CallArgList Args;
2207 
2208  // Push the this ptr.
2209  Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
2210 
2211  // Push the src ptr.
2212  QualType QT = *(FPT->param_type_begin());
2213  llvm::Type *t = CGM.getTypes().ConvertType(QT);
2214  Src = Builder.CreateBitCast(Src, t);
2215  Args.add(RValue::get(Src.getPointer()), QT);
2216 
2217  // Skip over first argument (Src).
2218  EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
2219  /*ParamsToSkip*/ 1);
2220 
2221  EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
2222 }
2223 
2224 void
2226  CXXCtorType CtorType,
2227  const FunctionArgList &Args,
2228  SourceLocation Loc) {
2229  CallArgList DelegateArgs;
2230 
2231  FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
2232  assert(I != E && "no parameters to constructor");
2233 
2234  // this
2235  Address This = LoadCXXThisAddress();
2236  DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
2237  ++I;
2238 
2239  // FIXME: The location of the VTT parameter in the parameter list is
2240  // specific to the Itanium ABI and shouldn't be hardcoded here.
2242  assert(I != E && "cannot skip vtt parameter, already done with args");
2243  assert((*I)->getType()->isPointerType() &&
2244  "skipping parameter not of vtt type");
2245  ++I;
2246  }
2247 
2248  // Explicit arguments.
2249  for (; I != E; ++I) {
2250  const VarDecl *param = *I;
2251  // FIXME: per-argument source location
2252  EmitDelegateCallArg(DelegateArgs, param, Loc);
2253  }
2254 
2255  EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
2256  /*Delegating=*/true, This, DelegateArgs);
2257 }
2258 
2259 namespace {
2260  struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
2261  const CXXDestructorDecl *Dtor;
2262  Address Addr;
2263  CXXDtorType Type;
2264 
2265  CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
2266  CXXDtorType Type)
2267  : Dtor(D), Addr(Addr), Type(Type) {}
2268 
2269  void Emit(CodeGenFunction &CGF, Flags flags) override {
2270  CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
2271  /*Delegating=*/true, Addr);
2272  }
2273  };
2274 } // end anonymous namespace
2275 
2276 void
2278  const FunctionArgList &Args) {
2279  assert(Ctor->isDelegatingConstructor());
2280 
2281  Address ThisPtr = LoadCXXThisAddress();
2282 
2283  AggValueSlot AggSlot =
2284  AggValueSlot::forAddr(ThisPtr, Qualifiers(),
2288 
2289  EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
2290 
2291  const CXXRecordDecl *ClassDecl = Ctor->getParent();
2292  if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
2293  CXXDtorType Type =
2295 
2296  EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2297  ClassDecl->getDestructor(),
2298  ThisPtr, Type);
2299  }
2300 }
2301 
2303  CXXDtorType Type,
2304  bool ForVirtualBase,
2305  bool Delegating,
2306  Address This) {
2307  CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2308  Delegating, This);
2309 }
2310 
2311 namespace {
2312  struct CallLocalDtor final : EHScopeStack::Cleanup {
2313  const CXXDestructorDecl *Dtor;
2314  Address Addr;
2315 
2316  CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
2317  : Dtor(D), Addr(Addr) {}
2318 
2319  void Emit(CodeGenFunction &CGF, Flags flags) override {
2321  /*ForVirtualBase=*/false,
2322  /*Delegating=*/false, Addr);
2323  }
2324  };
2325 } // end anonymous namespace
2326 
2328  Address Addr) {
2329  EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
2330 }
2331 
2333  CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2334  if (!ClassDecl) return;
2335  if (ClassDecl->hasTrivialDestructor()) return;
2336 
2337  const CXXDestructorDecl *D = ClassDecl->getDestructor();
2338  assert(D && D->isUsed() && "destructor not marked as used!");
2339  PushDestructorCleanup(D, Addr);
2340 }
2341 
2343  // Compute the address point.
2344  llvm::Value *VTableAddressPoint =
2346  *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
2347 
2348  if (!VTableAddressPoint)
2349  return;
2350 
2351  // Compute where to store the address point.
2352  llvm::Value *VirtualOffset = nullptr;
2353  CharUnits NonVirtualOffset = CharUnits::Zero();
2354 
2355  if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
2356  // We need to use the virtual base offset offset because the virtual base
2357  // might have a different offset in the most derived class.
2358 
2359  VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
2360  *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
2361  NonVirtualOffset = Vptr.OffsetFromNearestVBase;
2362  } else {
2363  // We can just use the base offset in the complete class.
2364  NonVirtualOffset = Vptr.Base.getBaseOffset();
2365  }
2366 
2367  // Apply the offsets.
2368  Address VTableField = LoadCXXThisAddress();
2369 
2370  if (!NonVirtualOffset.isZero() || VirtualOffset)
2371  VTableField = ApplyNonVirtualAndVirtualOffset(
2372  *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
2373  Vptr.NearestVBase);
2374 
2375  // Finally, store the address point. Use the same LLVM types as the field to
2376  // support optimization.
2377  llvm::Type *VTablePtrTy =
2378  llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2379  ->getPointerTo()
2380  ->getPointerTo();
2381  VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2382  VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
2383 
2384  llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2386  if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2387  CGM.getCodeGenOpts().StrictVTablePointers)
2389 }
2390 
2393  CodeGenFunction::VPtrsVector VPtrsResult;
2394  VisitedVirtualBasesSetTy VBases;
2396  /*NearestVBase=*/nullptr,
2397  /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2398  /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
2399  VPtrsResult);
2400  return VPtrsResult;
2401 }
2402 
2404  const CXXRecordDecl *NearestVBase,
2405  CharUnits OffsetFromNearestVBase,
2406  bool BaseIsNonVirtualPrimaryBase,
2407  const CXXRecordDecl *VTableClass,
2408  VisitedVirtualBasesSetTy &VBases,
2409  VPtrsVector &Vptrs) {
2410  // If this base is a non-virtual primary base the address point has already
2411  // been set.
2412  if (!BaseIsNonVirtualPrimaryBase) {
2413  // Initialize the vtable pointer for this base.
2414  VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
2415  Vptrs.push_back(Vptr);
2416  }
2417 
2418  const CXXRecordDecl *RD = Base.getBase();
2419 
2420  // Traverse bases.
2421  for (const auto &I : RD->bases()) {
2422  CXXRecordDecl *BaseDecl
2423  = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2424 
2425  // Ignore classes without a vtable.
2426  if (!BaseDecl->isDynamicClass())
2427  continue;
2428 
2429  CharUnits BaseOffset;
2430  CharUnits BaseOffsetFromNearestVBase;
2431  bool BaseDeclIsNonVirtualPrimaryBase;
2432 
2433  if (I.isVirtual()) {
2434  // Check if we've visited this virtual base before.
2435  if (!VBases.insert(BaseDecl).second)
2436  continue;
2437 
2438  const ASTRecordLayout &Layout =
2439  getContext().getASTRecordLayout(VTableClass);
2440 
2441  BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2442  BaseOffsetFromNearestVBase = CharUnits::Zero();
2443  BaseDeclIsNonVirtualPrimaryBase = false;
2444  } else {
2445  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2446 
2447  BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2448  BaseOffsetFromNearestVBase =
2449  OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2450  BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2451  }
2452 
2454  BaseSubobject(BaseDecl, BaseOffset),
2455  I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
2456  BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
2457  }
2458 }
2459 
2461  // Ignore classes without a vtable.
2462  if (!RD->isDynamicClass())
2463  return;
2464 
2465  // Initialize the vtable pointers for this class and all of its bases.
2467  for (const VPtr &Vptr : getVTablePointers(RD))
2469 
2470  if (RD->getNumVBases())
2472 }
2473 
2475  llvm::Type *VTableTy,
2476  const CXXRecordDecl *RD) {
2477  Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
2478  llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2480 
2481  if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
2482  CGM.getCodeGenOpts().StrictVTablePointers)
2484 
2485  return VTable;
2486 }
2487 
2488 // If a class has a single non-virtual base and does not introduce or override
2489 // virtual member functions or fields, it will have the same layout as its base.
2490 // This function returns the least derived such class.
2491 //
2492 // Casting an instance of a base class to such a derived class is technically
2493 // undefined behavior, but it is a relatively common hack for introducing member
2494 // functions on class instances with specific properties (e.g. llvm::Operator)
2495 // that works under most compilers and should not have security implications, so
2496 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2497 static const CXXRecordDecl *
2499  if (!RD->field_empty())
2500  return RD;
2501 
2502  if (RD->getNumVBases() != 0)
2503  return RD;
2504 
2505  if (RD->getNumBases() != 1)
2506  return RD;
2507 
2508  for (const CXXMethodDecl *MD : RD->methods()) {
2509  if (MD->isVirtual()) {
2510  // Virtual member functions are only ok if they are implicit destructors
2511  // because the implicit destructor will have the same semantics as the
2512  // base class's destructor if no fields are added.
2513  if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2514  continue;
2515  return RD;
2516  }
2517  }
2518 
2520  RD->bases_begin()->getType()->getAsCXXRecordDecl());
2521 }
2522 
2524  llvm::Value *VTable,
2525  SourceLocation Loc) {
2526  if (CGM.getCodeGenOpts().WholeProgramVTables &&
2528  llvm::Metadata *MD =
2530  llvm::Value *TypeId =
2531  llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2532 
2533  llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2534  llvm::Value *TypeTest =
2535  Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2536  {CastedVTable, TypeId});
2537  Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
2538  }
2539 
2540  if (SanOpts.has(SanitizerKind::CFIVCall))
2542 }
2543 
2545  llvm::Value *VTable,
2546  CFITypeCheckKind TCK,
2547  SourceLocation Loc) {
2548  if (!SanOpts.has(SanitizerKind::CFICastStrict))
2550 
2551  EmitVTablePtrCheck(RD, VTable, TCK, Loc);
2552 }
2553 
2555  llvm::Value *Derived,
2556  bool MayBeNull,
2557  CFITypeCheckKind TCK,
2558  SourceLocation Loc) {
2559  if (!getLangOpts().CPlusPlus)
2560  return;
2561 
2562  auto *ClassTy = T->getAs<RecordType>();
2563  if (!ClassTy)
2564  return;
2565 
2566  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2567 
2568  if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2569  return;
2570 
2571  if (!SanOpts.has(SanitizerKind::CFICastStrict))
2572  ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2573 
2574  llvm::BasicBlock *ContBlock = nullptr;
2575 
2576  if (MayBeNull) {
2577  llvm::Value *DerivedNotNull =
2578  Builder.CreateIsNotNull(Derived, "cast.nonnull");
2579 
2580  llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2581  ContBlock = createBasicBlock("cast.cont");
2582 
2583  Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2584 
2585  EmitBlock(CheckBlock);
2586  }
2587 
2588  llvm::Value *VTable =
2589  GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
2590 
2591  EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
2592 
2593  if (MayBeNull) {
2594  Builder.CreateBr(ContBlock);
2595  EmitBlock(ContBlock);
2596  }
2597 }
2598 
2600  llvm::Value *VTable,
2601  CFITypeCheckKind TCK,
2602  SourceLocation Loc) {
2603  if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
2605  return;
2606 
2607  std::string TypeName = RD->getQualifiedNameAsString();
2608  if (getContext().getSanitizerBlacklist().isBlacklistedType(TypeName))
2609  return;
2610 
2611  SanitizerScope SanScope(this);
2612  llvm::SanitizerStatKind SSK;
2613  switch (TCK) {
2614  case CFITCK_VCall:
2615  SSK = llvm::SanStat_CFI_VCall;
2616  break;
2617  case CFITCK_NVCall:
2618  SSK = llvm::SanStat_CFI_NVCall;
2619  break;
2620  case CFITCK_DerivedCast:
2621  SSK = llvm::SanStat_CFI_DerivedCast;
2622  break;
2623  case CFITCK_UnrelatedCast:
2624  SSK = llvm::SanStat_CFI_UnrelatedCast;
2625  break;
2626  case CFITCK_ICall:
2627  llvm_unreachable("not expecting CFITCK_ICall");
2628  }
2630 
2631  llvm::Metadata *MD =
2633  llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
2634 
2635  llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2636  llvm::Value *TypeTest = Builder.CreateCall(
2637  CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
2638 
2639  SanitizerMask M;
2640  switch (TCK) {
2641  case CFITCK_VCall:
2642  M = SanitizerKind::CFIVCall;
2643  break;
2644  case CFITCK_NVCall:
2645  M = SanitizerKind::CFINVCall;
2646  break;
2647  case CFITCK_DerivedCast:
2648  M = SanitizerKind::CFIDerivedCast;
2649  break;
2650  case CFITCK_UnrelatedCast:
2651  M = SanitizerKind::CFIUnrelatedCast;
2652  break;
2653  case CFITCK_ICall:
2654  llvm_unreachable("not expecting CFITCK_ICall");
2655  }
2656 
2657  llvm::Constant *StaticData[] = {
2658  llvm::ConstantInt::get(Int8Ty, TCK),
2661  };
2662 
2663  auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
2664  if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
2665  EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
2666  return;
2667  }
2668 
2669  if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
2670  EmitTrapCheck(TypeTest);
2671  return;
2672  }
2673 
2674  llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2675  CGM.getLLVMContext(),
2676  llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2677  llvm::Value *ValidVtable = Builder.CreateCall(
2678  CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
2679  EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
2680  StaticData, {CastedVTable, ValidVtable});
2681 }
2682 
2684  if (!CGM.getCodeGenOpts().WholeProgramVTables ||
2685  !SanOpts.has(SanitizerKind::CFIVCall) ||
2686  !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
2688  return false;
2689 
2690  std::string TypeName = RD->getQualifiedNameAsString();
2691  return !getContext().getSanitizerBlacklist().isBlacklistedType(TypeName);
2692 }
2693 
2695  const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
2696  SanitizerScope SanScope(this);
2697 
2698  EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
2699 
2700  llvm::Metadata *MD =
2702  llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
2703 
2704  llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2705  llvm::Value *CheckedLoad = Builder.CreateCall(
2706  CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
2707  {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
2708  TypeId});
2709  llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
2710 
2711  EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
2712  SanitizerHandler::CFICheckFail, nullptr, nullptr);
2713 
2714  return Builder.CreateBitCast(
2715  Builder.CreateExtractValue(CheckedLoad, 0),
2716  cast<llvm::PointerType>(VTable->getType())->getElementType());
2717 }
2718 
2720  const CXXMethodDecl *callOperator,
2721  CallArgList &callArgs) {
2722  // Get the address of the call operator.
2723  const CGFunctionInfo &calleeFnInfo =
2724  CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2725  llvm::Constant *calleePtr =
2726  CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2727  CGM.getTypes().GetFunctionType(calleeFnInfo));
2728 
2729  // Prepare the return slot.
2730  const FunctionProtoType *FPT =
2731  callOperator->getType()->castAs<FunctionProtoType>();
2732  QualType resultType = FPT->getReturnType();
2733  ReturnValueSlot returnSlot;
2734  if (!resultType->isVoidType() &&
2735  calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2736  !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2737  returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2738 
2739  // We don't need to separately arrange the call arguments because
2740  // the call can't be variadic anyway --- it's impossible to forward
2741  // variadic arguments.
2742 
2743  // Now emit our call.
2744  auto callee = CGCallee::forDirect(calleePtr, callOperator);
2745  RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
2746 
2747  // If necessary, copy the returned value into the slot.
2748  if (!resultType->isVoidType() && returnSlot.isNull())
2749  EmitReturnOfRValue(RV, resultType);
2750  else
2752 }
2753 
2755  const BlockDecl *BD = BlockInfo->getBlockDecl();
2756  const VarDecl *variable = BD->capture_begin()->getVariable();
2757  const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2758 
2759  // Start building arguments for forwarding call
2760  CallArgList CallArgs;
2761 
2762  QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2763  Address ThisPtr = GetAddrOfBlockDecl(variable, false);
2764  CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
2765 
2766  // Add the rest of the parameters.
2767  for (auto param : BD->parameters())
2768  EmitDelegateCallArg(CallArgs, param, param->getLocStart());
2769 
2770  assert(!Lambda->isGenericLambda() &&
2771  "generic lambda interconversion to block not implemented");
2773 }
2774 
2776  if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2777  // FIXME: Making this work correctly is nasty because it requires either
2778  // cloning the body of the call operator or making the call operator forward.
2779  CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2780  return;
2781  }
2782 
2783  EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
2784 }
2785 
2787  const CXXRecordDecl *Lambda = MD->getParent();
2788 
2789  // Start building arguments for forwarding call
2790  CallArgList CallArgs;
2791 
2792  QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2793  llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2794  CallArgs.add(RValue::get(ThisPtr), ThisType);
2795 
2796  // Add the rest of the parameters.
2797  for (auto Param : MD->parameters())
2798  EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2799 
2800  const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2801  // For a generic lambda, find the corresponding call operator specialization
2802  // to which the call to the static-invoker shall be forwarded.
2803  if (Lambda->isGenericLambda()) {
2804  assert(MD->isFunctionTemplateSpecialization());
2806  FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2807  void *InsertPos = nullptr;
2808  FunctionDecl *CorrespondingCallOpSpecialization =
2809  CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2810  assert(CorrespondingCallOpSpecialization);
2811  CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2812  }
2813  EmitForwardingCallToLambda(CallOp, CallArgs);
2814 }
2815 
2817  if (MD->isVariadic()) {
2818  // FIXME: Making this work correctly is nasty because it requires either
2819  // cloning the body of the call operator or making the call operator forward.
2820  CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2821  return;
2822  }
2823 
2825 }
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
void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type)
EnterDtorCleanups - Enter the cleanups necessary to complete the given phase of destruction for a des...
Definition: CGClass.cpp:1708
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
int64_t QuantityType
Definition: CharUnits.h:40
void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, CXXCtorType CtorType, const FunctionArgList &Args, SourceLocation Loc)
Definition: CGClass.cpp:2225
void DecorateInstructionWithInvariantGroup(llvm::Instruction *I, const CXXRecordDecl *RD)
Adds !invariant.barrier !tag to instruction.
Complete object ctor.
Definition: ABI.h:26
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition: CGDecl.cpp:1451
A (possibly-)qualified type.
Definition: Type.h:616
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:212
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2005
void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, FunctionArgList &Args)
EmitCtorPrologue - This routine generates necessary code to initialize base classes and non-static da...
Definition: CGClass.cpp:1239
base_class_range bases()
Definition: DeclCXX.h:737
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:173
CanQualType getReturnType() const
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2434
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
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:258
CXXCtorType getCtorType() const
Definition: GlobalDecl.h:64
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler...
Definition: CGExpr.cpp:2513
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
llvm::LLVMContext & getLLVMContext()
method_range methods() const
Definition: DeclCXX.h:779
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, IsZeroed_t isZeroed=IsNotZeroed)
Definition: CGValue.h:539
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:167
CharUnits getClassPointerAlignment(const CXXRecordDecl *CD)
Returns the assumed alignment of an opaque pointer to the given class.
Definition: CGClass.cpp:36
Stmt - This represents one statement.
Definition: Stmt.h:60
const TargetInfo & getTarget() const
Address GetAddressOfDirectBaseInCompleteClass(Address Value, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, bool BaseIsVirtual)
GetAddressOfBaseOfCompleteClass - Convert the given pointer to a complete class to the given direct b...
Definition: CGClass.cpp:197
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
Definition: CGClass.cpp:372
Checking the 'this' pointer for a constructor call.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
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
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Defines the C++ template declaration subclasses.
StringRef P
const llvm::DataLayout & getDataLayout() const
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition: StoreRef.h:26
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D)
Definition: CGClass.cpp:569
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
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition: CGExpr.cpp:571
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:227
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1177
void ForceCleanup(std::initializer_list< llvm::Value ** > ValuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, bool forPointeeType=false)
bool HasHiddenLTOVisibility(const CXXRecordDecl *RD)
Returns whether the given record has hidden LTO visibility and therefore may participate in (single-m...
Definition: CGVTables.cpp:912
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
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclBase.h:403
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2329
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:1772
! Language semantics require left-to-right evaluation.
virtual llvm::BasicBlock * EmitCtorCompleteObjectHandler(CodeGenFunction &CGF, const CXXRecordDecl *RD)
Definition: CGCXXABI.cpp:278
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:2766
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:52
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2299
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
Definition: TargetCXXABI.h:216
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1924
llvm::Value * GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, bool Delegating)
GetVTTParameter - Return the VTT parameter that should be passed to a base constructor/destructor wit...
Definition: CGClass.cpp:429
QualType getThisType(ASTContext &C) const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:1845
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
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
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified...
Definition: CGExpr.cpp:2995
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2029
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:1793
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
Definition: CGClass.cpp:1498
bool isVoidType() const
Definition: Type.h:5906
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2171
The collection of all-type qualifiers we support.
Definition: Type.h:118
static const CXXRecordDecl * LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD)
Definition: CGClass.cpp:2498
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2230
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
emitDestroy - Immediately perform the destruction of the given object.
Definition: CGDecl.cpp:1527
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask >> Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will call a handler function in a sanitizer runtime with the provided argum...
Definition: CGExpr.cpp:2719
bool isVolatileQualified() const
Definition: CGValue.h:271
bool hasAttr() const
Definition: DeclBase.h:521
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3314
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
EmitExprAsInit - Emits the code necessary to initialize a location in memory with the given initializ...
Definition: CGDecl.cpp:1316
bool isDelegatingConstructor() const
Determine whether this constructor is a delegating constructor.
Definition: DeclCXX.h:2443
llvm::SmallPtrSet< const CXXRecordDecl *, 4 > VisitedVirtualBasesSetTy
void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, Address This, Address Src, const CXXConstructExpr *E)
Definition: CGClass.cpp:2201
bool isReferenceType() const
Definition: Type.h:5721
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
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2366
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2960
bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD)
Returns whether we should perform a type checked load when loading a virtual function for virtual cal...
Definition: CGClass.cpp:2683
void pushEHDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushEHDestroy - Push the standard destructor for the given type as an EH-only cleanup.
Definition: CGDecl.cpp:1466
uint64_t getSubVTTIndex(const CXXRecordDecl *RD, BaseSubobject Base)
getSubVTTIndex - Return the index of the sub-VTT for the base class of the given record decl...
Definition: CGVTT.cpp:130
void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, CFITypeCheckKind TCK, SourceLocation Loc)
EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for RD using llvm...
Definition: CGClass.cpp:2599
virtual bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass)=0
Checks if ABI requires to initialize vptrs for given dynamic class.
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:449
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
CleanupKind getCleanupKind(QualType::DestructionKind kind)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1295
const Decl * getDecl() const
Definition: GlobalDecl.h:62
void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, Address This, const CXXConstructExpr *E)
Definition: CGClass.cpp:1947
void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD)
Definition: CGClass.cpp:2786
void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init)
Definition: CGClass.cpp:655
CharUnits getDynamicOffsetAlignment(CharUnits ActualAlign, const CXXRecordDecl *Class, CharUnits ExpectedTargetAlign)
Given a class pointer with an actual known alignment, and the expected alignment of an object at a dy...
Definition: CGClass.cpp:70
Address CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
Definition: CGExpr.cpp:118
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, bool ForVirtualBase, Address This, bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E)
Emit a call to a constructor inherited from a base class, passing the current constructor's arguments...
Definition: CGClass.cpp:2081
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
static bool hasScalarEvaluationKind(QualType T)
Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef)
Definition: CGBlocks.cpp:1064
virtual llvm::Value * EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr, const MemberPointerType *MPT)
Calculate an l-value from an object and a data member pointer.
Definition: CGCXXABI.cpp:65
Base object ctor.
Definition: ABI.h:27
const LangOptions & getLangOpts() const
Definition: ASTContext.h:659
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:537
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2251
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 EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, llvm::Value *VTable, SourceLocation Loc)
If whole-program virtual table optimization is enabled, emit an assumption that VTable is a member of...
Definition: CGClass.cpp:2523
uint32_t Offset
Definition: CacheTokens.cpp:43
QualType getReturnType() const
Definition: Type.h:3065
virtual llvm::Value * GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl, const CXXRecordDecl *BaseClassDecl)=0
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
bool isDefaulted() const
Whether this function is defaulted per C++0x.
Definition: Decl.h:1914
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
field_range fields() const
Definition: Decl.h:3483
Deleting dtor.
Definition: ABI.h:35
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...
const CGFunctionInfo & arrangeCXXConstructorCall(const CallArgList &Args, const CXXConstructorDecl *D, CXXCtorType CtorKind, unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs, bool PassProtoArgs=true)
Arrange a call to a C++ method, passing the given arguments.
Definition: CGCall.cpp:378
RecordDecl * getDecl() const
Definition: Type.h:3793
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:252
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, LValueBaseInfo *BaseInfo=nullptr)
Emit the address of a field using a member data pointer.
Definition: CGClass.cpp:129
const SanitizerBlacklist & getSanitizerBlacklist() const
Definition: ASTContext.h:661
virtual bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const =0
Determine whether it's possible to emit a vtable for RD, even though we do not know that the vtable h...
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2555
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
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...
const Type * getBaseClass() const
If this is a base class initializer, returns the type of the base class.
Definition: DeclCXX.cpp:1934
void EmitStmt(const Stmt *S)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:48
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:177
base_class_iterator bases_begin()
Definition: DeclCXX.h:744
virtual void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This)=0
Emit the destructor call.
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.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3193
Checking the operand of a cast to a virtual base object.
detail::InMemoryDirectory::const_iterator I
static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init)
Definition: CGClass.cpp:518
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2110
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) const
init_iterator init_begin()
Retrieve an iterator to the first initializer.
Definition: DeclCXX.h:2386
QualType getType() const
Definition: Decl.h:589
Represents the this expression in C++.
Definition: ExprCXX.h:888
LValue EmitLValueForField(LValue Base, const FieldDecl *Field)
Definition: CGExpr.cpp:3615
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1242
llvm::Constant * CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false)
Create a new runtime function with the specified type and name.
bool isUnion() const
Definition: Decl.h:3028
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:575
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3129
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
const CodeGen::CGBlockInfo * BlockInfo
const TargetInfo & getTarget() const
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
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
bool hasConstructorVariants() const
Does this ABI have different entrypoints for complete-object and base-subobject constructors?
Definition: TargetCXXABI.h:222
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1095
ASTContext * Context
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
Definition: CGCall.cpp:3002
Address getBitFieldAddress() const
Definition: CGValue.h:374
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF, CXXCtorInitializer *MemberInit, LValue &LHS)
Definition: CGClass.cpp:586
const CXXRecordDecl * getBase() const
getBase - Returns the base class declaration.
Definition: BaseSubobject.h:40
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:34
bool hasVolatile() const
Definition: Type.h:244
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
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, llvm::MDNode *TBAAInfo, bool ConvertTypeToTag=true)
Decorate the instruction with a TBAA tag.
static TypeEvaluationKind getEvaluationKind(QualType T)
hasAggregateLLVMType - Return true if the specified AST type will map into an aggregate LLVM type or ...
InheritedConstructor getInheritedConstructor() const
Get the constructor that this inheriting constructor is based on.
Definition: DeclCXX.h:2520
CXXDtorType
C++ destructor types.
Definition: ABI.h:34
llvm::Value * getPointer() const
Definition: Address.h:38
const Type * getTypeForDecl() const
Definition: Decl.h:2663
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
Definition: Decl.h:3557
Expr - This represents one expression.
Definition: Expr.h:105
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:69
CGCXXABI & getCXXABI() const
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition: ExprCXX.h:1255
static ParamValue forIndirect(Address addr)
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.
void EmitVTableAssumptionLoad(const VPtr &vptr, Address This)
Emit assumption that vptr load == global vtable.
Definition: CGClass.cpp:2172
bool isVirtual() const
Definition: DeclCXX.h:1947
bool usesInAlloca() const
Return true if this function uses inalloca arguments.
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
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:2613
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:125
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2551
capture_const_iterator capture_begin() const
Definition: Decl.h:3684
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2088
arg_range arguments()
Definition: ExprCXX.h:1286
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:219
ASTContext & getContext() const
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:207
void EmitAsanPrologueOrEpilogue(bool Prologue)
Definition: CGClass.cpp:740
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
llvm::LLVMContext & getLLVMContext()
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Base object dtor.
Definition: ABI.h:37
Expr * getSubExpr() const
Definition: Expr.h:1741
bool isIndirectMemberInitializer() const
Definition: DeclCXX.h:2183
void EmitConstructorBody(FunctionArgList &Args)
EmitConstructorBody - Emits the body of the current constructor.
Definition: CGClass.cpp:803
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
A scoped helper to set the current debug location to an inlined location.
Definition: CGDebugInfo.h:672
void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, CallArgList &CallArgs)
Definition: CGClass.cpp:2719
void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr, QualType DestTy, QualType SrcTy)
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1714
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:3644
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1100
void EmitLambdaToBlockPointerBody(FunctionArgList &Args)
Definition: CGClass.cpp:2775
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=None)
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:731
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
The COMDAT used for dtors.
Definition: ABI.h:38
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:29
bool hasObjCLifetime() const
Definition: Type.h:308
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
The l-value was considered opaque, so the alignment was determined from a type.
static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF, const CXXDestructorDecl *Dtor)
CanSkipVTablePointerInitialization - Check whether we need to initialize any vtable pointers before c...
Definition: CGClass.cpp:1371
Stmt * getBody(const FunctionDecl *&Definition) const
getBody - Retrieve the body (definition) of the function.
Definition: Decl.cpp:2597
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:59
Enumerates target-specific builtins in their own namespaces within namespace clang.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:142
#define false
Definition: stdbool.h:33
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1340
bool isSimple() const
Definition: CGValue.h:265
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:3959
virtual bool NeedsVTTParameter(GlobalDecl GD)
Return whether the given global decl needs a VTT parameter.
Definition: CGCXXABI.cpp:287
void PushDestructorCleanup(QualType T, Address Addr)
PushDestructorCleanup - Push a cleanup to call the complete-object destructor of an object of the giv...
Definition: CGClass.cpp:2332
ASTContext & getContext() const
Encodes a location in the source.
body_range body()
Definition: Stmt.h:605
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2878
bool isBlacklistedType(StringRef MangledTypeName, StringRef Category=StringRef()) const
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:204
FieldDecl * getAnyMember() const
Definition: DeclCXX.h:2243
void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This)
Emit assumption load for all bases.
Definition: CGClass.cpp:2193
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
Definition: CGCall.cpp:278
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:136
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
Checking the operand of a cast to a base object.
An aggregate value slot.
Definition: CGValue.h:456
init_iterator init_end()
Retrieve an iterator past the last initializer.
Definition: DeclCXX.h:2394
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:617
llvm::GlobalVariable * GetAddrOfVTT(const CXXRecordDecl *RD)
GetAddrOfVTT - Get the address of the VTT for the given record decl.
Definition: CGVTT.cpp:106
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
virtual size_t getSrcArgforCopyCtor(const CXXConstructorDecl *, FunctionArgList &Args) const =0
SourceLocation getSourceLocation() const
Determine the source location of the initializer.
Definition: DeclCXX.cpp:1941
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2066
bool isBaseVirtual() const
Returns whether the base is virtual or not.
Definition: DeclCXX.h:2224
SanitizerSet SanOpts
Sanitizers enabled for this function.
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2235
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
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
const CodeGenOptions & getCodeGenOpts() const
An aligned address.
Definition: Address.h:25
const LangOptions & getLangOpts() const
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2804
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6105
All available information about a concrete callee.
Definition: CGCall.h:66
Complete object dtor.
Definition: ABI.h:36
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2823
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Definition: CGDecl.cpp:1771
static ParamValue forDirect(llvm::Value *value)
bool isBitField() const
Definition: CGValue.h:267
void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase, bool Delegating, CallArgList &Args)
Emit a call to an inheriting constructor (that is, one that invokes a constructor inherited from a ba...
Definition: CGClass.cpp:2128
static void EmitBaseInitializer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, CXXCtorInitializer *BaseInit, CXXCtorType CtorType)
Definition: CGClass.cpp:524
bool isDynamicClass() const
Definition: DeclCXX.h:715
Opcode getOpcode() const
Definition: Expr.h:1738
virtual bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr)=0
Checks if ABI requires extra virtual offset for vtable field.
CXXCtorType
C++ constructor types.
Definition: ABI.h:25
SourceLocation getLocation() const LLVM_READONLY
Definition: ExprCXX.h:1389
void InitializeVTablePointer(const VPtr &vptr)
Initialize the vtable pointer of the given subobject.
Definition: CGClass.cpp:2342
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
FunctionArgList - Type for representing both the decl and type of parameters to a function...
Definition: CGCall.h:276
bool isAnonymousStructOrUnion() const
isAnonymousStructOrUnion - Whether this is an anonymous struct or union.
Definition: Decl.h:3421
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
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
uint64_t SanitizerMask
Definition: Sanitizers.h:24
bool isScalar() const
Definition: CGValue.h:51
void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
Definition: CGClass.cpp:2554
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
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
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:58
static bool canEmitDelegateCallArgs(CodeGenFunction &CGF, const CXXConstructorDecl *Ctor, CXXCtorType Type, CallArgList &Args)
Definition: CGClass.cpp:1982
A scope within which we are constructing the fields of an object which might use a CXXDefaultInitExpr...
IndirectFieldDecl - An instance of this class is created to represent a field injected from an anonym...
Definition: Decl.h:2594
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, const FunctionArgList &Args)
Definition: CGClass.cpp:2277
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required...
Definition: DeclBase.cpp:367
void InitializeVTablePointers(const CXXRecordDecl *ClassDecl)
Definition: CGClass.cpp:2460
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
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2087
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2238
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
unsigned getNumArgs() const
Definition: ExprCXX.h:1300
CharUnits getVBaseAlignment(CharUnits DerivedAlign, const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the assumed alignment of a virtual base of a class.
Definition: CGClass.cpp:55
bool field_empty() const
Definition: Decl.h:3492
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type. ...
Definition: CGExprAgg.cpp:1539
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5662
JumpDest ReturnBlock
ReturnBlock - Unified return block.
virtual void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF, const CXXRecordDecl *RD)
Emit the code to initialize hidden members required to handle virtual inheritance, if needed by the ABI.
Definition: CGCXXABI.h:288
virtual llvm::Constant * getVTableAddressPoint(BaseSubobject Base, const CXXRecordDecl *VTableClass)=0
Get the address point of the vtable for the given base subobject.
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
StructorType getFromCtorType(CXXCtorType T)
Definition: CodeGenTypes.h:77
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2105
void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD)
Definition: CGClass.cpp:2816
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:50
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
llvm::Constant * GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd)
Returns the offset from a derived class to a class.
Definition: CGClass.cpp:175
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1303
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.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1548
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:1909
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:1928
bool isComplex() const
Definition: CGValue.h:52
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:436
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Represents a base class of a C++ class.
Definition: DeclCXX.h:158
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
llvm::Value * LoadCXXVTT()
LoadCXXVTT - Load the VTT parameter to base constructors/destructors have virtual bases...
unsigned getFieldIndex() const
getFieldIndex - Returns the index of this field within its record, as appropriate for passing to ASTR...
Definition: Decl.cpp:3605
bool isAnyMemberInitializer() const
Definition: DeclCXX.h:2179
void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body)
virtual AddedStructorArgs addImplicitConstructorArgs(CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type, bool ForVirtualBase, bool Delegating, CallArgList &Args)=0
Add any ABI-specific implicit arguments needed to call a constructor.
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1451
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2009
VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass)
Definition: CGClass.cpp:2392
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
A template argument list.
Definition: DeclTemplate.h:195
virtual llvm::Value * getVTableAddressPointInStructor(CodeGenFunction &CGF, const CXXRecordDecl *RD, BaseSubobject Base, const CXXRecordDecl *NearestVBase)=0
Get the address point of the vtable for the given base subobject while building a constructor or a de...
const Type * getClass() const
Definition: Type.h:2475
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2378
static void EmitMemberInitializer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, CXXCtorInitializer *MemberInit, const CXXConstructorDecl *Constructor, FunctionArgList &Args)
Definition: CGClass.cpp:600
Represents a C++ struct/union/class.
Definition: DeclCXX.h:267
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:861
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
llvm::Type * ConvertType(QualType T)
static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor)
Checks whether the given constructor is a valid subject for the complete-to-base constructor delegati...
Definition: CGClass.cpp:692
LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo=LValueBaseInfo(AlignmentSource::Type))
! No language constraints on evaluation order.
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1082
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EmitTrapCheck(llvm::Value *Checked)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it...
Definition: CGExpr.cpp:2975
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:271
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:70
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:245
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
CharUnits computeNonVirtualBaseClassOffset(const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start, CastExpr::path_const_iterator End)
Definition: CGClass.cpp:147
static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit)
Definition: CGClass.cpp:1230
const FunctionDecl * getOperatorDelete() const
Definition: DeclCXX.h:2576
static Address ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr, CharUnits nonVirtualOffset, llvm::Value *virtualOffset, const CXXRecordDecl *derivedClass, const CXXRecordDecl *nearestVBase)
Definition: CGClass.cpp:225
Struct with all informations about dynamic [sub]class needed to set vptr.
static RValue get(llvm::Value *V)
Definition: CGValue.h:85
void EmitDestructorBody(FunctionArgList &Args)
EmitDestructorBody - Emits the body of the current destructor.
Definition: CGClass.cpp:1389
void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant * > StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false. ...
Definition: CGExpr.cpp:2827
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2375
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Definition: CGCleanup.cpp:1034
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition: CGExpr.cpp:2591
CodeGenVTables & getVTables()
CharUnits getBaseOffset() const
getBaseOffset - Returns the base class offset.
Definition: BaseSubobject.h:43
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CodeGenTypes & getTypes() const
LValue - This represents an lvalue references.
Definition: CGValue.h:171
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:752
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:147
static bool HasTrivialDestructorBody(ASTContext &Context, const CXXRecordDecl *BaseClassDecl, const CXXRecordDecl *MostDerivedClassDecl)
Definition: CGClass.cpp:1308
Notes how many arguments were added to the beginning (Prefix) and ending (Suffix) of an arg list...
Definition: CGCXXABI.h:299
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1235
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
bool hasTrivialBody() const
hasTrivialBody - Returns whether the function has a trivial body that does not require any specific c...
Definition: Decl.cpp:2572
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition: CGClass.cpp:265
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:182
void PopCleanupBlock(bool FallThroughIsBranchThrough=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
Definition: CGCleanup.cpp:640
base_class_range vbases()
Definition: DeclCXX.h:754
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.
Declaration of a template function.
Definition: DeclTemplate.h:939
static bool FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field)
Definition: CGClass.cpp:1351
llvm::Value * EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset)
Emit a type checked load from the given vtable.
Definition: CGClass.cpp:2694
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
Structure with information about how a bitfield should be accessed.
llvm::MDNode * getTBAAInfoForVTablePtr()
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5516
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1519