CGClass.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
  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. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/EvaluatedExprVisitor.h"
  17. #include "clang/AST/RecordLayout.h"
  18. #include "clang/AST/StmtCXX.h"
  19. #include "clang/Frontend/CodeGenOptions.h"
  20. using namespace clang;
  21. using namespace CodeGen;
  22. static CharUnits
  23. ComputeNonVirtualBaseClassOffset(ASTContext &Context,
  24. const CXXRecordDecl *DerivedClass,
  25. CastExpr::path_const_iterator Start,
  26. CastExpr::path_const_iterator End) {
  27. CharUnits Offset = CharUnits::Zero();
  28. const CXXRecordDecl *RD = DerivedClass;
  29. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  30. const CXXBaseSpecifier *Base = *I;
  31. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  32. // Get the layout.
  33. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  34. const CXXRecordDecl *BaseDecl =
  35. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  36. // Add the offset.
  37. Offset += Layout.getBaseClassOffset(BaseDecl);
  38. RD = BaseDecl;
  39. }
  40. return Offset;
  41. }
  42. llvm::Constant *
  43. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  44. CastExpr::path_const_iterator PathBegin,
  45. CastExpr::path_const_iterator PathEnd) {
  46. assert(PathBegin != PathEnd && "Base path should not be empty!");
  47. CharUnits Offset =
  48. ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
  49. PathBegin, PathEnd);
  50. if (Offset.isZero())
  51. return 0;
  52. const llvm::Type *PtrDiffTy =
  53. Types.ConvertType(getContext().getPointerDiffType());
  54. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  55. }
  56. /// Gets the address of a direct base class within a complete object.
  57. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  58. /// when the type is known to be complete (e.g. in complete destructors).
  59. ///
  60. /// The object pointed to by 'This' is assumed to be non-null.
  61. llvm::Value *
  62. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
  63. const CXXRecordDecl *Derived,
  64. const CXXRecordDecl *Base,
  65. bool BaseIsVirtual) {
  66. // 'this' must be a pointer (in some address space) to Derived.
  67. assert(This->getType()->isPointerTy() &&
  68. cast<llvm::PointerType>(This->getType())->getElementType()
  69. == ConvertType(Derived));
  70. // Compute the offset of the virtual base.
  71. CharUnits Offset;
  72. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  73. if (BaseIsVirtual)
  74. Offset = Layout.getVBaseClassOffset(Base);
  75. else
  76. Offset = Layout.getBaseClassOffset(Base);
  77. // Shift and cast down to the base type.
  78. // TODO: for complete types, this should be possible with a GEP.
  79. llvm::Value *V = This;
  80. if (Offset.isPositive()) {
  81. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
  82. V = Builder.CreateBitCast(V, Int8PtrTy);
  83. V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
  84. }
  85. V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
  86. return V;
  87. }
  88. static llvm::Value *
  89. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
  90. CharUnits NonVirtual, llvm::Value *Virtual) {
  91. const llvm::Type *PtrDiffTy =
  92. CGF.ConvertType(CGF.getContext().getPointerDiffType());
  93. llvm::Value *NonVirtualOffset = 0;
  94. if (!NonVirtual.isZero())
  95. NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
  96. NonVirtual.getQuantity());
  97. llvm::Value *BaseOffset;
  98. if (Virtual) {
  99. if (NonVirtualOffset)
  100. BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
  101. else
  102. BaseOffset = Virtual;
  103. } else
  104. BaseOffset = NonVirtualOffset;
  105. // Apply the base offset.
  106. const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
  107. ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
  108. ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
  109. return ThisPtr;
  110. }
  111. llvm::Value *
  112. CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
  113. const CXXRecordDecl *Derived,
  114. CastExpr::path_const_iterator PathBegin,
  115. CastExpr::path_const_iterator PathEnd,
  116. bool NullCheckValue) {
  117. assert(PathBegin != PathEnd && "Base path should not be empty!");
  118. CastExpr::path_const_iterator Start = PathBegin;
  119. const CXXRecordDecl *VBase = 0;
  120. // Get the virtual base.
  121. if ((*Start)->isVirtual()) {
  122. VBase =
  123. cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
  124. ++Start;
  125. }
  126. CharUnits NonVirtualOffset =
  127. ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
  128. Start, PathEnd);
  129. // Get the base pointer type.
  130. const llvm::Type *BasePtrTy =
  131. ConvertType((PathEnd[-1])->getType())->getPointerTo();
  132. if (NonVirtualOffset.isZero() && !VBase) {
  133. // Just cast back.
  134. return Builder.CreateBitCast(Value, BasePtrTy);
  135. }
  136. llvm::BasicBlock *CastNull = 0;
  137. llvm::BasicBlock *CastNotNull = 0;
  138. llvm::BasicBlock *CastEnd = 0;
  139. if (NullCheckValue) {
  140. CastNull = createBasicBlock("cast.null");
  141. CastNotNull = createBasicBlock("cast.notnull");
  142. CastEnd = createBasicBlock("cast.end");
  143. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  144. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  145. EmitBlock(CastNotNull);
  146. }
  147. llvm::Value *VirtualOffset = 0;
  148. if (VBase) {
  149. if (Derived->hasAttr<FinalAttr>()) {
  150. VirtualOffset = 0;
  151. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  152. CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
  153. NonVirtualOffset += VBaseOffset;
  154. } else
  155. VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
  156. }
  157. // Apply the offsets.
  158. Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
  159. NonVirtualOffset,
  160. VirtualOffset);
  161. // Cast back.
  162. Value = Builder.CreateBitCast(Value, BasePtrTy);
  163. if (NullCheckValue) {
  164. Builder.CreateBr(CastEnd);
  165. EmitBlock(CastNull);
  166. Builder.CreateBr(CastEnd);
  167. EmitBlock(CastEnd);
  168. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  169. PHI->addIncoming(Value, CastNotNull);
  170. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  171. CastNull);
  172. Value = PHI;
  173. }
  174. return Value;
  175. }
  176. llvm::Value *
  177. CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
  178. const CXXRecordDecl *Derived,
  179. CastExpr::path_const_iterator PathBegin,
  180. CastExpr::path_const_iterator PathEnd,
  181. bool NullCheckValue) {
  182. assert(PathBegin != PathEnd && "Base path should not be empty!");
  183. QualType DerivedTy =
  184. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  185. const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  186. llvm::Value *NonVirtualOffset =
  187. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  188. if (!NonVirtualOffset) {
  189. // No offset, we can just cast back.
  190. return Builder.CreateBitCast(Value, DerivedPtrTy);
  191. }
  192. llvm::BasicBlock *CastNull = 0;
  193. llvm::BasicBlock *CastNotNull = 0;
  194. llvm::BasicBlock *CastEnd = 0;
  195. if (NullCheckValue) {
  196. CastNull = createBasicBlock("cast.null");
  197. CastNotNull = createBasicBlock("cast.notnull");
  198. CastEnd = createBasicBlock("cast.end");
  199. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  200. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  201. EmitBlock(CastNotNull);
  202. }
  203. // Apply the offset.
  204. Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
  205. Value = Builder.CreateSub(Value, NonVirtualOffset);
  206. Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
  207. // Just cast.
  208. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  209. if (NullCheckValue) {
  210. Builder.CreateBr(CastEnd);
  211. EmitBlock(CastNull);
  212. Builder.CreateBr(CastEnd);
  213. EmitBlock(CastEnd);
  214. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  215. PHI->addIncoming(Value, CastNotNull);
  216. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  217. CastNull);
  218. Value = PHI;
  219. }
  220. return Value;
  221. }
  222. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  223. /// base constructor/destructor with virtual bases.
  224. static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
  225. bool ForVirtualBase) {
  226. if (!CodeGenVTables::needsVTTParameter(GD)) {
  227. // This constructor/destructor does not need a VTT parameter.
  228. return 0;
  229. }
  230. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
  231. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  232. llvm::Value *VTT;
  233. uint64_t SubVTTIndex;
  234. // If the record matches the base, this is the complete ctor/dtor
  235. // variant calling the base variant in a class with virtual bases.
  236. if (RD == Base) {
  237. assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
  238. "doing no-op VTT offset in base dtor/ctor?");
  239. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  240. SubVTTIndex = 0;
  241. } else {
  242. const ASTRecordLayout &Layout =
  243. CGF.getContext().getASTRecordLayout(RD);
  244. CharUnits BaseOffset = ForVirtualBase ?
  245. Layout.getVBaseClassOffset(Base) :
  246. Layout.getBaseClassOffset(Base);
  247. SubVTTIndex =
  248. CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  249. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  250. }
  251. if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
  252. // A VTT parameter was passed to the constructor, use it.
  253. VTT = CGF.LoadCXXVTT();
  254. VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  255. } else {
  256. // We're the complete constructor, so get the VTT by name.
  257. VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
  258. VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  259. }
  260. return VTT;
  261. }
  262. namespace {
  263. /// Call the destructor for a direct base class.
  264. struct CallBaseDtor : EHScopeStack::Cleanup {
  265. const CXXRecordDecl *BaseClass;
  266. bool BaseIsVirtual;
  267. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  268. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  269. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  270. const CXXRecordDecl *DerivedClass =
  271. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  272. const CXXDestructorDecl *D = BaseClass->getDestructor();
  273. llvm::Value *Addr =
  274. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
  275. DerivedClass, BaseClass,
  276. BaseIsVirtual);
  277. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
  278. }
  279. };
  280. /// A visitor which checks whether an initializer uses 'this' in a
  281. /// way which requires the vtable to be properly set.
  282. struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
  283. typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
  284. bool UsesThis;
  285. DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
  286. // Black-list all explicit and implicit references to 'this'.
  287. //
  288. // Do we need to worry about external references to 'this' derived
  289. // from arbitrary code? If so, then anything which runs arbitrary
  290. // external code might potentially access the vtable.
  291. void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
  292. };
  293. }
  294. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  295. DynamicThisUseChecker Checker(C);
  296. Checker.Visit(const_cast<Expr*>(Init));
  297. return Checker.UsesThis;
  298. }
  299. static void EmitBaseInitializer(CodeGenFunction &CGF,
  300. const CXXRecordDecl *ClassDecl,
  301. CXXCtorInitializer *BaseInit,
  302. CXXCtorType CtorType) {
  303. assert(BaseInit->isBaseInitializer() &&
  304. "Must have base initializer!");
  305. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  306. const Type *BaseType = BaseInit->getBaseClass();
  307. CXXRecordDecl *BaseClassDecl =
  308. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  309. bool isBaseVirtual = BaseInit->isBaseVirtual();
  310. // The base constructor doesn't construct virtual bases.
  311. if (CtorType == Ctor_Base && isBaseVirtual)
  312. return;
  313. // If the initializer for the base (other than the constructor
  314. // itself) accesses 'this' in any way, we need to initialize the
  315. // vtables.
  316. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  317. CGF.InitializeVTablePointers(ClassDecl);
  318. // We can pretend to be a complete class because it only matters for
  319. // virtual bases, and we only do virtual bases for complete ctors.
  320. llvm::Value *V =
  321. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  322. BaseClassDecl,
  323. isBaseVirtual);
  324. AggValueSlot AggSlot = AggValueSlot::forAddr(V, Qualifiers(),
  325. /*Lifetime*/ true);
  326. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  327. if (CGF.CGM.getLangOptions().Exceptions &&
  328. !BaseClassDecl->hasTrivialDestructor())
  329. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  330. isBaseVirtual);
  331. }
  332. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  333. LValue LHS,
  334. llvm::Value *ArrayIndexVar,
  335. CXXCtorInitializer *MemberInit,
  336. QualType T,
  337. unsigned Index) {
  338. if (Index == MemberInit->getNumArrayIndices()) {
  339. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  340. llvm::Value *Dest = LHS.getAddress();
  341. if (ArrayIndexVar) {
  342. // If we have an array index variable, load it and use it as an offset.
  343. // Then, increment the value.
  344. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  345. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  346. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  347. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  348. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  349. }
  350. if (!CGF.hasAggregateLLVMType(T)) {
  351. CGF.EmitScalarInit(MemberInit->getInit(), 0, Dest, false,
  352. LHS.isVolatileQualified(),
  353. CGF.getContext().getTypeAlign(T),
  354. T);
  355. } else if (T->isAnyComplexType()) {
  356. CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,
  357. LHS.isVolatileQualified());
  358. } else {
  359. AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.getQuals(),
  360. /*Lifetime*/ true);
  361. CGF.EmitAggExpr(MemberInit->getInit(), Slot);
  362. }
  363. return;
  364. }
  365. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  366. assert(Array && "Array initialization without the array type?");
  367. llvm::Value *IndexVar
  368. = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
  369. assert(IndexVar && "Array index variable not loaded");
  370. // Initialize this index variable to zero.
  371. llvm::Value* Zero
  372. = llvm::Constant::getNullValue(
  373. CGF.ConvertType(CGF.getContext().getSizeType()));
  374. CGF.Builder.CreateStore(Zero, IndexVar);
  375. // Start the loop with a block that tests the condition.
  376. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  377. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  378. CGF.EmitBlock(CondBlock);
  379. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  380. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  381. // otherwise, go to the block after the for-loop.
  382. uint64_t NumElements = Array->getSize().getZExtValue();
  383. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  384. llvm::Value *NumElementsPtr =
  385. llvm::ConstantInt::get(Counter->getType(), NumElements);
  386. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  387. "isless");
  388. // If the condition is true, execute the body.
  389. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  390. CGF.EmitBlock(ForBody);
  391. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  392. {
  393. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  394. // Inside the loop body recurse to emit the inner loop or, eventually, the
  395. // constructor call.
  396. EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
  397. Array->getElementType(), Index + 1);
  398. }
  399. CGF.EmitBlock(ContinueBlock);
  400. // Emit the increment of the loop counter.
  401. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  402. Counter = CGF.Builder.CreateLoad(IndexVar);
  403. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  404. CGF.Builder.CreateStore(NextVal, IndexVar);
  405. // Finally, branch back up to the condition for the next iteration.
  406. CGF.EmitBranch(CondBlock);
  407. // Emit the fall-through block.
  408. CGF.EmitBlock(AfterFor, true);
  409. }
  410. namespace {
  411. struct CallMemberDtor : EHScopeStack::Cleanup {
  412. FieldDecl *Field;
  413. CXXDestructorDecl *Dtor;
  414. CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
  415. : Field(Field), Dtor(Dtor) {}
  416. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  417. // FIXME: Is this OK for C++0x delegating constructors?
  418. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  419. LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
  420. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  421. LHS.getAddress());
  422. }
  423. };
  424. }
  425. static void EmitMemberInitializer(CodeGenFunction &CGF,
  426. const CXXRecordDecl *ClassDecl,
  427. CXXCtorInitializer *MemberInit,
  428. const CXXConstructorDecl *Constructor,
  429. FunctionArgList &Args) {
  430. assert(MemberInit->isAnyMemberInitializer() &&
  431. "Must have member initializer!");
  432. assert(MemberInit->getInit() && "Must have initializer!");
  433. // non-static data member initializers.
  434. FieldDecl *Field = MemberInit->getAnyMember();
  435. QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
  436. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  437. LValue LHS;
  438. // If we are initializing an anonymous union field, drill down to the field.
  439. if (MemberInit->isIndirectMemberInitializer()) {
  440. LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
  441. MemberInit->getIndirectMember(), 0);
  442. FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
  443. } else {
  444. LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
  445. }
  446. // FIXME: If there's no initializer and the CXXCtorInitializer
  447. // was implicitly generated, we shouldn't be zeroing memory.
  448. if (FieldType->isArrayType() && !MemberInit->getInit()) {
  449. CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
  450. } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
  451. if (LHS.isSimple()) {
  452. CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS.getAddress(),
  453. CGF.getContext().getDeclAlign(Field), false);
  454. } else {
  455. RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
  456. CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
  457. }
  458. } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
  459. CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
  460. LHS.isVolatileQualified());
  461. } else {
  462. llvm::Value *ArrayIndexVar = 0;
  463. const ConstantArrayType *Array
  464. = CGF.getContext().getAsConstantArrayType(FieldType);
  465. if (Array && Constructor->isImplicit() &&
  466. Constructor->isCopyConstructor()) {
  467. const llvm::Type *SizeTy
  468. = CGF.ConvertType(CGF.getContext().getSizeType());
  469. // The LHS is a pointer to the first object we'll be constructing, as
  470. // a flat array.
  471. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  472. const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
  473. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  474. llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
  475. BasePtr);
  476. LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  477. // Create an array index that will be used to walk over all of the
  478. // objects we're constructing.
  479. ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
  480. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  481. CGF.Builder.CreateStore(Zero, ArrayIndexVar);
  482. // If we are copying an array of PODs or classes with trivial copy
  483. // constructors, perform a single aggregate copy.
  484. const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
  485. if (BaseElementTy.isPODType(CGF.getContext()) ||
  486. (Record && Record->hasTrivialCopyConstructor())) {
  487. // Find the source pointer. We knows it's the last argument because
  488. // we know we're in a copy constructor.
  489. unsigned SrcArgIndex = Args.size() - 1;
  490. llvm::Value *SrcPtr
  491. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  492. LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
  493. // Copy the aggregate.
  494. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  495. LHS.isVolatileQualified());
  496. return;
  497. }
  498. // Emit the block variables for the array indices, if any.
  499. for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
  500. CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
  501. }
  502. EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
  503. if (!CGF.CGM.getLangOptions().Exceptions)
  504. return;
  505. // FIXME: If we have an array of classes w/ non-trivial destructors,
  506. // we need to destroy in reverse order of construction along the exception
  507. // path.
  508. const RecordType *RT = FieldType->getAs<RecordType>();
  509. if (!RT)
  510. return;
  511. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  512. if (!RD->hasTrivialDestructor())
  513. CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
  514. RD->getDestructor());
  515. }
  516. }
  517. /// Checks whether the given constructor is a valid subject for the
  518. /// complete-to-base constructor delegation optimization, i.e.
  519. /// emitting the complete constructor as a simple call to the base
  520. /// constructor.
  521. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
  522. // Currently we disable the optimization for classes with virtual
  523. // bases because (1) the addresses of parameter variables need to be
  524. // consistent across all initializers but (2) the delegate function
  525. // call necessarily creates a second copy of the parameter variable.
  526. //
  527. // The limiting example (purely theoretical AFAIK):
  528. // struct A { A(int &c) { c++; } };
  529. // struct B : virtual A {
  530. // B(int count) : A(count) { printf("%d\n", count); }
  531. // };
  532. // ...although even this example could in principle be emitted as a
  533. // delegation since the address of the parameter doesn't escape.
  534. if (Ctor->getParent()->getNumVBases()) {
  535. // TODO: white-list trivial vbase initializers. This case wouldn't
  536. // be subject to the restrictions below.
  537. // TODO: white-list cases where:
  538. // - there are no non-reference parameters to the constructor
  539. // - the initializers don't access any non-reference parameters
  540. // - the initializers don't take the address of non-reference
  541. // parameters
  542. // - etc.
  543. // If we ever add any of the above cases, remember that:
  544. // - function-try-blocks will always blacklist this optimization
  545. // - we need to perform the constructor prologue and cleanup in
  546. // EmitConstructorBody.
  547. return false;
  548. }
  549. // We also disable the optimization for variadic functions because
  550. // it's impossible to "re-pass" varargs.
  551. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  552. return false;
  553. // FIXME: Decide if we can do a delegation of a delegating constructor.
  554. if (Ctor->isDelegatingConstructor())
  555. return false;
  556. return true;
  557. }
  558. /// EmitConstructorBody - Emits the body of the current constructor.
  559. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  560. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  561. CXXCtorType CtorType = CurGD.getCtorType();
  562. // Before we go any further, try the complete->base constructor
  563. // delegation optimization.
  564. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
  565. if (CGDebugInfo *DI = getDebugInfo())
  566. DI->EmitStopPoint(Builder);
  567. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
  568. return;
  569. }
  570. Stmt *Body = Ctor->getBody();
  571. // Enter the function-try-block before the constructor prologue if
  572. // applicable.
  573. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  574. if (IsTryBody)
  575. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  576. EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
  577. // Emit the constructor prologue, i.e. the base and member
  578. // initializers.
  579. EmitCtorPrologue(Ctor, CtorType, Args);
  580. // Emit the body of the statement.
  581. if (IsTryBody)
  582. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  583. else if (Body)
  584. EmitStmt(Body);
  585. // Emit any cleanup blocks associated with the member or base
  586. // initializers, which includes (along the exceptional path) the
  587. // destructors for those members and bases that were fully
  588. // constructed.
  589. PopCleanupBlocks(CleanupDepth);
  590. if (IsTryBody)
  591. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  592. }
  593. /// EmitCtorPrologue - This routine generates necessary code to initialize
  594. /// base classes and non-static data members belonging to this constructor.
  595. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  596. CXXCtorType CtorType,
  597. FunctionArgList &Args) {
  598. if (CD->isDelegatingConstructor())
  599. return EmitDelegatingCXXConstructorCall(CD, Args);
  600. const CXXRecordDecl *ClassDecl = CD->getParent();
  601. llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
  602. for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  603. E = CD->init_end();
  604. B != E; ++B) {
  605. CXXCtorInitializer *Member = (*B);
  606. if (Member->isBaseInitializer()) {
  607. EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
  608. } else {
  609. assert(Member->isAnyMemberInitializer() &&
  610. "Delegating initializer on non-delegating constructor");
  611. MemberInitializers.push_back(Member);
  612. }
  613. }
  614. InitializeVTablePointers(ClassDecl);
  615. for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
  616. EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
  617. }
  618. static bool
  619. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  620. static bool
  621. HasTrivialDestructorBody(ASTContext &Context,
  622. const CXXRecordDecl *BaseClassDecl,
  623. const CXXRecordDecl *MostDerivedClassDecl)
  624. {
  625. // If the destructor is trivial we don't have to check anything else.
  626. if (BaseClassDecl->hasTrivialDestructor())
  627. return true;
  628. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  629. return false;
  630. // Check fields.
  631. for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
  632. E = BaseClassDecl->field_end(); I != E; ++I) {
  633. const FieldDecl *Field = *I;
  634. if (!FieldHasTrivialDestructorBody(Context, Field))
  635. return false;
  636. }
  637. // Check non-virtual bases.
  638. for (CXXRecordDecl::base_class_const_iterator I =
  639. BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
  640. I != E; ++I) {
  641. if (I->isVirtual())
  642. continue;
  643. const CXXRecordDecl *NonVirtualBase =
  644. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  645. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  646. MostDerivedClassDecl))
  647. return false;
  648. }
  649. if (BaseClassDecl == MostDerivedClassDecl) {
  650. // Check virtual bases.
  651. for (CXXRecordDecl::base_class_const_iterator I =
  652. BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
  653. I != E; ++I) {
  654. const CXXRecordDecl *VirtualBase =
  655. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  656. if (!HasTrivialDestructorBody(Context, VirtualBase,
  657. MostDerivedClassDecl))
  658. return false;
  659. }
  660. }
  661. return true;
  662. }
  663. static bool
  664. FieldHasTrivialDestructorBody(ASTContext &Context,
  665. const FieldDecl *Field)
  666. {
  667. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  668. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  669. if (!RT)
  670. return true;
  671. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  672. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  673. }
  674. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  675. /// any vtable pointers before calling this destructor.
  676. static bool CanSkipVTablePointerInitialization(ASTContext &Context,
  677. const CXXDestructorDecl *Dtor) {
  678. if (!Dtor->hasTrivialBody())
  679. return false;
  680. // Check the fields.
  681. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  682. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  683. E = ClassDecl->field_end(); I != E; ++I) {
  684. const FieldDecl *Field = *I;
  685. if (!FieldHasTrivialDestructorBody(Context, Field))
  686. return false;
  687. }
  688. return true;
  689. }
  690. /// EmitDestructorBody - Emits the body of the current destructor.
  691. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  692. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  693. CXXDtorType DtorType = CurGD.getDtorType();
  694. // The call to operator delete in a deleting destructor happens
  695. // outside of the function-try-block, which means it's always
  696. // possible to delegate the destructor body to the complete
  697. // destructor. Do so.
  698. if (DtorType == Dtor_Deleting) {
  699. EnterDtorCleanups(Dtor, Dtor_Deleting);
  700. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  701. LoadCXXThis());
  702. PopCleanupBlock();
  703. return;
  704. }
  705. Stmt *Body = Dtor->getBody();
  706. // If the body is a function-try-block, enter the try before
  707. // anything else.
  708. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  709. if (isTryBody)
  710. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  711. // Enter the epilogue cleanups.
  712. RunCleanupsScope DtorEpilogue(*this);
  713. // If this is the complete variant, just invoke the base variant;
  714. // the epilogue will destruct the virtual bases. But we can't do
  715. // this optimization if the body is a function-try-block, because
  716. // we'd introduce *two* handler blocks.
  717. switch (DtorType) {
  718. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  719. case Dtor_Complete:
  720. // Enter the cleanup scopes for virtual bases.
  721. EnterDtorCleanups(Dtor, Dtor_Complete);
  722. if (!isTryBody) {
  723. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  724. LoadCXXThis());
  725. break;
  726. }
  727. // Fallthrough: act like we're in the base variant.
  728. case Dtor_Base:
  729. // Enter the cleanup scopes for fields and non-virtual bases.
  730. EnterDtorCleanups(Dtor, Dtor_Base);
  731. // Initialize the vtable pointers before entering the body.
  732. if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
  733. InitializeVTablePointers(Dtor->getParent());
  734. if (isTryBody)
  735. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  736. else if (Body)
  737. EmitStmt(Body);
  738. else {
  739. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  740. // nothing to do besides what's in the epilogue
  741. }
  742. // -fapple-kext must inline any call to this dtor into
  743. // the caller's body.
  744. if (getContext().getLangOptions().AppleKext)
  745. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  746. break;
  747. }
  748. // Jump out through the epilogue cleanups.
  749. DtorEpilogue.ForceCleanup();
  750. // Exit the try if applicable.
  751. if (isTryBody)
  752. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  753. }
  754. namespace {
  755. /// Call the operator delete associated with the current destructor.
  756. struct CallDtorDelete : EHScopeStack::Cleanup {
  757. CallDtorDelete() {}
  758. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  759. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  760. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  761. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  762. CGF.getContext().getTagDeclType(ClassDecl));
  763. }
  764. };
  765. struct CallArrayFieldDtor : EHScopeStack::Cleanup {
  766. const FieldDecl *Field;
  767. CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
  768. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  769. QualType FieldType = Field->getType();
  770. QualType BaseType = CGF.getContext().getBaseElementType(FieldType);
  771. const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
  772. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  773. LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
  774. // FIXME: Qualifiers?
  775. /*CVRQualifiers=*/0);
  776. const llvm::Type *BasePtr
  777. = CGF.ConvertType(BaseType)->getPointerTo();
  778. llvm::Value *BaseAddrPtr
  779. = CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
  780. const ConstantArrayType *Array
  781. = CGF.getContext().getAsConstantArrayType(FieldType);
  782. CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
  783. Array, BaseAddrPtr);
  784. }
  785. };
  786. struct CallFieldDtor : EHScopeStack::Cleanup {
  787. const FieldDecl *Field;
  788. CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
  789. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  790. const CXXRecordDecl *FieldClassDecl =
  791. Field->getType()->getAsCXXRecordDecl();
  792. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  793. LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
  794. // FIXME: Qualifiers?
  795. /*CVRQualifiers=*/0);
  796. CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
  797. Dtor_Complete, /*ForVirtualBase=*/false,
  798. LHS.getAddress());
  799. }
  800. };
  801. }
  802. /// EmitDtorEpilogue - Emit all code that comes at the end of class's
  803. /// destructor. This is to call destructors on members and base classes
  804. /// in reverse order of their construction.
  805. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  806. CXXDtorType DtorType) {
  807. assert(!DD->isTrivial() &&
  808. "Should not emit dtor epilogue for trivial dtor!");
  809. // The deleting-destructor phase just needs to call the appropriate
  810. // operator delete that Sema picked up.
  811. if (DtorType == Dtor_Deleting) {
  812. assert(DD->getOperatorDelete() &&
  813. "operator delete missing - EmitDtorEpilogue");
  814. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  815. return;
  816. }
  817. const CXXRecordDecl *ClassDecl = DD->getParent();
  818. // The complete-destructor phase just destructs all the virtual bases.
  819. if (DtorType == Dtor_Complete) {
  820. // We push them in the forward order so that they'll be popped in
  821. // the reverse order.
  822. for (CXXRecordDecl::base_class_const_iterator I =
  823. ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
  824. I != E; ++I) {
  825. const CXXBaseSpecifier &Base = *I;
  826. CXXRecordDecl *BaseClassDecl
  827. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  828. // Ignore trivial destructors.
  829. if (BaseClassDecl->hasTrivialDestructor())
  830. continue;
  831. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  832. BaseClassDecl,
  833. /*BaseIsVirtual*/ true);
  834. }
  835. return;
  836. }
  837. assert(DtorType == Dtor_Base);
  838. // Destroy non-virtual bases.
  839. for (CXXRecordDecl::base_class_const_iterator I =
  840. ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
  841. const CXXBaseSpecifier &Base = *I;
  842. // Ignore virtual bases.
  843. if (Base.isVirtual())
  844. continue;
  845. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  846. // Ignore trivial destructors.
  847. if (BaseClassDecl->hasTrivialDestructor())
  848. continue;
  849. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  850. BaseClassDecl,
  851. /*BaseIsVirtual*/ false);
  852. }
  853. // Destroy direct fields.
  854. llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
  855. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  856. E = ClassDecl->field_end(); I != E; ++I) {
  857. const FieldDecl *Field = *I;
  858. QualType FieldType = getContext().getCanonicalType(Field->getType());
  859. const ConstantArrayType *Array =
  860. getContext().getAsConstantArrayType(FieldType);
  861. if (Array)
  862. FieldType = getContext().getBaseElementType(Array->getElementType());
  863. switch (FieldType.isDestructedType()) {
  864. case QualType::DK_none:
  865. continue;
  866. case QualType::DK_cxx_destructor:
  867. if (Array)
  868. EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
  869. else
  870. EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
  871. break;
  872. case QualType::DK_objc_strong_lifetime:
  873. PushARCFieldReleaseCleanup(getARCCleanupKind(), Field);
  874. break;
  875. case QualType::DK_objc_weak_lifetime:
  876. PushARCFieldWeakReleaseCleanup(getARCCleanupKind(), Field);
  877. break;
  878. }
  879. }
  880. }
  881. /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
  882. /// for-loop to call the default constructor on individual members of the
  883. /// array.
  884. /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
  885. /// array type and 'ArrayPtr' points to the beginning fo the array.
  886. /// It is assumed that all relevant checks have been made by the caller.
  887. ///
  888. /// \param ZeroInitialization True if each element should be zero-initialized
  889. /// before it is constructed.
  890. void
  891. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  892. const ConstantArrayType *ArrayTy,
  893. llvm::Value *ArrayPtr,
  894. CallExpr::const_arg_iterator ArgBeg,
  895. CallExpr::const_arg_iterator ArgEnd,
  896. bool ZeroInitialization) {
  897. const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  898. llvm::Value * NumElements =
  899. llvm::ConstantInt::get(SizeTy,
  900. getContext().getConstantArrayElementCount(ArrayTy));
  901. EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
  902. ZeroInitialization);
  903. }
  904. void
  905. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  906. llvm::Value *NumElements,
  907. llvm::Value *ArrayPtr,
  908. CallExpr::const_arg_iterator ArgBeg,
  909. CallExpr::const_arg_iterator ArgEnd,
  910. bool ZeroInitialization) {
  911. const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  912. // Create a temporary for the loop index and initialize it with 0.
  913. llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
  914. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  915. Builder.CreateStore(Zero, IndexPtr);
  916. // Start the loop with a block that tests the condition.
  917. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
  918. llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
  919. EmitBlock(CondBlock);
  920. llvm::BasicBlock *ForBody = createBasicBlock("for.body");
  921. // Generate: if (loop-index < number-of-elements fall to the loop body,
  922. // otherwise, go to the block after the for-loop.
  923. llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
  924. llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
  925. // If the condition is true, execute the body.
  926. Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  927. EmitBlock(ForBody);
  928. llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
  929. // Inside the loop body, emit the constructor call on the array element.
  930. Counter = Builder.CreateLoad(IndexPtr);
  931. llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
  932. "arrayidx");
  933. // Zero initialize the storage, if requested.
  934. if (ZeroInitialization)
  935. EmitNullInitialization(Address,
  936. getContext().getTypeDeclType(D->getParent()));
  937. // C++ [class.temporary]p4:
  938. // There are two contexts in which temporaries are destroyed at a different
  939. // point than the end of the full-expression. The first context is when a
  940. // default constructor is called to initialize an element of an array.
  941. // If the constructor has one or more default arguments, the destruction of
  942. // every temporary created in a default argument expression is sequenced
  943. // before the construction of the next array element, if any.
  944. // Keep track of the current number of live temporaries.
  945. {
  946. RunCleanupsScope Scope(*this);
  947. EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
  948. ArgBeg, ArgEnd);
  949. }
  950. EmitBlock(ContinueBlock);
  951. // Emit the increment of the loop counter.
  952. llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
  953. Counter = Builder.CreateLoad(IndexPtr);
  954. NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
  955. Builder.CreateStore(NextVal, IndexPtr);
  956. // Finally, branch back up to the condition for the next iteration.
  957. EmitBranch(CondBlock);
  958. // Emit the fall-through block.
  959. EmitBlock(AfterFor, true);
  960. }
  961. /// EmitCXXAggrDestructorCall - calls the default destructor on array
  962. /// elements in reverse order of construction.
  963. void
  964. CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
  965. const ArrayType *Array,
  966. llvm::Value *This) {
  967. const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
  968. assert(CA && "Do we support VLA for destruction ?");
  969. uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
  970. const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
  971. llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
  972. EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
  973. }
  974. /// EmitCXXAggrDestructorCall - calls the default destructor on array
  975. /// elements in reverse order of construction.
  976. void
  977. CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
  978. llvm::Value *UpperCount,
  979. llvm::Value *This) {
  980. const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
  981. llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
  982. // Create a temporary for the loop index and initialize it with count of
  983. // array elements.
  984. llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
  985. // Store the number of elements in the index pointer.
  986. Builder.CreateStore(UpperCount, IndexPtr);
  987. // Start the loop with a block that tests the condition.
  988. llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
  989. llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
  990. EmitBlock(CondBlock);
  991. llvm::BasicBlock *ForBody = createBasicBlock("for.body");
  992. // Generate: if (loop-index != 0 fall to the loop body,
  993. // otherwise, go to the block after the for-loop.
  994. llvm::Value* zeroConstant =
  995. llvm::Constant::getNullValue(SizeLTy);
  996. llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
  997. llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
  998. "isne");
  999. // If the condition is true, execute the body.
  1000. Builder.CreateCondBr(IsNE, ForBody, AfterFor);
  1001. EmitBlock(ForBody);
  1002. llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
  1003. // Inside the loop body, emit the constructor call on the array element.
  1004. Counter = Builder.CreateLoad(IndexPtr);
  1005. Counter = Builder.CreateSub(Counter, One);
  1006. llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
  1007. EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
  1008. EmitBlock(ContinueBlock);
  1009. // Emit the decrement of the loop counter.
  1010. Counter = Builder.CreateLoad(IndexPtr);
  1011. Counter = Builder.CreateSub(Counter, One, "dec");
  1012. Builder.CreateStore(Counter, IndexPtr);
  1013. // Finally, branch back up to the condition for the next iteration.
  1014. EmitBranch(CondBlock);
  1015. // Emit the fall-through block.
  1016. EmitBlock(AfterFor, true);
  1017. }
  1018. void
  1019. CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1020. CXXCtorType Type, bool ForVirtualBase,
  1021. llvm::Value *This,
  1022. CallExpr::const_arg_iterator ArgBeg,
  1023. CallExpr::const_arg_iterator ArgEnd) {
  1024. CGDebugInfo *DI = getDebugInfo();
  1025. if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
  1026. // If debug info for this class has been emitted then this is the right time
  1027. // to do so.
  1028. const CXXRecordDecl *Parent = D->getParent();
  1029. DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
  1030. Parent->getLocation());
  1031. }
  1032. if (D->isTrivial()) {
  1033. if (ArgBeg == ArgEnd) {
  1034. // Trivial default constructor, no codegen required.
  1035. assert(D->isDefaultConstructor() &&
  1036. "trivial 0-arg ctor not a default ctor");
  1037. return;
  1038. }
  1039. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1040. assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
  1041. const Expr *E = (*ArgBeg);
  1042. QualType Ty = E->getType();
  1043. llvm::Value *Src = EmitLValue(E).getAddress();
  1044. EmitAggregateCopy(This, Src, Ty);
  1045. return;
  1046. }
  1047. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
  1048. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
  1049. EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
  1050. }
  1051. void
  1052. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1053. llvm::Value *This, llvm::Value *Src,
  1054. CallExpr::const_arg_iterator ArgBeg,
  1055. CallExpr::const_arg_iterator ArgEnd) {
  1056. if (D->isTrivial()) {
  1057. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1058. assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
  1059. EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
  1060. return;
  1061. }
  1062. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
  1063. clang::Ctor_Complete);
  1064. assert(D->isInstance() &&
  1065. "Trying to emit a member call expr on a static method!");
  1066. const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
  1067. CallArgList Args;
  1068. // Push the this ptr.
  1069. Args.add(RValue::get(This), D->getThisType(getContext()));
  1070. // Push the src ptr.
  1071. QualType QT = *(FPT->arg_type_begin());
  1072. const llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1073. Src = Builder.CreateBitCast(Src, t);
  1074. Args.add(RValue::get(Src), QT);
  1075. // Skip over first argument (Src).
  1076. ++ArgBeg;
  1077. CallExpr::const_arg_iterator Arg = ArgBeg;
  1078. for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
  1079. E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
  1080. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1081. EmitCallArg(Args, *Arg, *I);
  1082. }
  1083. // Either we've emitted all the call args, or we have a call to a
  1084. // variadic function.
  1085. assert((Arg == ArgEnd || FPT->isVariadic()) &&
  1086. "Extra arguments in non-variadic function!");
  1087. // If we still have any arguments, emit them using the type of the argument.
  1088. for (; Arg != ArgEnd; ++Arg) {
  1089. QualType ArgType = Arg->getType();
  1090. EmitCallArg(Args, *Arg, ArgType);
  1091. }
  1092. QualType ResultType = FPT->getResultType();
  1093. EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
  1094. FPT->getExtInfo()),
  1095. Callee, ReturnValueSlot(), Args, D);
  1096. }
  1097. void
  1098. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1099. CXXCtorType CtorType,
  1100. const FunctionArgList &Args) {
  1101. CallArgList DelegateArgs;
  1102. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1103. assert(I != E && "no parameters to constructor");
  1104. // this
  1105. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1106. ++I;
  1107. // vtt
  1108. if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
  1109. /*ForVirtualBase=*/false)) {
  1110. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1111. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1112. if (CodeGenVTables::needsVTTParameter(CurGD)) {
  1113. assert(I != E && "cannot skip vtt parameter, already done with args");
  1114. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1115. ++I;
  1116. }
  1117. }
  1118. // Explicit arguments.
  1119. for (; I != E; ++I) {
  1120. const VarDecl *param = *I;
  1121. EmitDelegateCallArg(DelegateArgs, param);
  1122. }
  1123. EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
  1124. CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
  1125. ReturnValueSlot(), DelegateArgs, Ctor);
  1126. }
  1127. namespace {
  1128. struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
  1129. const CXXDestructorDecl *Dtor;
  1130. llvm::Value *Addr;
  1131. CXXDtorType Type;
  1132. CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
  1133. CXXDtorType Type)
  1134. : Dtor(D), Addr(Addr), Type(Type) {}
  1135. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  1136. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1137. Addr);
  1138. }
  1139. };
  1140. }
  1141. void
  1142. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1143. const FunctionArgList &Args) {
  1144. assert(Ctor->isDelegatingConstructor());
  1145. llvm::Value *ThisPtr = LoadCXXThis();
  1146. AggValueSlot AggSlot =
  1147. AggValueSlot::forAddr(ThisPtr, Qualifiers(), /*Lifetime*/ true);
  1148. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1149. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1150. if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1151. CXXDtorType Type =
  1152. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1153. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1154. ClassDecl->getDestructor(),
  1155. ThisPtr, Type);
  1156. }
  1157. }
  1158. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1159. CXXDtorType Type,
  1160. bool ForVirtualBase,
  1161. llvm::Value *This) {
  1162. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
  1163. ForVirtualBase);
  1164. llvm::Value *Callee = 0;
  1165. if (getContext().getLangOptions().AppleKext)
  1166. Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
  1167. DD->getParent());
  1168. if (!Callee)
  1169. Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
  1170. EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
  1171. }
  1172. namespace {
  1173. struct CallLocalDtor : EHScopeStack::Cleanup {
  1174. const CXXDestructorDecl *Dtor;
  1175. llvm::Value *Addr;
  1176. CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
  1177. : Dtor(D), Addr(Addr) {}
  1178. void Emit(CodeGenFunction &CGF, bool IsForEH) {
  1179. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1180. /*ForVirtualBase=*/false, Addr);
  1181. }
  1182. };
  1183. }
  1184. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1185. llvm::Value *Addr) {
  1186. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1187. }
  1188. void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
  1189. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1190. if (!ClassDecl) return;
  1191. if (ClassDecl->hasTrivialDestructor()) return;
  1192. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1193. assert(D && D->isUsed() && "destructor not marked as used!");
  1194. PushDestructorCleanup(D, Addr);
  1195. }
  1196. llvm::Value *
  1197. CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
  1198. const CXXRecordDecl *ClassDecl,
  1199. const CXXRecordDecl *BaseClassDecl) {
  1200. llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
  1201. CharUnits VBaseOffsetOffset =
  1202. CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
  1203. llvm::Value *VBaseOffsetPtr =
  1204. Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
  1205. "vbase.offset.ptr");
  1206. const llvm::Type *PtrDiffTy =
  1207. ConvertType(getContext().getPointerDiffType());
  1208. VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
  1209. PtrDiffTy->getPointerTo());
  1210. llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
  1211. return VBaseOffset;
  1212. }
  1213. void
  1214. CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
  1215. const CXXRecordDecl *NearestVBase,
  1216. CharUnits OffsetFromNearestVBase,
  1217. llvm::Constant *VTable,
  1218. const CXXRecordDecl *VTableClass) {
  1219. const CXXRecordDecl *RD = Base.getBase();
  1220. // Compute the address point.
  1221. llvm::Value *VTableAddressPoint;
  1222. // Check if we need to use a vtable from the VTT.
  1223. if (CodeGenVTables::needsVTTParameter(CurGD) &&
  1224. (RD->getNumVBases() || NearestVBase)) {
  1225. // Get the secondary vpointer index.
  1226. uint64_t VirtualPointerIndex =
  1227. CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
  1228. /// Load the VTT.
  1229. llvm::Value *VTT = LoadCXXVTT();
  1230. if (VirtualPointerIndex)
  1231. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
  1232. // And load the address point from the VTT.
  1233. VTableAddressPoint = Builder.CreateLoad(VTT);
  1234. } else {
  1235. uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
  1236. VTableAddressPoint =
  1237. Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
  1238. }
  1239. // Compute where to store the address point.
  1240. llvm::Value *VirtualOffset = 0;
  1241. CharUnits NonVirtualOffset = CharUnits::Zero();
  1242. if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
  1243. // We need to use the virtual base offset offset because the virtual base
  1244. // might have a different offset in the most derived class.
  1245. VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
  1246. NearestVBase);
  1247. NonVirtualOffset = OffsetFromNearestVBase;
  1248. } else {
  1249. // We can just use the base offset in the complete class.
  1250. NonVirtualOffset = Base.getBaseOffset();
  1251. }
  1252. // Apply the offsets.
  1253. llvm::Value *VTableField = LoadCXXThis();
  1254. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1255. VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
  1256. NonVirtualOffset,
  1257. VirtualOffset);
  1258. // Finally, store the address point.
  1259. const llvm::Type *AddressPointPtrTy =
  1260. VTableAddressPoint->getType()->getPointerTo();
  1261. VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
  1262. Builder.CreateStore(VTableAddressPoint, VTableField);
  1263. }
  1264. void
  1265. CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
  1266. const CXXRecordDecl *NearestVBase,
  1267. CharUnits OffsetFromNearestVBase,
  1268. bool BaseIsNonVirtualPrimaryBase,
  1269. llvm::Constant *VTable,
  1270. const CXXRecordDecl *VTableClass,
  1271. VisitedVirtualBasesSetTy& VBases) {
  1272. // If this base is a non-virtual primary base the address point has already
  1273. // been set.
  1274. if (!BaseIsNonVirtualPrimaryBase) {
  1275. // Initialize the vtable pointer for this base.
  1276. InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
  1277. VTable, VTableClass);
  1278. }
  1279. const CXXRecordDecl *RD = Base.getBase();
  1280. // Traverse bases.
  1281. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1282. E = RD->bases_end(); I != E; ++I) {
  1283. CXXRecordDecl *BaseDecl
  1284. = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1285. // Ignore classes without a vtable.
  1286. if (!BaseDecl->isDynamicClass())
  1287. continue;
  1288. CharUnits BaseOffset;
  1289. CharUnits BaseOffsetFromNearestVBase;
  1290. bool BaseDeclIsNonVirtualPrimaryBase;
  1291. if (I->isVirtual()) {
  1292. // Check if we've visited this virtual base before.
  1293. if (!VBases.insert(BaseDecl))
  1294. continue;
  1295. const ASTRecordLayout &Layout =
  1296. getContext().getASTRecordLayout(VTableClass);
  1297. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  1298. BaseOffsetFromNearestVBase = CharUnits::Zero();
  1299. BaseDeclIsNonVirtualPrimaryBase = false;
  1300. } else {
  1301. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1302. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  1303. BaseOffsetFromNearestVBase =
  1304. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  1305. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  1306. }
  1307. InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
  1308. I->isVirtual() ? BaseDecl : NearestVBase,
  1309. BaseOffsetFromNearestVBase,
  1310. BaseDeclIsNonVirtualPrimaryBase,
  1311. VTable, VTableClass, VBases);
  1312. }
  1313. }
  1314. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  1315. // Ignore classes without a vtable.
  1316. if (!RD->isDynamicClass())
  1317. return;
  1318. // Get the VTable.
  1319. llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
  1320. // Initialize the vtable pointers for this class and all of its bases.
  1321. VisitedVirtualBasesSetTy VBases;
  1322. InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
  1323. /*NearestVBase=*/0,
  1324. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1325. /*BaseIsNonVirtualPrimaryBase=*/false,
  1326. VTable, RD, VBases);
  1327. }
  1328. llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
  1329. const llvm::Type *Ty) {
  1330. llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
  1331. return Builder.CreateLoad(VTablePtrSrc, "vtable");
  1332. }
  1333. static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
  1334. const Expr *E = Base;
  1335. while (true) {
  1336. E = E->IgnoreParens();
  1337. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1338. if (CE->getCastKind() == CK_DerivedToBase ||
  1339. CE->getCastKind() == CK_UncheckedDerivedToBase ||
  1340. CE->getCastKind() == CK_NoOp) {
  1341. E = CE->getSubExpr();
  1342. continue;
  1343. }
  1344. }
  1345. break;
  1346. }
  1347. QualType DerivedType = E->getType();
  1348. if (const PointerType *PTy = DerivedType->getAs<PointerType>())
  1349. DerivedType = PTy->getPointeeType();
  1350. return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
  1351. }
  1352. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  1353. // quite what we want.
  1354. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  1355. while (true) {
  1356. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  1357. E = PE->getSubExpr();
  1358. continue;
  1359. }
  1360. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1361. if (CE->getCastKind() == CK_NoOp) {
  1362. E = CE->getSubExpr();
  1363. continue;
  1364. }
  1365. }
  1366. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1367. if (UO->getOpcode() == UO_Extension) {
  1368. E = UO->getSubExpr();
  1369. continue;
  1370. }
  1371. }
  1372. return E;
  1373. }
  1374. }
  1375. /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
  1376. /// function call on the given expr can be devirtualized.
  1377. /// expr can be devirtualized.
  1378. static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
  1379. const CXXMethodDecl *MD) {
  1380. // If the most derived class is marked final, we know that no subclass can
  1381. // override this member function and so we can devirtualize it. For example:
  1382. //
  1383. // struct A { virtual void f(); }
  1384. // struct B final : A { };
  1385. //
  1386. // void f(B *b) {
  1387. // b->f();
  1388. // }
  1389. //
  1390. const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
  1391. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  1392. return true;
  1393. // If the member function is marked 'final', we know that it can't be
  1394. // overridden and can therefore devirtualize it.
  1395. if (MD->hasAttr<FinalAttr>())
  1396. return true;
  1397. // Similarly, if the class itself is marked 'final' it can't be overridden
  1398. // and we can therefore devirtualize the member function call.
  1399. if (MD->getParent()->hasAttr<FinalAttr>())
  1400. return true;
  1401. Base = skipNoOpCastsAndParens(Base);
  1402. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1403. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1404. // This is a record decl. We know the type and can devirtualize it.
  1405. return VD->getType()->isRecordType();
  1406. }
  1407. return false;
  1408. }
  1409. // We can always devirtualize calls on temporary object expressions.
  1410. if (isa<CXXConstructExpr>(Base))
  1411. return true;
  1412. // And calls on bound temporaries.
  1413. if (isa<CXXBindTemporaryExpr>(Base))
  1414. return true;
  1415. // Check if this is a call expr that returns a record type.
  1416. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  1417. return CE->getCallReturnType()->isRecordType();
  1418. // We can't devirtualize the call.
  1419. return false;
  1420. }
  1421. static bool UseVirtualCall(ASTContext &Context,
  1422. const CXXOperatorCallExpr *CE,
  1423. const CXXMethodDecl *MD) {
  1424. if (!MD->isVirtual())
  1425. return false;
  1426. // When building with -fapple-kext, all calls must go through the vtable since
  1427. // the kernel linker can do runtime patching of vtables.
  1428. if (Context.getLangOptions().AppleKext)
  1429. return true;
  1430. return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
  1431. }
  1432. llvm::Value *
  1433. CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1434. const CXXMethodDecl *MD,
  1435. llvm::Value *This) {
  1436. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  1437. const llvm::Type *Ty =
  1438. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
  1439. FPT->isVariadic());
  1440. if (UseVirtualCall(getContext(), E, MD))
  1441. return BuildVirtualCall(MD, This, Ty);
  1442. return CGM.GetAddrOfFunction(MD, Ty);
  1443. }