CGClass.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  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. 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. 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. 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. 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. 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, Flags flags) {
  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 =
  325. AggValueSlot::forAddr(V, Qualifiers(),
  326. AggValueSlot::IsDestructed,
  327. AggValueSlot::DoesNotNeedGCBarriers,
  328. AggValueSlot::IsNotAliased);
  329. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  330. if (CGF.CGM.getLangOptions().Exceptions &&
  331. !BaseClassDecl->hasTrivialDestructor())
  332. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  333. isBaseVirtual);
  334. }
  335. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  336. LValue LHS,
  337. llvm::Value *ArrayIndexVar,
  338. CXXCtorInitializer *MemberInit,
  339. QualType T,
  340. unsigned Index) {
  341. if (Index == MemberInit->getNumArrayIndices()) {
  342. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  343. llvm::Value *Dest = LHS.getAddress();
  344. if (ArrayIndexVar) {
  345. // If we have an array index variable, load it and use it as an offset.
  346. // Then, increment the value.
  347. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  348. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  349. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  350. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  351. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  352. }
  353. if (!CGF.hasAggregateLLVMType(T)) {
  354. LValue lvalue = CGF.MakeAddrLValue(Dest, T);
  355. CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, lvalue, false);
  356. } else if (T->isAnyComplexType()) {
  357. CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,
  358. LHS.isVolatileQualified());
  359. } else {
  360. AggValueSlot Slot =
  361. AggValueSlot::forAddr(Dest, LHS.getQuals(),
  362. AggValueSlot::IsDestructed,
  363. AggValueSlot::DoesNotNeedGCBarriers,
  364. AggValueSlot::IsNotAliased);
  365. CGF.EmitAggExpr(MemberInit->getInit(), Slot);
  366. }
  367. return;
  368. }
  369. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  370. assert(Array && "Array initialization without the array type?");
  371. llvm::Value *IndexVar
  372. = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
  373. assert(IndexVar && "Array index variable not loaded");
  374. // Initialize this index variable to zero.
  375. llvm::Value* Zero
  376. = llvm::Constant::getNullValue(
  377. CGF.ConvertType(CGF.getContext().getSizeType()));
  378. CGF.Builder.CreateStore(Zero, IndexVar);
  379. // Start the loop with a block that tests the condition.
  380. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  381. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  382. CGF.EmitBlock(CondBlock);
  383. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  384. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  385. // otherwise, go to the block after the for-loop.
  386. uint64_t NumElements = Array->getSize().getZExtValue();
  387. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  388. llvm::Value *NumElementsPtr =
  389. llvm::ConstantInt::get(Counter->getType(), NumElements);
  390. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  391. "isless");
  392. // If the condition is true, execute the body.
  393. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  394. CGF.EmitBlock(ForBody);
  395. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  396. {
  397. CodeGenFunction::RunCleanupsScope Cleanups(CGF);
  398. // Inside the loop body recurse to emit the inner loop or, eventually, the
  399. // constructor call.
  400. EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
  401. Array->getElementType(), Index + 1);
  402. }
  403. CGF.EmitBlock(ContinueBlock);
  404. // Emit the increment of the loop counter.
  405. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  406. Counter = CGF.Builder.CreateLoad(IndexVar);
  407. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  408. CGF.Builder.CreateStore(NextVal, IndexVar);
  409. // Finally, branch back up to the condition for the next iteration.
  410. CGF.EmitBranch(CondBlock);
  411. // Emit the fall-through block.
  412. CGF.EmitBlock(AfterFor, true);
  413. }
  414. namespace {
  415. struct CallMemberDtor : EHScopeStack::Cleanup {
  416. FieldDecl *Field;
  417. CXXDestructorDecl *Dtor;
  418. CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
  419. : Field(Field), Dtor(Dtor) {}
  420. void Emit(CodeGenFunction &CGF, Flags flags) {
  421. // FIXME: Is this OK for C++0x delegating constructors?
  422. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  423. LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
  424. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  425. LHS.getAddress());
  426. }
  427. };
  428. }
  429. static void EmitMemberInitializer(CodeGenFunction &CGF,
  430. const CXXRecordDecl *ClassDecl,
  431. CXXCtorInitializer *MemberInit,
  432. const CXXConstructorDecl *Constructor,
  433. FunctionArgList &Args) {
  434. assert(MemberInit->isAnyMemberInitializer() &&
  435. "Must have member initializer!");
  436. assert(MemberInit->getInit() && "Must have initializer!");
  437. // non-static data member initializers.
  438. FieldDecl *Field = MemberInit->getAnyMember();
  439. QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
  440. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  441. LValue LHS;
  442. // If we are initializing an anonymous union field, drill down to the field.
  443. if (MemberInit->isIndirectMemberInitializer()) {
  444. LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
  445. MemberInit->getIndirectMember(), 0);
  446. FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
  447. } else {
  448. LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
  449. }
  450. // FIXME: If there's no initializer and the CXXCtorInitializer
  451. // was implicitly generated, we shouldn't be zeroing memory.
  452. if (FieldType->isArrayType() && !MemberInit->getInit()) {
  453. CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
  454. } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
  455. if (LHS.isSimple()) {
  456. CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false);
  457. } else {
  458. RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
  459. CGF.EmitStoreThroughLValue(RHS, LHS);
  460. }
  461. } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
  462. CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
  463. LHS.isVolatileQualified());
  464. } else {
  465. llvm::Value *ArrayIndexVar = 0;
  466. const ConstantArrayType *Array
  467. = CGF.getContext().getAsConstantArrayType(FieldType);
  468. if (Array && Constructor->isImplicit() &&
  469. Constructor->isCopyConstructor()) {
  470. llvm::Type *SizeTy
  471. = CGF.ConvertType(CGF.getContext().getSizeType());
  472. // The LHS is a pointer to the first object we'll be constructing, as
  473. // a flat array.
  474. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  475. llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
  476. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  477. llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
  478. BasePtr);
  479. LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  480. // Create an array index that will be used to walk over all of the
  481. // objects we're constructing.
  482. ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
  483. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  484. CGF.Builder.CreateStore(Zero, ArrayIndexVar);
  485. // If we are copying an array of PODs or classes with trivial copy
  486. // constructors, perform a single aggregate copy.
  487. const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
  488. if (BaseElementTy.isPODType(CGF.getContext()) ||
  489. (Record && Record->hasTrivialCopyConstructor())) {
  490. // Find the source pointer. We knows it's the last argument because
  491. // we know we're in a copy constructor.
  492. unsigned SrcArgIndex = Args.size() - 1;
  493. llvm::Value *SrcPtr
  494. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  495. LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
  496. // Copy the aggregate.
  497. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  498. LHS.isVolatileQualified());
  499. return;
  500. }
  501. // Emit the block variables for the array indices, if any.
  502. for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
  503. CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
  504. }
  505. EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
  506. if (!CGF.CGM.getLangOptions().Exceptions)
  507. return;
  508. // FIXME: If we have an array of classes w/ non-trivial destructors,
  509. // we need to destroy in reverse order of construction along the exception
  510. // path.
  511. const RecordType *RT = FieldType->getAs<RecordType>();
  512. if (!RT)
  513. return;
  514. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  515. if (!RD->hasTrivialDestructor())
  516. CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
  517. RD->getDestructor());
  518. }
  519. }
  520. /// Checks whether the given constructor is a valid subject for the
  521. /// complete-to-base constructor delegation optimization, i.e.
  522. /// emitting the complete constructor as a simple call to the base
  523. /// constructor.
  524. static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
  525. // Currently we disable the optimization for classes with virtual
  526. // bases because (1) the addresses of parameter variables need to be
  527. // consistent across all initializers but (2) the delegate function
  528. // call necessarily creates a second copy of the parameter variable.
  529. //
  530. // The limiting example (purely theoretical AFAIK):
  531. // struct A { A(int &c) { c++; } };
  532. // struct B : virtual A {
  533. // B(int count) : A(count) { printf("%d\n", count); }
  534. // };
  535. // ...although even this example could in principle be emitted as a
  536. // delegation since the address of the parameter doesn't escape.
  537. if (Ctor->getParent()->getNumVBases()) {
  538. // TODO: white-list trivial vbase initializers. This case wouldn't
  539. // be subject to the restrictions below.
  540. // TODO: white-list cases where:
  541. // - there are no non-reference parameters to the constructor
  542. // - the initializers don't access any non-reference parameters
  543. // - the initializers don't take the address of non-reference
  544. // parameters
  545. // - etc.
  546. // If we ever add any of the above cases, remember that:
  547. // - function-try-blocks will always blacklist this optimization
  548. // - we need to perform the constructor prologue and cleanup in
  549. // EmitConstructorBody.
  550. return false;
  551. }
  552. // We also disable the optimization for variadic functions because
  553. // it's impossible to "re-pass" varargs.
  554. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  555. return false;
  556. // FIXME: Decide if we can do a delegation of a delegating constructor.
  557. if (Ctor->isDelegatingConstructor())
  558. return false;
  559. return true;
  560. }
  561. /// EmitConstructorBody - Emits the body of the current constructor.
  562. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  563. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  564. CXXCtorType CtorType = CurGD.getCtorType();
  565. // Before we go any further, try the complete->base constructor
  566. // delegation optimization.
  567. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
  568. if (CGDebugInfo *DI = getDebugInfo())
  569. DI->EmitStopPoint(Builder);
  570. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
  571. return;
  572. }
  573. Stmt *Body = Ctor->getBody();
  574. // Enter the function-try-block before the constructor prologue if
  575. // applicable.
  576. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  577. if (IsTryBody)
  578. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  579. EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
  580. // Emit the constructor prologue, i.e. the base and member
  581. // initializers.
  582. EmitCtorPrologue(Ctor, CtorType, Args);
  583. // Emit the body of the statement.
  584. if (IsTryBody)
  585. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  586. else if (Body)
  587. EmitStmt(Body);
  588. // Emit any cleanup blocks associated with the member or base
  589. // initializers, which includes (along the exceptional path) the
  590. // destructors for those members and bases that were fully
  591. // constructed.
  592. PopCleanupBlocks(CleanupDepth);
  593. if (IsTryBody)
  594. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  595. }
  596. /// EmitCtorPrologue - This routine generates necessary code to initialize
  597. /// base classes and non-static data members belonging to this constructor.
  598. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  599. CXXCtorType CtorType,
  600. FunctionArgList &Args) {
  601. if (CD->isDelegatingConstructor())
  602. return EmitDelegatingCXXConstructorCall(CD, Args);
  603. const CXXRecordDecl *ClassDecl = CD->getParent();
  604. SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
  605. for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  606. E = CD->init_end();
  607. B != E; ++B) {
  608. CXXCtorInitializer *Member = (*B);
  609. if (Member->isBaseInitializer()) {
  610. EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
  611. } else {
  612. assert(Member->isAnyMemberInitializer() &&
  613. "Delegating initializer on non-delegating constructor");
  614. MemberInitializers.push_back(Member);
  615. }
  616. }
  617. InitializeVTablePointers(ClassDecl);
  618. for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
  619. EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
  620. }
  621. static bool
  622. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  623. static bool
  624. HasTrivialDestructorBody(ASTContext &Context,
  625. const CXXRecordDecl *BaseClassDecl,
  626. const CXXRecordDecl *MostDerivedClassDecl)
  627. {
  628. // If the destructor is trivial we don't have to check anything else.
  629. if (BaseClassDecl->hasTrivialDestructor())
  630. return true;
  631. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  632. return false;
  633. // Check fields.
  634. for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
  635. E = BaseClassDecl->field_end(); I != E; ++I) {
  636. const FieldDecl *Field = *I;
  637. if (!FieldHasTrivialDestructorBody(Context, Field))
  638. return false;
  639. }
  640. // Check non-virtual bases.
  641. for (CXXRecordDecl::base_class_const_iterator I =
  642. BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
  643. I != E; ++I) {
  644. if (I->isVirtual())
  645. continue;
  646. const CXXRecordDecl *NonVirtualBase =
  647. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  648. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  649. MostDerivedClassDecl))
  650. return false;
  651. }
  652. if (BaseClassDecl == MostDerivedClassDecl) {
  653. // Check virtual bases.
  654. for (CXXRecordDecl::base_class_const_iterator I =
  655. BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
  656. I != E; ++I) {
  657. const CXXRecordDecl *VirtualBase =
  658. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  659. if (!HasTrivialDestructorBody(Context, VirtualBase,
  660. MostDerivedClassDecl))
  661. return false;
  662. }
  663. }
  664. return true;
  665. }
  666. static bool
  667. FieldHasTrivialDestructorBody(ASTContext &Context,
  668. const FieldDecl *Field)
  669. {
  670. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  671. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  672. if (!RT)
  673. return true;
  674. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  675. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  676. }
  677. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  678. /// any vtable pointers before calling this destructor.
  679. static bool CanSkipVTablePointerInitialization(ASTContext &Context,
  680. const CXXDestructorDecl *Dtor) {
  681. if (!Dtor->hasTrivialBody())
  682. return false;
  683. // Check the fields.
  684. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  685. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  686. E = ClassDecl->field_end(); I != E; ++I) {
  687. const FieldDecl *Field = *I;
  688. if (!FieldHasTrivialDestructorBody(Context, Field))
  689. return false;
  690. }
  691. return true;
  692. }
  693. /// EmitDestructorBody - Emits the body of the current destructor.
  694. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  695. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  696. CXXDtorType DtorType = CurGD.getDtorType();
  697. // The call to operator delete in a deleting destructor happens
  698. // outside of the function-try-block, which means it's always
  699. // possible to delegate the destructor body to the complete
  700. // destructor. Do so.
  701. if (DtorType == Dtor_Deleting) {
  702. EnterDtorCleanups(Dtor, Dtor_Deleting);
  703. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  704. LoadCXXThis());
  705. PopCleanupBlock();
  706. return;
  707. }
  708. Stmt *Body = Dtor->getBody();
  709. // If the body is a function-try-block, enter the try before
  710. // anything else.
  711. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  712. if (isTryBody)
  713. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  714. // Enter the epilogue cleanups.
  715. RunCleanupsScope DtorEpilogue(*this);
  716. // If this is the complete variant, just invoke the base variant;
  717. // the epilogue will destruct the virtual bases. But we can't do
  718. // this optimization if the body is a function-try-block, because
  719. // we'd introduce *two* handler blocks.
  720. switch (DtorType) {
  721. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  722. case Dtor_Complete:
  723. // Enter the cleanup scopes for virtual bases.
  724. EnterDtorCleanups(Dtor, Dtor_Complete);
  725. if (!isTryBody) {
  726. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  727. LoadCXXThis());
  728. break;
  729. }
  730. // Fallthrough: act like we're in the base variant.
  731. case Dtor_Base:
  732. // Enter the cleanup scopes for fields and non-virtual bases.
  733. EnterDtorCleanups(Dtor, Dtor_Base);
  734. // Initialize the vtable pointers before entering the body.
  735. if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
  736. InitializeVTablePointers(Dtor->getParent());
  737. if (isTryBody)
  738. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  739. else if (Body)
  740. EmitStmt(Body);
  741. else {
  742. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  743. // nothing to do besides what's in the epilogue
  744. }
  745. // -fapple-kext must inline any call to this dtor into
  746. // the caller's body.
  747. if (getContext().getLangOptions().AppleKext)
  748. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  749. break;
  750. }
  751. // Jump out through the epilogue cleanups.
  752. DtorEpilogue.ForceCleanup();
  753. // Exit the try if applicable.
  754. if (isTryBody)
  755. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  756. }
  757. namespace {
  758. /// Call the operator delete associated with the current destructor.
  759. struct CallDtorDelete : EHScopeStack::Cleanup {
  760. CallDtorDelete() {}
  761. void Emit(CodeGenFunction &CGF, Flags flags) {
  762. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  763. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  764. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  765. CGF.getContext().getTagDeclType(ClassDecl));
  766. }
  767. };
  768. class DestroyField : public EHScopeStack::Cleanup {
  769. const FieldDecl *field;
  770. CodeGenFunction::Destroyer &destroyer;
  771. bool useEHCleanupForArray;
  772. public:
  773. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  774. bool useEHCleanupForArray)
  775. : field(field), destroyer(*destroyer),
  776. useEHCleanupForArray(useEHCleanupForArray) {}
  777. void Emit(CodeGenFunction &CGF, Flags flags) {
  778. // Find the address of the field.
  779. llvm::Value *thisValue = CGF.LoadCXXThis();
  780. LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
  781. assert(LV.isSimple());
  782. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  783. flags.isForNormalCleanup() && useEHCleanupForArray);
  784. }
  785. };
  786. }
  787. /// EmitDtorEpilogue - Emit all code that comes at the end of class's
  788. /// destructor. This is to call destructors on members and base classes
  789. /// in reverse order of their construction.
  790. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  791. CXXDtorType DtorType) {
  792. assert(!DD->isTrivial() &&
  793. "Should not emit dtor epilogue for trivial dtor!");
  794. // The deleting-destructor phase just needs to call the appropriate
  795. // operator delete that Sema picked up.
  796. if (DtorType == Dtor_Deleting) {
  797. assert(DD->getOperatorDelete() &&
  798. "operator delete missing - EmitDtorEpilogue");
  799. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  800. return;
  801. }
  802. const CXXRecordDecl *ClassDecl = DD->getParent();
  803. // The complete-destructor phase just destructs all the virtual bases.
  804. if (DtorType == Dtor_Complete) {
  805. // We push them in the forward order so that they'll be popped in
  806. // the reverse order.
  807. for (CXXRecordDecl::base_class_const_iterator I =
  808. ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
  809. I != E; ++I) {
  810. const CXXBaseSpecifier &Base = *I;
  811. CXXRecordDecl *BaseClassDecl
  812. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  813. // Ignore trivial destructors.
  814. if (BaseClassDecl->hasTrivialDestructor())
  815. continue;
  816. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  817. BaseClassDecl,
  818. /*BaseIsVirtual*/ true);
  819. }
  820. return;
  821. }
  822. assert(DtorType == Dtor_Base);
  823. // Destroy non-virtual bases.
  824. for (CXXRecordDecl::base_class_const_iterator I =
  825. ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
  826. const CXXBaseSpecifier &Base = *I;
  827. // Ignore virtual bases.
  828. if (Base.isVirtual())
  829. continue;
  830. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  831. // Ignore trivial destructors.
  832. if (BaseClassDecl->hasTrivialDestructor())
  833. continue;
  834. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  835. BaseClassDecl,
  836. /*BaseIsVirtual*/ false);
  837. }
  838. // Destroy direct fields.
  839. SmallVector<const FieldDecl *, 16> FieldDecls;
  840. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  841. E = ClassDecl->field_end(); I != E; ++I) {
  842. const FieldDecl *field = *I;
  843. QualType type = field->getType();
  844. QualType::DestructionKind dtorKind = type.isDestructedType();
  845. if (!dtorKind) continue;
  846. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  847. EHStack.pushCleanup<DestroyField>(cleanupKind, field,
  848. getDestroyer(dtorKind),
  849. cleanupKind & EHCleanup);
  850. }
  851. }
  852. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  853. /// constructor for each of several members of an array.
  854. ///
  855. /// \param ctor the constructor to call for each element
  856. /// \param argBegin,argEnd the arguments to evaluate and pass to the
  857. /// constructor
  858. /// \param arrayType the type of the array to initialize
  859. /// \param arrayBegin an arrayType*
  860. /// \param zeroInitialize true if each element should be
  861. /// zero-initialized before it is constructed
  862. void
  863. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  864. const ConstantArrayType *arrayType,
  865. llvm::Value *arrayBegin,
  866. CallExpr::const_arg_iterator argBegin,
  867. CallExpr::const_arg_iterator argEnd,
  868. bool zeroInitialize) {
  869. QualType elementType;
  870. llvm::Value *numElements =
  871. emitArrayLength(arrayType, elementType, arrayBegin);
  872. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
  873. argBegin, argEnd, zeroInitialize);
  874. }
  875. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  876. /// constructor for each of several members of an array.
  877. ///
  878. /// \param ctor the constructor to call for each element
  879. /// \param numElements the number of elements in the array;
  880. /// may be zero
  881. /// \param argBegin,argEnd the arguments to evaluate and pass to the
  882. /// constructor
  883. /// \param arrayBegin a T*, where T is the type constructed by ctor
  884. /// \param zeroInitialize true if each element should be
  885. /// zero-initialized before it is constructed
  886. void
  887. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  888. llvm::Value *numElements,
  889. llvm::Value *arrayBegin,
  890. CallExpr::const_arg_iterator argBegin,
  891. CallExpr::const_arg_iterator argEnd,
  892. bool zeroInitialize) {
  893. // It's legal for numElements to be zero. This can happen both
  894. // dynamically, because x can be zero in 'new A[x]', and statically,
  895. // because of GCC extensions that permit zero-length arrays. There
  896. // are probably legitimate places where we could assume that this
  897. // doesn't happen, but it's not clear that it's worth it.
  898. llvm::BranchInst *zeroCheckBranch = 0;
  899. // Optimize for a constant count.
  900. llvm::ConstantInt *constantCount
  901. = dyn_cast<llvm::ConstantInt>(numElements);
  902. if (constantCount) {
  903. // Just skip out if the constant count is zero.
  904. if (constantCount->isZero()) return;
  905. // Otherwise, emit the check.
  906. } else {
  907. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  908. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  909. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  910. EmitBlock(loopBB);
  911. }
  912. // Find the end of the array.
  913. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  914. "arrayctor.end");
  915. // Enter the loop, setting up a phi for the current location to initialize.
  916. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  917. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  918. EmitBlock(loopBB);
  919. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  920. "arrayctor.cur");
  921. cur->addIncoming(arrayBegin, entryBB);
  922. // Inside the loop body, emit the constructor call on the array element.
  923. QualType type = getContext().getTypeDeclType(ctor->getParent());
  924. // Zero initialize the storage, if requested.
  925. if (zeroInitialize)
  926. EmitNullInitialization(cur, type);
  927. // C++ [class.temporary]p4:
  928. // There are two contexts in which temporaries are destroyed at a different
  929. // point than the end of the full-expression. The first context is when a
  930. // default constructor is called to initialize an element of an array.
  931. // If the constructor has one or more default arguments, the destruction of
  932. // every temporary created in a default argument expression is sequenced
  933. // before the construction of the next array element, if any.
  934. {
  935. RunCleanupsScope Scope(*this);
  936. // Evaluate the constructor and its arguments in a regular
  937. // partial-destroy cleanup.
  938. if (getLangOptions().Exceptions &&
  939. !ctor->getParent()->hasTrivialDestructor()) {
  940. Destroyer *destroyer = destroyCXXObject;
  941. pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
  942. }
  943. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
  944. cur, argBegin, argEnd);
  945. }
  946. // Go to the next element.
  947. llvm::Value *next =
  948. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  949. "arrayctor.next");
  950. cur->addIncoming(next, Builder.GetInsertBlock());
  951. // Check whether that's the end of the loop.
  952. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  953. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  954. Builder.CreateCondBr(done, contBB, loopBB);
  955. // Patch the earlier check to skip over the loop.
  956. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  957. EmitBlock(contBB);
  958. }
  959. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  960. llvm::Value *addr,
  961. QualType type) {
  962. const RecordType *rtype = type->castAs<RecordType>();
  963. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  964. const CXXDestructorDecl *dtor = record->getDestructor();
  965. assert(!dtor->isTrivial());
  966. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  967. addr);
  968. }
  969. void
  970. CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  971. CXXCtorType Type, bool ForVirtualBase,
  972. llvm::Value *This,
  973. CallExpr::const_arg_iterator ArgBeg,
  974. CallExpr::const_arg_iterator ArgEnd) {
  975. CGDebugInfo *DI = getDebugInfo();
  976. if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
  977. // If debug info for this class has been emitted then this is the right time
  978. // to do so.
  979. const CXXRecordDecl *Parent = D->getParent();
  980. DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
  981. Parent->getLocation());
  982. }
  983. if (D->isTrivial()) {
  984. if (ArgBeg == ArgEnd) {
  985. // Trivial default constructor, no codegen required.
  986. assert(D->isDefaultConstructor() &&
  987. "trivial 0-arg ctor not a default ctor");
  988. return;
  989. }
  990. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  991. assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
  992. const Expr *E = (*ArgBeg);
  993. QualType Ty = E->getType();
  994. llvm::Value *Src = EmitLValue(E).getAddress();
  995. EmitAggregateCopy(This, Src, Ty);
  996. return;
  997. }
  998. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
  999. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
  1000. EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
  1001. }
  1002. void
  1003. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1004. llvm::Value *This, llvm::Value *Src,
  1005. CallExpr::const_arg_iterator ArgBeg,
  1006. CallExpr::const_arg_iterator ArgEnd) {
  1007. if (D->isTrivial()) {
  1008. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1009. assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
  1010. EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
  1011. return;
  1012. }
  1013. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
  1014. clang::Ctor_Complete);
  1015. assert(D->isInstance() &&
  1016. "Trying to emit a member call expr on a static method!");
  1017. const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
  1018. CallArgList Args;
  1019. // Push the this ptr.
  1020. Args.add(RValue::get(This), D->getThisType(getContext()));
  1021. // Push the src ptr.
  1022. QualType QT = *(FPT->arg_type_begin());
  1023. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1024. Src = Builder.CreateBitCast(Src, t);
  1025. Args.add(RValue::get(Src), QT);
  1026. // Skip over first argument (Src).
  1027. ++ArgBeg;
  1028. CallExpr::const_arg_iterator Arg = ArgBeg;
  1029. for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
  1030. E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
  1031. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1032. EmitCallArg(Args, *Arg, *I);
  1033. }
  1034. // Either we've emitted all the call args, or we have a call to a
  1035. // variadic function.
  1036. assert((Arg == ArgEnd || FPT->isVariadic()) &&
  1037. "Extra arguments in non-variadic function!");
  1038. // If we still have any arguments, emit them using the type of the argument.
  1039. for (; Arg != ArgEnd; ++Arg) {
  1040. QualType ArgType = Arg->getType();
  1041. EmitCallArg(Args, *Arg, ArgType);
  1042. }
  1043. EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
  1044. ReturnValueSlot(), Args, D);
  1045. }
  1046. void
  1047. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1048. CXXCtorType CtorType,
  1049. const FunctionArgList &Args) {
  1050. CallArgList DelegateArgs;
  1051. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1052. assert(I != E && "no parameters to constructor");
  1053. // this
  1054. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1055. ++I;
  1056. // vtt
  1057. if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
  1058. /*ForVirtualBase=*/false)) {
  1059. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1060. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1061. if (CodeGenVTables::needsVTTParameter(CurGD)) {
  1062. assert(I != E && "cannot skip vtt parameter, already done with args");
  1063. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1064. ++I;
  1065. }
  1066. }
  1067. // Explicit arguments.
  1068. for (; I != E; ++I) {
  1069. const VarDecl *param = *I;
  1070. EmitDelegateCallArg(DelegateArgs, param);
  1071. }
  1072. EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
  1073. CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
  1074. ReturnValueSlot(), DelegateArgs, Ctor);
  1075. }
  1076. namespace {
  1077. struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
  1078. const CXXDestructorDecl *Dtor;
  1079. llvm::Value *Addr;
  1080. CXXDtorType Type;
  1081. CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
  1082. CXXDtorType Type)
  1083. : Dtor(D), Addr(Addr), Type(Type) {}
  1084. void Emit(CodeGenFunction &CGF, Flags flags) {
  1085. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1086. Addr);
  1087. }
  1088. };
  1089. }
  1090. void
  1091. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1092. const FunctionArgList &Args) {
  1093. assert(Ctor->isDelegatingConstructor());
  1094. llvm::Value *ThisPtr = LoadCXXThis();
  1095. AggValueSlot AggSlot =
  1096. AggValueSlot::forAddr(ThisPtr, Qualifiers(),
  1097. AggValueSlot::IsDestructed,
  1098. AggValueSlot::DoesNotNeedGCBarriers,
  1099. AggValueSlot::IsNotAliased);
  1100. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1101. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1102. if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1103. CXXDtorType Type =
  1104. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1105. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1106. ClassDecl->getDestructor(),
  1107. ThisPtr, Type);
  1108. }
  1109. }
  1110. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1111. CXXDtorType Type,
  1112. bool ForVirtualBase,
  1113. llvm::Value *This) {
  1114. llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
  1115. ForVirtualBase);
  1116. llvm::Value *Callee = 0;
  1117. if (getContext().getLangOptions().AppleKext)
  1118. Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
  1119. DD->getParent());
  1120. if (!Callee)
  1121. Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
  1122. EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
  1123. }
  1124. namespace {
  1125. struct CallLocalDtor : EHScopeStack::Cleanup {
  1126. const CXXDestructorDecl *Dtor;
  1127. llvm::Value *Addr;
  1128. CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
  1129. : Dtor(D), Addr(Addr) {}
  1130. void Emit(CodeGenFunction &CGF, Flags flags) {
  1131. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1132. /*ForVirtualBase=*/false, Addr);
  1133. }
  1134. };
  1135. }
  1136. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1137. llvm::Value *Addr) {
  1138. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1139. }
  1140. void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
  1141. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1142. if (!ClassDecl) return;
  1143. if (ClassDecl->hasTrivialDestructor()) return;
  1144. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1145. assert(D && D->isUsed() && "destructor not marked as used!");
  1146. PushDestructorCleanup(D, Addr);
  1147. }
  1148. llvm::Value *
  1149. CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
  1150. const CXXRecordDecl *ClassDecl,
  1151. const CXXRecordDecl *BaseClassDecl) {
  1152. llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
  1153. CharUnits VBaseOffsetOffset =
  1154. CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
  1155. llvm::Value *VBaseOffsetPtr =
  1156. Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
  1157. "vbase.offset.ptr");
  1158. llvm::Type *PtrDiffTy =
  1159. ConvertType(getContext().getPointerDiffType());
  1160. VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
  1161. PtrDiffTy->getPointerTo());
  1162. llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
  1163. return VBaseOffset;
  1164. }
  1165. void
  1166. CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
  1167. const CXXRecordDecl *NearestVBase,
  1168. CharUnits OffsetFromNearestVBase,
  1169. llvm::Constant *VTable,
  1170. const CXXRecordDecl *VTableClass) {
  1171. const CXXRecordDecl *RD = Base.getBase();
  1172. // Compute the address point.
  1173. llvm::Value *VTableAddressPoint;
  1174. // Check if we need to use a vtable from the VTT.
  1175. if (CodeGenVTables::needsVTTParameter(CurGD) &&
  1176. (RD->getNumVBases() || NearestVBase)) {
  1177. // Get the secondary vpointer index.
  1178. uint64_t VirtualPointerIndex =
  1179. CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
  1180. /// Load the VTT.
  1181. llvm::Value *VTT = LoadCXXVTT();
  1182. if (VirtualPointerIndex)
  1183. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
  1184. // And load the address point from the VTT.
  1185. VTableAddressPoint = Builder.CreateLoad(VTT);
  1186. } else {
  1187. uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
  1188. VTableAddressPoint =
  1189. Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
  1190. }
  1191. // Compute where to store the address point.
  1192. llvm::Value *VirtualOffset = 0;
  1193. CharUnits NonVirtualOffset = CharUnits::Zero();
  1194. if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
  1195. // We need to use the virtual base offset offset because the virtual base
  1196. // might have a different offset in the most derived class.
  1197. VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
  1198. NearestVBase);
  1199. NonVirtualOffset = OffsetFromNearestVBase;
  1200. } else {
  1201. // We can just use the base offset in the complete class.
  1202. NonVirtualOffset = Base.getBaseOffset();
  1203. }
  1204. // Apply the offsets.
  1205. llvm::Value *VTableField = LoadCXXThis();
  1206. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1207. VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
  1208. NonVirtualOffset,
  1209. VirtualOffset);
  1210. // Finally, store the address point.
  1211. llvm::Type *AddressPointPtrTy =
  1212. VTableAddressPoint->getType()->getPointerTo();
  1213. VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
  1214. Builder.CreateStore(VTableAddressPoint, VTableField);
  1215. }
  1216. void
  1217. CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
  1218. const CXXRecordDecl *NearestVBase,
  1219. CharUnits OffsetFromNearestVBase,
  1220. bool BaseIsNonVirtualPrimaryBase,
  1221. llvm::Constant *VTable,
  1222. const CXXRecordDecl *VTableClass,
  1223. VisitedVirtualBasesSetTy& VBases) {
  1224. // If this base is a non-virtual primary base the address point has already
  1225. // been set.
  1226. if (!BaseIsNonVirtualPrimaryBase) {
  1227. // Initialize the vtable pointer for this base.
  1228. InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
  1229. VTable, VTableClass);
  1230. }
  1231. const CXXRecordDecl *RD = Base.getBase();
  1232. // Traverse bases.
  1233. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1234. E = RD->bases_end(); I != E; ++I) {
  1235. CXXRecordDecl *BaseDecl
  1236. = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1237. // Ignore classes without a vtable.
  1238. if (!BaseDecl->isDynamicClass())
  1239. continue;
  1240. CharUnits BaseOffset;
  1241. CharUnits BaseOffsetFromNearestVBase;
  1242. bool BaseDeclIsNonVirtualPrimaryBase;
  1243. if (I->isVirtual()) {
  1244. // Check if we've visited this virtual base before.
  1245. if (!VBases.insert(BaseDecl))
  1246. continue;
  1247. const ASTRecordLayout &Layout =
  1248. getContext().getASTRecordLayout(VTableClass);
  1249. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  1250. BaseOffsetFromNearestVBase = CharUnits::Zero();
  1251. BaseDeclIsNonVirtualPrimaryBase = false;
  1252. } else {
  1253. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1254. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  1255. BaseOffsetFromNearestVBase =
  1256. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  1257. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  1258. }
  1259. InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
  1260. I->isVirtual() ? BaseDecl : NearestVBase,
  1261. BaseOffsetFromNearestVBase,
  1262. BaseDeclIsNonVirtualPrimaryBase,
  1263. VTable, VTableClass, VBases);
  1264. }
  1265. }
  1266. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  1267. // Ignore classes without a vtable.
  1268. if (!RD->isDynamicClass())
  1269. return;
  1270. // Get the VTable.
  1271. llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
  1272. // Initialize the vtable pointers for this class and all of its bases.
  1273. VisitedVirtualBasesSetTy VBases;
  1274. InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
  1275. /*NearestVBase=*/0,
  1276. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1277. /*BaseIsNonVirtualPrimaryBase=*/false,
  1278. VTable, RD, VBases);
  1279. }
  1280. llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
  1281. llvm::Type *Ty) {
  1282. llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
  1283. return Builder.CreateLoad(VTablePtrSrc, "vtable");
  1284. }
  1285. static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
  1286. const Expr *E = Base;
  1287. while (true) {
  1288. E = E->IgnoreParens();
  1289. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1290. if (CE->getCastKind() == CK_DerivedToBase ||
  1291. CE->getCastKind() == CK_UncheckedDerivedToBase ||
  1292. CE->getCastKind() == CK_NoOp) {
  1293. E = CE->getSubExpr();
  1294. continue;
  1295. }
  1296. }
  1297. break;
  1298. }
  1299. QualType DerivedType = E->getType();
  1300. if (const PointerType *PTy = DerivedType->getAs<PointerType>())
  1301. DerivedType = PTy->getPointeeType();
  1302. return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
  1303. }
  1304. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  1305. // quite what we want.
  1306. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  1307. while (true) {
  1308. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  1309. E = PE->getSubExpr();
  1310. continue;
  1311. }
  1312. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1313. if (CE->getCastKind() == CK_NoOp) {
  1314. E = CE->getSubExpr();
  1315. continue;
  1316. }
  1317. }
  1318. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1319. if (UO->getOpcode() == UO_Extension) {
  1320. E = UO->getSubExpr();
  1321. continue;
  1322. }
  1323. }
  1324. return E;
  1325. }
  1326. }
  1327. /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
  1328. /// function call on the given expr can be devirtualized.
  1329. /// expr can be devirtualized.
  1330. static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
  1331. const CXXMethodDecl *MD) {
  1332. // If the most derived class is marked final, we know that no subclass can
  1333. // override this member function and so we can devirtualize it. For example:
  1334. //
  1335. // struct A { virtual void f(); }
  1336. // struct B final : A { };
  1337. //
  1338. // void f(B *b) {
  1339. // b->f();
  1340. // }
  1341. //
  1342. const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
  1343. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  1344. return true;
  1345. // If the member function is marked 'final', we know that it can't be
  1346. // overridden and can therefore devirtualize it.
  1347. if (MD->hasAttr<FinalAttr>())
  1348. return true;
  1349. // Similarly, if the class itself is marked 'final' it can't be overridden
  1350. // and we can therefore devirtualize the member function call.
  1351. if (MD->getParent()->hasAttr<FinalAttr>())
  1352. return true;
  1353. Base = skipNoOpCastsAndParens(Base);
  1354. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1355. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1356. // This is a record decl. We know the type and can devirtualize it.
  1357. return VD->getType()->isRecordType();
  1358. }
  1359. return false;
  1360. }
  1361. // We can always devirtualize calls on temporary object expressions.
  1362. if (isa<CXXConstructExpr>(Base))
  1363. return true;
  1364. // And calls on bound temporaries.
  1365. if (isa<CXXBindTemporaryExpr>(Base))
  1366. return true;
  1367. // Check if this is a call expr that returns a record type.
  1368. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  1369. return CE->getCallReturnType()->isRecordType();
  1370. // We can't devirtualize the call.
  1371. return false;
  1372. }
  1373. static bool UseVirtualCall(ASTContext &Context,
  1374. const CXXOperatorCallExpr *CE,
  1375. const CXXMethodDecl *MD) {
  1376. if (!MD->isVirtual())
  1377. return false;
  1378. // When building with -fapple-kext, all calls must go through the vtable since
  1379. // the kernel linker can do runtime patching of vtables.
  1380. if (Context.getLangOptions().AppleKext)
  1381. return true;
  1382. return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
  1383. }
  1384. llvm::Value *
  1385. CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1386. const CXXMethodDecl *MD,
  1387. llvm::Value *This) {
  1388. const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
  1389. llvm::Type *Ty =
  1390. CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
  1391. FPT->isVariadic());
  1392. if (UseVirtualCall(getContext(), E, MD))
  1393. return BuildVirtualCall(MD, This, Ty);
  1394. return CGM.GetAddrOfFunction(MD, Ty);
  1395. }