CGClass.cpp 65 KB

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