CGClass.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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 "CGBlocks.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGRecordLayout.h"
  16. #include "CodeGenFunction.h"
  17. #include "CGCXXABI.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/AST/StmtCXX.h"
  23. #include "clang/Basic/TargetBuiltins.h"
  24. #include "clang/CodeGen/CGFunctionInfo.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. using namespace clang;
  27. using namespace CodeGen;
  28. static CharUnits
  29. ComputeNonVirtualBaseClassOffset(ASTContext &Context,
  30. const CXXRecordDecl *DerivedClass,
  31. CastExpr::path_const_iterator Start,
  32. CastExpr::path_const_iterator End) {
  33. CharUnits Offset = CharUnits::Zero();
  34. const CXXRecordDecl *RD = DerivedClass;
  35. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  36. const CXXBaseSpecifier *Base = *I;
  37. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  38. // Get the layout.
  39. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  40. const CXXRecordDecl *BaseDecl =
  41. cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
  42. // Add the offset.
  43. Offset += Layout.getBaseClassOffset(BaseDecl);
  44. RD = BaseDecl;
  45. }
  46. return Offset;
  47. }
  48. llvm::Constant *
  49. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  50. CastExpr::path_const_iterator PathBegin,
  51. CastExpr::path_const_iterator PathEnd) {
  52. assert(PathBegin != PathEnd && "Base path should not be empty!");
  53. CharUnits Offset =
  54. ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
  55. PathBegin, PathEnd);
  56. if (Offset.isZero())
  57. return 0;
  58. llvm::Type *PtrDiffTy =
  59. Types.ConvertType(getContext().getPointerDiffType());
  60. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  61. }
  62. /// Gets the address of a direct base class within a complete object.
  63. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  64. /// when the type is known to be complete (e.g. in complete destructors).
  65. ///
  66. /// The object pointed to by 'This' is assumed to be non-null.
  67. llvm::Value *
  68. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
  69. const CXXRecordDecl *Derived,
  70. const CXXRecordDecl *Base,
  71. bool BaseIsVirtual) {
  72. // 'this' must be a pointer (in some address space) to Derived.
  73. assert(This->getType()->isPointerTy() &&
  74. cast<llvm::PointerType>(This->getType())->getElementType()
  75. == ConvertType(Derived));
  76. // Compute the offset of the virtual base.
  77. CharUnits Offset;
  78. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  79. if (BaseIsVirtual)
  80. Offset = Layout.getVBaseClassOffset(Base);
  81. else
  82. Offset = Layout.getBaseClassOffset(Base);
  83. // Shift and cast down to the base type.
  84. // TODO: for complete types, this should be possible with a GEP.
  85. llvm::Value *V = This;
  86. if (Offset.isPositive()) {
  87. V = Builder.CreateBitCast(V, Int8PtrTy);
  88. V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
  89. }
  90. V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
  91. return V;
  92. }
  93. static llvm::Value *
  94. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
  95. CharUnits nonVirtualOffset,
  96. llvm::Value *virtualOffset) {
  97. // Assert that we have something to do.
  98. assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
  99. // Compute the offset from the static and dynamic components.
  100. llvm::Value *baseOffset;
  101. if (!nonVirtualOffset.isZero()) {
  102. baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
  103. nonVirtualOffset.getQuantity());
  104. if (virtualOffset) {
  105. baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
  106. }
  107. } else {
  108. baseOffset = virtualOffset;
  109. }
  110. // Apply the base offset.
  111. ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
  112. ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
  113. return ptr;
  114. }
  115. llvm::Value *
  116. CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
  117. const CXXRecordDecl *Derived,
  118. CastExpr::path_const_iterator PathBegin,
  119. CastExpr::path_const_iterator PathEnd,
  120. bool NullCheckValue) {
  121. assert(PathBegin != PathEnd && "Base path should not be empty!");
  122. CastExpr::path_const_iterator Start = PathBegin;
  123. const CXXRecordDecl *VBase = 0;
  124. // Sema has done some convenient canonicalization here: if the
  125. // access path involved any virtual steps, the conversion path will
  126. // *start* with a step down to the correct virtual base subobject,
  127. // and hence will not require any further steps.
  128. if ((*Start)->isVirtual()) {
  129. VBase =
  130. cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
  131. ++Start;
  132. }
  133. // Compute the static offset of the ultimate destination within its
  134. // allocating subobject (the virtual base, if there is one, or else
  135. // the "complete" object that we see).
  136. CharUnits NonVirtualOffset =
  137. ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
  138. Start, PathEnd);
  139. // If there's a virtual step, we can sometimes "devirtualize" it.
  140. // For now, that's limited to when the derived type is final.
  141. // TODO: "devirtualize" this for accesses to known-complete objects.
  142. if (VBase && Derived->hasAttr<FinalAttr>()) {
  143. const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
  144. CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
  145. NonVirtualOffset += vBaseOffset;
  146. VBase = 0; // we no longer have a virtual step
  147. }
  148. // Get the base pointer type.
  149. llvm::Type *BasePtrTy =
  150. ConvertType((PathEnd[-1])->getType())->getPointerTo();
  151. // If the static offset is zero and we don't have a virtual step,
  152. // just do a bitcast; null checks are unnecessary.
  153. if (NonVirtualOffset.isZero() && !VBase) {
  154. return Builder.CreateBitCast(Value, BasePtrTy);
  155. }
  156. llvm::BasicBlock *origBB = 0;
  157. llvm::BasicBlock *endBB = 0;
  158. // Skip over the offset (and the vtable load) if we're supposed to
  159. // null-check the pointer.
  160. if (NullCheckValue) {
  161. origBB = Builder.GetInsertBlock();
  162. llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
  163. endBB = createBasicBlock("cast.end");
  164. llvm::Value *isNull = Builder.CreateIsNull(Value);
  165. Builder.CreateCondBr(isNull, endBB, notNullBB);
  166. EmitBlock(notNullBB);
  167. }
  168. // Compute the virtual offset.
  169. llvm::Value *VirtualOffset = 0;
  170. if (VBase) {
  171. VirtualOffset =
  172. CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
  173. }
  174. // Apply both offsets.
  175. Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
  176. NonVirtualOffset,
  177. VirtualOffset);
  178. // Cast to the destination type.
  179. Value = Builder.CreateBitCast(Value, BasePtrTy);
  180. // Build a phi if we needed a null check.
  181. if (NullCheckValue) {
  182. llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
  183. Builder.CreateBr(endBB);
  184. EmitBlock(endBB);
  185. llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
  186. PHI->addIncoming(Value, notNullBB);
  187. PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
  188. Value = PHI;
  189. }
  190. return Value;
  191. }
  192. llvm::Value *
  193. CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
  194. const CXXRecordDecl *Derived,
  195. CastExpr::path_const_iterator PathBegin,
  196. CastExpr::path_const_iterator PathEnd,
  197. bool NullCheckValue) {
  198. assert(PathBegin != PathEnd && "Base path should not be empty!");
  199. QualType DerivedTy =
  200. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  201. llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
  202. llvm::Value *NonVirtualOffset =
  203. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  204. if (!NonVirtualOffset) {
  205. // No offset, we can just cast back.
  206. return Builder.CreateBitCast(Value, DerivedPtrTy);
  207. }
  208. llvm::BasicBlock *CastNull = 0;
  209. llvm::BasicBlock *CastNotNull = 0;
  210. llvm::BasicBlock *CastEnd = 0;
  211. if (NullCheckValue) {
  212. CastNull = createBasicBlock("cast.null");
  213. CastNotNull = createBasicBlock("cast.notnull");
  214. CastEnd = createBasicBlock("cast.end");
  215. llvm::Value *IsNull = Builder.CreateIsNull(Value);
  216. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  217. EmitBlock(CastNotNull);
  218. }
  219. // Apply the offset.
  220. Value = Builder.CreateBitCast(Value, Int8PtrTy);
  221. Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
  222. "sub.ptr");
  223. // Just cast.
  224. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  225. if (NullCheckValue) {
  226. Builder.CreateBr(CastEnd);
  227. EmitBlock(CastNull);
  228. Builder.CreateBr(CastEnd);
  229. EmitBlock(CastEnd);
  230. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  231. PHI->addIncoming(Value, CastNotNull);
  232. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
  233. CastNull);
  234. Value = PHI;
  235. }
  236. return Value;
  237. }
  238. llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
  239. bool ForVirtualBase,
  240. bool Delegating) {
  241. if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
  242. // This constructor/destructor does not need a VTT parameter.
  243. return 0;
  244. }
  245. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
  246. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  247. llvm::Value *VTT;
  248. uint64_t SubVTTIndex;
  249. if (Delegating) {
  250. // If this is a delegating constructor call, just load the VTT.
  251. return LoadCXXVTT();
  252. } else if (RD == Base) {
  253. // If the record matches the base, this is the complete ctor/dtor
  254. // variant calling the base variant in a class with virtual bases.
  255. assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
  256. "doing no-op VTT offset in base dtor/ctor?");
  257. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  258. SubVTTIndex = 0;
  259. } else {
  260. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  261. CharUnits BaseOffset = ForVirtualBase ?
  262. Layout.getVBaseClassOffset(Base) :
  263. Layout.getBaseClassOffset(Base);
  264. SubVTTIndex =
  265. CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  266. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  267. }
  268. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  269. // A VTT parameter was passed to the constructor, use it.
  270. VTT = LoadCXXVTT();
  271. VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
  272. } else {
  273. // We're the complete constructor, so get the VTT by name.
  274. VTT = CGM.getVTables().GetAddrOfVTT(RD);
  275. VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
  276. }
  277. return VTT;
  278. }
  279. namespace {
  280. /// Call the destructor for a direct base class.
  281. struct CallBaseDtor : EHScopeStack::Cleanup {
  282. const CXXRecordDecl *BaseClass;
  283. bool BaseIsVirtual;
  284. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  285. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  286. void Emit(CodeGenFunction &CGF, Flags flags) {
  287. const CXXRecordDecl *DerivedClass =
  288. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  289. const CXXDestructorDecl *D = BaseClass->getDestructor();
  290. llvm::Value *Addr =
  291. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
  292. DerivedClass, BaseClass,
  293. BaseIsVirtual);
  294. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
  295. /*Delegating=*/false, Addr);
  296. }
  297. };
  298. /// A visitor which checks whether an initializer uses 'this' in a
  299. /// way which requires the vtable to be properly set.
  300. struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
  301. typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
  302. bool UsesThis;
  303. DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
  304. // Black-list all explicit and implicit references to 'this'.
  305. //
  306. // Do we need to worry about external references to 'this' derived
  307. // from arbitrary code? If so, then anything which runs arbitrary
  308. // external code might potentially access the vtable.
  309. void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
  310. };
  311. }
  312. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  313. DynamicThisUseChecker Checker(C);
  314. Checker.Visit(const_cast<Expr*>(Init));
  315. return Checker.UsesThis;
  316. }
  317. static void EmitBaseInitializer(CodeGenFunction &CGF,
  318. const CXXRecordDecl *ClassDecl,
  319. CXXCtorInitializer *BaseInit,
  320. CXXCtorType CtorType) {
  321. assert(BaseInit->isBaseInitializer() &&
  322. "Must have base initializer!");
  323. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  324. const Type *BaseType = BaseInit->getBaseClass();
  325. CXXRecordDecl *BaseClassDecl =
  326. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  327. bool isBaseVirtual = BaseInit->isBaseVirtual();
  328. // The base constructor doesn't construct virtual bases.
  329. if (CtorType == Ctor_Base && isBaseVirtual)
  330. return;
  331. // If the initializer for the base (other than the constructor
  332. // itself) accesses 'this' in any way, we need to initialize the
  333. // vtables.
  334. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  335. CGF.InitializeVTablePointers(ClassDecl);
  336. // We can pretend to be a complete class because it only matters for
  337. // virtual bases, and we only do virtual bases for complete ctors.
  338. llvm::Value *V =
  339. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  340. BaseClassDecl,
  341. isBaseVirtual);
  342. CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
  343. AggValueSlot AggSlot =
  344. AggValueSlot::forAddr(V, Alignment, Qualifiers(),
  345. AggValueSlot::IsDestructed,
  346. AggValueSlot::DoesNotNeedGCBarriers,
  347. AggValueSlot::IsNotAliased);
  348. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  349. if (CGF.CGM.getLangOpts().Exceptions &&
  350. !BaseClassDecl->hasTrivialDestructor())
  351. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  352. isBaseVirtual);
  353. }
  354. static void EmitAggMemberInitializer(CodeGenFunction &CGF,
  355. LValue LHS,
  356. Expr *Init,
  357. llvm::Value *ArrayIndexVar,
  358. QualType T,
  359. ArrayRef<VarDecl *> ArrayIndexes,
  360. unsigned Index) {
  361. if (Index == ArrayIndexes.size()) {
  362. LValue LV = LHS;
  363. if (ArrayIndexVar) {
  364. // If we have an array index variable, load it and use it as an offset.
  365. // Then, increment the value.
  366. llvm::Value *Dest = LHS.getAddress();
  367. llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
  368. Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
  369. llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
  370. Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
  371. CGF.Builder.CreateStore(Next, ArrayIndexVar);
  372. // Update the LValue.
  373. LV.setAddress(Dest);
  374. CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
  375. LV.setAlignment(std::min(Align, LV.getAlignment()));
  376. }
  377. switch (CGF.getEvaluationKind(T)) {
  378. case TEK_Scalar:
  379. CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
  380. break;
  381. case TEK_Complex:
  382. CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
  383. break;
  384. case TEK_Aggregate: {
  385. AggValueSlot Slot =
  386. AggValueSlot::forLValue(LV,
  387. AggValueSlot::IsDestructed,
  388. AggValueSlot::DoesNotNeedGCBarriers,
  389. AggValueSlot::IsNotAliased);
  390. CGF.EmitAggExpr(Init, Slot);
  391. break;
  392. }
  393. }
  394. return;
  395. }
  396. const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
  397. assert(Array && "Array initialization without the array type?");
  398. llvm::Value *IndexVar
  399. = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
  400. assert(IndexVar && "Array index variable not loaded");
  401. // Initialize this index variable to zero.
  402. llvm::Value* Zero
  403. = llvm::Constant::getNullValue(
  404. CGF.ConvertType(CGF.getContext().getSizeType()));
  405. CGF.Builder.CreateStore(Zero, IndexVar);
  406. // Start the loop with a block that tests the condition.
  407. llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
  408. llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
  409. CGF.EmitBlock(CondBlock);
  410. llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
  411. // Generate: if (loop-index < number-of-elements) fall to the loop body,
  412. // otherwise, go to the block after the for-loop.
  413. uint64_t NumElements = Array->getSize().getZExtValue();
  414. llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
  415. llvm::Value *NumElementsPtr =
  416. llvm::ConstantInt::get(Counter->getType(), NumElements);
  417. llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
  418. "isless");
  419. // If the condition is true, execute the body.
  420. CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
  421. CGF.EmitBlock(ForBody);
  422. llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
  423. // Inside the loop body recurse to emit the inner loop or, eventually, the
  424. // constructor call.
  425. EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
  426. Array->getElementType(), ArrayIndexes, Index + 1);
  427. CGF.EmitBlock(ContinueBlock);
  428. // Emit the increment of the loop counter.
  429. llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
  430. Counter = CGF.Builder.CreateLoad(IndexVar);
  431. NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
  432. CGF.Builder.CreateStore(NextVal, IndexVar);
  433. // Finally, branch back up to the condition for the next iteration.
  434. CGF.EmitBranch(CondBlock);
  435. // Emit the fall-through block.
  436. CGF.EmitBlock(AfterFor, true);
  437. }
  438. static void EmitMemberInitializer(CodeGenFunction &CGF,
  439. const CXXRecordDecl *ClassDecl,
  440. CXXCtorInitializer *MemberInit,
  441. const CXXConstructorDecl *Constructor,
  442. FunctionArgList &Args) {
  443. assert(MemberInit->isAnyMemberInitializer() &&
  444. "Must have member initializer!");
  445. assert(MemberInit->getInit() && "Must have initializer!");
  446. // non-static data member initializers.
  447. FieldDecl *Field = MemberInit->getAnyMember();
  448. QualType FieldType = Field->getType();
  449. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  450. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  451. LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  452. if (MemberInit->isIndirectMemberInitializer()) {
  453. // If we are initializing an anonymous union field, drill down to
  454. // the field.
  455. IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
  456. IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
  457. IEnd = IndirectField->chain_end();
  458. for ( ; I != IEnd; ++I)
  459. LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
  460. FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
  461. } else {
  462. LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
  463. }
  464. // Special case: if we are in a copy or move constructor, and we are copying
  465. // an array of PODs or classes with trivial copy constructors, ignore the
  466. // AST and perform the copy we know is equivalent.
  467. // FIXME: This is hacky at best... if we had a bit more explicit information
  468. // in the AST, we could generalize it more easily.
  469. const ConstantArrayType *Array
  470. = CGF.getContext().getAsConstantArrayType(FieldType);
  471. if (Array && Constructor->isDefaulted() &&
  472. Constructor->isCopyOrMoveConstructor()) {
  473. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  474. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  475. if (BaseElementTy.isPODType(CGF.getContext()) ||
  476. (CE && CE->getConstructor()->isTrivial())) {
  477. // Find the source pointer. We know it's the last argument because
  478. // we know we're in an implicit copy constructor.
  479. unsigned SrcArgIndex = Args.size() - 1;
  480. llvm::Value *SrcPtr
  481. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  482. LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  483. LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
  484. // Copy the aggregate.
  485. CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
  486. LHS.isVolatileQualified());
  487. return;
  488. }
  489. }
  490. ArrayRef<VarDecl *> ArrayIndexes;
  491. if (MemberInit->getNumArrayIndices())
  492. ArrayIndexes = MemberInit->getArrayIndexes();
  493. CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
  494. }
  495. void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
  496. LValue LHS, Expr *Init,
  497. ArrayRef<VarDecl *> ArrayIndexes) {
  498. QualType FieldType = Field->getType();
  499. switch (getEvaluationKind(FieldType)) {
  500. case TEK_Scalar:
  501. if (LHS.isSimple()) {
  502. EmitExprAsInit(Init, Field, LHS, false);
  503. } else {
  504. RValue RHS = RValue::get(EmitScalarExpr(Init));
  505. EmitStoreThroughLValue(RHS, LHS);
  506. }
  507. break;
  508. case TEK_Complex:
  509. EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
  510. break;
  511. case TEK_Aggregate: {
  512. llvm::Value *ArrayIndexVar = 0;
  513. if (ArrayIndexes.size()) {
  514. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  515. // The LHS is a pointer to the first object we'll be constructing, as
  516. // a flat array.
  517. QualType BaseElementTy = getContext().getBaseElementType(FieldType);
  518. llvm::Type *BasePtr = ConvertType(BaseElementTy);
  519. BasePtr = llvm::PointerType::getUnqual(BasePtr);
  520. llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
  521. BasePtr);
  522. LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
  523. // Create an array index that will be used to walk over all of the
  524. // objects we're constructing.
  525. ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
  526. llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
  527. Builder.CreateStore(Zero, ArrayIndexVar);
  528. // Emit the block variables for the array indices, if any.
  529. for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
  530. EmitAutoVarDecl(*ArrayIndexes[I]);
  531. }
  532. EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
  533. ArrayIndexes, 0);
  534. }
  535. }
  536. // Ensure that we destroy this object if an exception is thrown
  537. // later in the constructor.
  538. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  539. if (needsEHCleanup(dtorKind))
  540. pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
  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. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  591. if (CGDebugInfo *DI = getDebugInfo())
  592. DI->EmitLocation(Builder, Ctor->getLocEnd());
  593. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
  594. return;
  595. }
  596. Stmt *Body = Ctor->getBody();
  597. // Enter the function-try-block before the constructor prologue if
  598. // applicable.
  599. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  600. if (IsTryBody)
  601. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  602. RunCleanupsScope RunCleanups(*this);
  603. // TODO: in restricted cases, we can emit the vbase initializers of
  604. // a complete ctor and then delegate to the base ctor.
  605. // Emit the constructor prologue, i.e. the base and member
  606. // initializers.
  607. EmitCtorPrologue(Ctor, CtorType, Args);
  608. // Emit the body of the statement.
  609. if (IsTryBody)
  610. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  611. else if (Body)
  612. EmitStmt(Body);
  613. // Emit any cleanup blocks associated with the member or base
  614. // initializers, which includes (along the exceptional path) the
  615. // destructors for those members and bases that were fully
  616. // constructed.
  617. RunCleanups.ForceCleanup();
  618. if (IsTryBody)
  619. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  620. }
  621. namespace {
  622. /// RAII object to indicate that codegen is copying the value representation
  623. /// instead of the object representation. Useful when copying a struct or
  624. /// class which has uninitialized members and we're only performing
  625. /// lvalue-to-rvalue conversion on the object but not its members.
  626. class CopyingValueRepresentation {
  627. public:
  628. explicit CopyingValueRepresentation(CodeGenFunction &CGF)
  629. : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
  630. SO.Bool = false;
  631. SO.Enum = false;
  632. CGF.SanOpts = &SO;
  633. }
  634. ~CopyingValueRepresentation() {
  635. CGF.SanOpts = OldSanOpts;
  636. }
  637. private:
  638. CodeGenFunction &CGF;
  639. SanitizerOptions SO;
  640. const SanitizerOptions *OldSanOpts;
  641. };
  642. }
  643. namespace {
  644. class FieldMemcpyizer {
  645. public:
  646. FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
  647. const VarDecl *SrcRec)
  648. : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
  649. RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
  650. FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
  651. LastAddedFieldIndex(0) { }
  652. static bool isMemcpyableField(FieldDecl *F) {
  653. Qualifiers Qual = F->getType().getQualifiers();
  654. if (Qual.hasVolatile() || Qual.hasObjCLifetime())
  655. return false;
  656. return true;
  657. }
  658. void addMemcpyableField(FieldDecl *F) {
  659. if (FirstField == 0)
  660. addInitialField(F);
  661. else
  662. addNextField(F);
  663. }
  664. CharUnits getMemcpySize() const {
  665. unsigned LastFieldSize =
  666. LastField->isBitField() ?
  667. LastField->getBitWidthValue(CGF.getContext()) :
  668. CGF.getContext().getTypeSize(LastField->getType());
  669. uint64_t MemcpySizeBits =
  670. LastFieldOffset + LastFieldSize - FirstFieldOffset +
  671. CGF.getContext().getCharWidth() - 1;
  672. CharUnits MemcpySize =
  673. CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
  674. return MemcpySize;
  675. }
  676. void emitMemcpy() {
  677. // Give the subclass a chance to bail out if it feels the memcpy isn't
  678. // worth it (e.g. Hasn't aggregated enough data).
  679. if (FirstField == 0) {
  680. return;
  681. }
  682. CharUnits Alignment;
  683. if (FirstField->isBitField()) {
  684. const CGRecordLayout &RL =
  685. CGF.getTypes().getCGRecordLayout(FirstField->getParent());
  686. const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
  687. Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
  688. } else {
  689. Alignment = CGF.getContext().getDeclAlign(FirstField);
  690. }
  691. assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
  692. Alignment) == 0 && "Bad field alignment.");
  693. CharUnits MemcpySize = getMemcpySize();
  694. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  695. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  696. LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  697. LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
  698. llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
  699. LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  700. LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
  701. emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
  702. Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
  703. MemcpySize, Alignment);
  704. reset();
  705. }
  706. void reset() {
  707. FirstField = 0;
  708. }
  709. protected:
  710. CodeGenFunction &CGF;
  711. const CXXRecordDecl *ClassDecl;
  712. private:
  713. void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  714. CharUnits Size, CharUnits Alignment) {
  715. llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
  716. llvm::Type *DBP =
  717. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
  718. DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
  719. llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
  720. llvm::Type *SBP =
  721. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
  722. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
  723. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
  724. Alignment.getQuantity());
  725. }
  726. void addInitialField(FieldDecl *F) {
  727. FirstField = F;
  728. LastField = F;
  729. FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  730. LastFieldOffset = FirstFieldOffset;
  731. LastAddedFieldIndex = F->getFieldIndex();
  732. return;
  733. }
  734. void addNextField(FieldDecl *F) {
  735. // For the most part, the following invariant will hold:
  736. // F->getFieldIndex() == LastAddedFieldIndex + 1
  737. // The one exception is that Sema won't add a copy-initializer for an
  738. // unnamed bitfield, which will show up here as a gap in the sequence.
  739. assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
  740. "Cannot aggregate fields out of order.");
  741. LastAddedFieldIndex = F->getFieldIndex();
  742. // The 'first' and 'last' fields are chosen by offset, rather than field
  743. // index. This allows the code to support bitfields, as well as regular
  744. // fields.
  745. uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  746. if (FOffset < FirstFieldOffset) {
  747. FirstField = F;
  748. FirstFieldOffset = FOffset;
  749. } else if (FOffset > LastFieldOffset) {
  750. LastField = F;
  751. LastFieldOffset = FOffset;
  752. }
  753. }
  754. const VarDecl *SrcRec;
  755. const ASTRecordLayout &RecLayout;
  756. FieldDecl *FirstField;
  757. FieldDecl *LastField;
  758. uint64_t FirstFieldOffset, LastFieldOffset;
  759. unsigned LastAddedFieldIndex;
  760. };
  761. class ConstructorMemcpyizer : public FieldMemcpyizer {
  762. private:
  763. /// Get source argument for copy constructor. Returns null if not a copy
  764. /// constructor.
  765. static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
  766. FunctionArgList &Args) {
  767. if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
  768. return Args[Args.size() - 1];
  769. return 0;
  770. }
  771. // Returns true if a CXXCtorInitializer represents a member initialization
  772. // that can be rolled into a memcpy.
  773. bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
  774. if (!MemcpyableCtor)
  775. return false;
  776. FieldDecl *Field = MemberInit->getMember();
  777. assert(Field != 0 && "No field for member init.");
  778. QualType FieldType = Field->getType();
  779. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  780. // Bail out on non-POD, not-trivially-constructable members.
  781. if (!(CE && CE->getConstructor()->isTrivial()) &&
  782. !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
  783. FieldType->isReferenceType()))
  784. return false;
  785. // Bail out on volatile fields.
  786. if (!isMemcpyableField(Field))
  787. return false;
  788. // Otherwise we're good.
  789. return true;
  790. }
  791. public:
  792. ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
  793. FunctionArgList &Args)
  794. : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
  795. ConstructorDecl(CD),
  796. MemcpyableCtor(CD->isDefaulted() &&
  797. CD->isCopyOrMoveConstructor() &&
  798. CGF.getLangOpts().getGC() == LangOptions::NonGC),
  799. Args(Args) { }
  800. void addMemberInitializer(CXXCtorInitializer *MemberInit) {
  801. if (isMemberInitMemcpyable(MemberInit)) {
  802. AggregatedInits.push_back(MemberInit);
  803. addMemcpyableField(MemberInit->getMember());
  804. } else {
  805. emitAggregatedInits();
  806. EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
  807. ConstructorDecl, Args);
  808. }
  809. }
  810. void emitAggregatedInits() {
  811. if (AggregatedInits.size() <= 1) {
  812. // This memcpy is too small to be worthwhile. Fall back on default
  813. // codegen.
  814. if (!AggregatedInits.empty()) {
  815. CopyingValueRepresentation CVR(CGF);
  816. EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
  817. AggregatedInits[0], ConstructorDecl, Args);
  818. }
  819. reset();
  820. return;
  821. }
  822. pushEHDestructors();
  823. emitMemcpy();
  824. AggregatedInits.clear();
  825. }
  826. void pushEHDestructors() {
  827. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  828. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  829. LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  830. for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
  831. QualType FieldType = AggregatedInits[i]->getMember()->getType();
  832. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  833. if (CGF.needsEHCleanup(dtorKind))
  834. CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
  835. }
  836. }
  837. void finish() {
  838. emitAggregatedInits();
  839. }
  840. private:
  841. const CXXConstructorDecl *ConstructorDecl;
  842. bool MemcpyableCtor;
  843. FunctionArgList &Args;
  844. SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
  845. };
  846. class AssignmentMemcpyizer : public FieldMemcpyizer {
  847. private:
  848. // Returns the memcpyable field copied by the given statement, if one
  849. // exists. Otherwise returns null.
  850. FieldDecl *getMemcpyableField(Stmt *S) {
  851. if (!AssignmentsMemcpyable)
  852. return 0;
  853. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
  854. // Recognise trivial assignments.
  855. if (BO->getOpcode() != BO_Assign)
  856. return 0;
  857. MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
  858. if (!ME)
  859. return 0;
  860. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  861. if (!Field || !isMemcpyableField(Field))
  862. return 0;
  863. Stmt *RHS = BO->getRHS();
  864. if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
  865. RHS = EC->getSubExpr();
  866. if (!RHS)
  867. return 0;
  868. MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
  869. if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
  870. return 0;
  871. return Field;
  872. } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
  873. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
  874. if (!(MD && (MD->isCopyAssignmentOperator() ||
  875. MD->isMoveAssignmentOperator()) &&
  876. MD->isTrivial()))
  877. return 0;
  878. MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
  879. if (!IOA)
  880. return 0;
  881. FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
  882. if (!Field || !isMemcpyableField(Field))
  883. return 0;
  884. MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
  885. if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
  886. return 0;
  887. return Field;
  888. } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  889. FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  890. if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
  891. return 0;
  892. Expr *DstPtr = CE->getArg(0);
  893. if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
  894. DstPtr = DC->getSubExpr();
  895. UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
  896. if (!DUO || DUO->getOpcode() != UO_AddrOf)
  897. return 0;
  898. MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
  899. if (!ME)
  900. return 0;
  901. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  902. if (!Field || !isMemcpyableField(Field))
  903. return 0;
  904. Expr *SrcPtr = CE->getArg(1);
  905. if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
  906. SrcPtr = SC->getSubExpr();
  907. UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
  908. if (!SUO || SUO->getOpcode() != UO_AddrOf)
  909. return 0;
  910. MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
  911. if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
  912. return 0;
  913. return Field;
  914. }
  915. return 0;
  916. }
  917. bool AssignmentsMemcpyable;
  918. SmallVector<Stmt*, 16> AggregatedStmts;
  919. public:
  920. AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
  921. FunctionArgList &Args)
  922. : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
  923. AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
  924. assert(Args.size() == 2);
  925. }
  926. void emitAssignment(Stmt *S) {
  927. FieldDecl *F = getMemcpyableField(S);
  928. if (F) {
  929. addMemcpyableField(F);
  930. AggregatedStmts.push_back(S);
  931. } else {
  932. emitAggregatedStmts();
  933. CGF.EmitStmt(S);
  934. }
  935. }
  936. void emitAggregatedStmts() {
  937. if (AggregatedStmts.size() <= 1) {
  938. if (!AggregatedStmts.empty()) {
  939. CopyingValueRepresentation CVR(CGF);
  940. CGF.EmitStmt(AggregatedStmts[0]);
  941. }
  942. reset();
  943. }
  944. emitMemcpy();
  945. AggregatedStmts.clear();
  946. }
  947. void finish() {
  948. emitAggregatedStmts();
  949. }
  950. };
  951. }
  952. /// EmitCtorPrologue - This routine generates necessary code to initialize
  953. /// base classes and non-static data members belonging to this constructor.
  954. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  955. CXXCtorType CtorType,
  956. FunctionArgList &Args) {
  957. if (CD->isDelegatingConstructor())
  958. return EmitDelegatingCXXConstructorCall(CD, Args);
  959. const CXXRecordDecl *ClassDecl = CD->getParent();
  960. CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  961. E = CD->init_end();
  962. llvm::BasicBlock *BaseCtorContinueBB = 0;
  963. if (ClassDecl->getNumVBases() &&
  964. !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  965. // The ABIs that don't have constructor variants need to put a branch
  966. // before the virtual base initialization code.
  967. BaseCtorContinueBB =
  968. CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
  969. assert(BaseCtorContinueBB);
  970. }
  971. // Virtual base initializers first.
  972. for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
  973. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  974. }
  975. if (BaseCtorContinueBB) {
  976. // Complete object handler should continue to the remaining initializers.
  977. Builder.CreateBr(BaseCtorContinueBB);
  978. EmitBlock(BaseCtorContinueBB);
  979. }
  980. // Then, non-virtual base initializers.
  981. for (; B != E && (*B)->isBaseInitializer(); B++) {
  982. assert(!(*B)->isBaseVirtual());
  983. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  984. }
  985. InitializeVTablePointers(ClassDecl);
  986. // And finally, initialize class members.
  987. FieldConstructionScope FCS(*this, CXXThisValue);
  988. ConstructorMemcpyizer CM(*this, CD, Args);
  989. for (; B != E; B++) {
  990. CXXCtorInitializer *Member = (*B);
  991. assert(!Member->isBaseInitializer());
  992. assert(Member->isAnyMemberInitializer() &&
  993. "Delegating initializer on non-delegating constructor");
  994. CM.addMemberInitializer(Member);
  995. }
  996. CM.finish();
  997. }
  998. static bool
  999. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  1000. static bool
  1001. HasTrivialDestructorBody(ASTContext &Context,
  1002. const CXXRecordDecl *BaseClassDecl,
  1003. const CXXRecordDecl *MostDerivedClassDecl)
  1004. {
  1005. // If the destructor is trivial we don't have to check anything else.
  1006. if (BaseClassDecl->hasTrivialDestructor())
  1007. return true;
  1008. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  1009. return false;
  1010. // Check fields.
  1011. for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
  1012. E = BaseClassDecl->field_end(); I != E; ++I) {
  1013. const FieldDecl *Field = *I;
  1014. if (!FieldHasTrivialDestructorBody(Context, Field))
  1015. return false;
  1016. }
  1017. // Check non-virtual bases.
  1018. for (CXXRecordDecl::base_class_const_iterator I =
  1019. BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
  1020. I != E; ++I) {
  1021. if (I->isVirtual())
  1022. continue;
  1023. const CXXRecordDecl *NonVirtualBase =
  1024. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  1025. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  1026. MostDerivedClassDecl))
  1027. return false;
  1028. }
  1029. if (BaseClassDecl == MostDerivedClassDecl) {
  1030. // Check virtual bases.
  1031. for (CXXRecordDecl::base_class_const_iterator I =
  1032. BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
  1033. I != E; ++I) {
  1034. const CXXRecordDecl *VirtualBase =
  1035. cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
  1036. if (!HasTrivialDestructorBody(Context, VirtualBase,
  1037. MostDerivedClassDecl))
  1038. return false;
  1039. }
  1040. }
  1041. return true;
  1042. }
  1043. static bool
  1044. FieldHasTrivialDestructorBody(ASTContext &Context,
  1045. const FieldDecl *Field)
  1046. {
  1047. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  1048. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  1049. if (!RT)
  1050. return true;
  1051. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  1052. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  1053. }
  1054. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  1055. /// any vtable pointers before calling this destructor.
  1056. static bool CanSkipVTablePointerInitialization(ASTContext &Context,
  1057. const CXXDestructorDecl *Dtor) {
  1058. if (!Dtor->hasTrivialBody())
  1059. return false;
  1060. // Check the fields.
  1061. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1062. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  1063. E = ClassDecl->field_end(); I != E; ++I) {
  1064. const FieldDecl *Field = *I;
  1065. if (!FieldHasTrivialDestructorBody(Context, Field))
  1066. return false;
  1067. }
  1068. return true;
  1069. }
  1070. /// EmitDestructorBody - Emits the body of the current destructor.
  1071. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  1072. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  1073. CXXDtorType DtorType = CurGD.getDtorType();
  1074. // The call to operator delete in a deleting destructor happens
  1075. // outside of the function-try-block, which means it's always
  1076. // possible to delegate the destructor body to the complete
  1077. // destructor. Do so.
  1078. if (DtorType == Dtor_Deleting) {
  1079. EnterDtorCleanups(Dtor, Dtor_Deleting);
  1080. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  1081. /*Delegating=*/false, LoadCXXThis());
  1082. PopCleanupBlock();
  1083. return;
  1084. }
  1085. Stmt *Body = Dtor->getBody();
  1086. // If the body is a function-try-block, enter the try before
  1087. // anything else.
  1088. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  1089. if (isTryBody)
  1090. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1091. // Enter the epilogue cleanups.
  1092. RunCleanupsScope DtorEpilogue(*this);
  1093. // If this is the complete variant, just invoke the base variant;
  1094. // the epilogue will destruct the virtual bases. But we can't do
  1095. // this optimization if the body is a function-try-block, because
  1096. // we'd introduce *two* handler blocks. In the Microsoft ABI, we
  1097. // always delegate because we might not have a definition in this TU.
  1098. switch (DtorType) {
  1099. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  1100. case Dtor_Complete:
  1101. assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
  1102. "can't emit a dtor without a body for non-Microsoft ABIs");
  1103. // Enter the cleanup scopes for virtual bases.
  1104. EnterDtorCleanups(Dtor, Dtor_Complete);
  1105. if (!isTryBody) {
  1106. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1107. /*Delegating=*/false, LoadCXXThis());
  1108. break;
  1109. }
  1110. // Fallthrough: act like we're in the base variant.
  1111. case Dtor_Base:
  1112. assert(Body);
  1113. // Enter the cleanup scopes for fields and non-virtual bases.
  1114. EnterDtorCleanups(Dtor, Dtor_Base);
  1115. // Initialize the vtable pointers before entering the body.
  1116. if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
  1117. InitializeVTablePointers(Dtor->getParent());
  1118. if (isTryBody)
  1119. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  1120. else if (Body)
  1121. EmitStmt(Body);
  1122. else {
  1123. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  1124. // nothing to do besides what's in the epilogue
  1125. }
  1126. // -fapple-kext must inline any call to this dtor into
  1127. // the caller's body.
  1128. if (getLangOpts().AppleKext)
  1129. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  1130. break;
  1131. }
  1132. // Jump out through the epilogue cleanups.
  1133. DtorEpilogue.ForceCleanup();
  1134. // Exit the try if applicable.
  1135. if (isTryBody)
  1136. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1137. }
  1138. void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
  1139. const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
  1140. const Stmt *RootS = AssignOp->getBody();
  1141. assert(isa<CompoundStmt>(RootS) &&
  1142. "Body of an implicit assignment operator should be compound stmt.");
  1143. const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
  1144. LexicalScope Scope(*this, RootCS->getSourceRange());
  1145. AssignmentMemcpyizer AM(*this, AssignOp, Args);
  1146. for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
  1147. E = RootCS->body_end();
  1148. I != E; ++I) {
  1149. AM.emitAssignment(*I);
  1150. }
  1151. AM.finish();
  1152. }
  1153. namespace {
  1154. /// Call the operator delete associated with the current destructor.
  1155. struct CallDtorDelete : EHScopeStack::Cleanup {
  1156. CallDtorDelete() {}
  1157. void Emit(CodeGenFunction &CGF, Flags flags) {
  1158. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1159. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1160. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1161. CGF.getContext().getTagDeclType(ClassDecl));
  1162. }
  1163. };
  1164. struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
  1165. llvm::Value *ShouldDeleteCondition;
  1166. public:
  1167. CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
  1168. : ShouldDeleteCondition(ShouldDeleteCondition) {
  1169. assert(ShouldDeleteCondition != NULL);
  1170. }
  1171. void Emit(CodeGenFunction &CGF, Flags flags) {
  1172. llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
  1173. llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
  1174. llvm::Value *ShouldCallDelete
  1175. = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
  1176. CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
  1177. CGF.EmitBlock(callDeleteBB);
  1178. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1179. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1180. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1181. CGF.getContext().getTagDeclType(ClassDecl));
  1182. CGF.Builder.CreateBr(continueBB);
  1183. CGF.EmitBlock(continueBB);
  1184. }
  1185. };
  1186. class DestroyField : public EHScopeStack::Cleanup {
  1187. const FieldDecl *field;
  1188. CodeGenFunction::Destroyer *destroyer;
  1189. bool useEHCleanupForArray;
  1190. public:
  1191. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  1192. bool useEHCleanupForArray)
  1193. : field(field), destroyer(destroyer),
  1194. useEHCleanupForArray(useEHCleanupForArray) {}
  1195. void Emit(CodeGenFunction &CGF, Flags flags) {
  1196. // Find the address of the field.
  1197. llvm::Value *thisValue = CGF.LoadCXXThis();
  1198. QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
  1199. LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
  1200. LValue LV = CGF.EmitLValueForField(ThisLV, field);
  1201. assert(LV.isSimple());
  1202. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  1203. flags.isForNormalCleanup() && useEHCleanupForArray);
  1204. }
  1205. };
  1206. }
  1207. /// EmitDtorEpilogue - Emit all code that comes at the end of class's
  1208. /// destructor. This is to call destructors on members and base classes
  1209. /// in reverse order of their construction.
  1210. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  1211. CXXDtorType DtorType) {
  1212. assert(!DD->isTrivial() &&
  1213. "Should not emit dtor epilogue for trivial dtor!");
  1214. // The deleting-destructor phase just needs to call the appropriate
  1215. // operator delete that Sema picked up.
  1216. if (DtorType == Dtor_Deleting) {
  1217. assert(DD->getOperatorDelete() &&
  1218. "operator delete missing - EmitDtorEpilogue");
  1219. if (CXXStructorImplicitParamValue) {
  1220. // If there is an implicit param to the deleting dtor, it's a boolean
  1221. // telling whether we should call delete at the end of the dtor.
  1222. EHStack.pushCleanup<CallDtorDeleteConditional>(
  1223. NormalAndEHCleanup, CXXStructorImplicitParamValue);
  1224. } else {
  1225. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  1226. }
  1227. return;
  1228. }
  1229. const CXXRecordDecl *ClassDecl = DD->getParent();
  1230. // Unions have no bases and do not call field destructors.
  1231. if (ClassDecl->isUnion())
  1232. return;
  1233. // The complete-destructor phase just destructs all the virtual bases.
  1234. if (DtorType == Dtor_Complete) {
  1235. // We push them in the forward order so that they'll be popped in
  1236. // the reverse order.
  1237. for (CXXRecordDecl::base_class_const_iterator I =
  1238. ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
  1239. I != E; ++I) {
  1240. const CXXBaseSpecifier &Base = *I;
  1241. CXXRecordDecl *BaseClassDecl
  1242. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  1243. // Ignore trivial destructors.
  1244. if (BaseClassDecl->hasTrivialDestructor())
  1245. continue;
  1246. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1247. BaseClassDecl,
  1248. /*BaseIsVirtual*/ true);
  1249. }
  1250. return;
  1251. }
  1252. assert(DtorType == Dtor_Base);
  1253. // Destroy non-virtual bases.
  1254. for (CXXRecordDecl::base_class_const_iterator I =
  1255. ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
  1256. const CXXBaseSpecifier &Base = *I;
  1257. // Ignore virtual bases.
  1258. if (Base.isVirtual())
  1259. continue;
  1260. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  1261. // Ignore trivial destructors.
  1262. if (BaseClassDecl->hasTrivialDestructor())
  1263. continue;
  1264. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1265. BaseClassDecl,
  1266. /*BaseIsVirtual*/ false);
  1267. }
  1268. // Destroy direct fields.
  1269. SmallVector<const FieldDecl *, 16> FieldDecls;
  1270. for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
  1271. E = ClassDecl->field_end(); I != E; ++I) {
  1272. const FieldDecl *field = *I;
  1273. QualType type = field->getType();
  1274. QualType::DestructionKind dtorKind = type.isDestructedType();
  1275. if (!dtorKind) continue;
  1276. // Anonymous union members do not have their destructors called.
  1277. const RecordType *RT = type->getAsUnionType();
  1278. if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
  1279. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1280. EHStack.pushCleanup<DestroyField>(cleanupKind, field,
  1281. getDestroyer(dtorKind),
  1282. cleanupKind & EHCleanup);
  1283. }
  1284. }
  1285. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1286. /// constructor for each of several members of an array.
  1287. ///
  1288. /// \param ctor the constructor to call for each element
  1289. /// \param arrayType the type of the array to initialize
  1290. /// \param arrayBegin an arrayType*
  1291. /// \param zeroInitialize true if each element should be
  1292. /// zero-initialized before it is constructed
  1293. void
  1294. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1295. const ConstantArrayType *arrayType,
  1296. llvm::Value *arrayBegin,
  1297. CallExpr::const_arg_iterator argBegin,
  1298. CallExpr::const_arg_iterator argEnd,
  1299. bool zeroInitialize) {
  1300. QualType elementType;
  1301. llvm::Value *numElements =
  1302. emitArrayLength(arrayType, elementType, arrayBegin);
  1303. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
  1304. argBegin, argEnd, zeroInitialize);
  1305. }
  1306. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1307. /// constructor for each of several members of an array.
  1308. ///
  1309. /// \param ctor the constructor to call for each element
  1310. /// \param numElements the number of elements in the array;
  1311. /// may be zero
  1312. /// \param arrayBegin a T*, where T is the type constructed by ctor
  1313. /// \param zeroInitialize true if each element should be
  1314. /// zero-initialized before it is constructed
  1315. void
  1316. CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1317. llvm::Value *numElements,
  1318. llvm::Value *arrayBegin,
  1319. CallExpr::const_arg_iterator argBegin,
  1320. CallExpr::const_arg_iterator argEnd,
  1321. bool zeroInitialize) {
  1322. // It's legal for numElements to be zero. This can happen both
  1323. // dynamically, because x can be zero in 'new A[x]', and statically,
  1324. // because of GCC extensions that permit zero-length arrays. There
  1325. // are probably legitimate places where we could assume that this
  1326. // doesn't happen, but it's not clear that it's worth it.
  1327. llvm::BranchInst *zeroCheckBranch = 0;
  1328. // Optimize for a constant count.
  1329. llvm::ConstantInt *constantCount
  1330. = dyn_cast<llvm::ConstantInt>(numElements);
  1331. if (constantCount) {
  1332. // Just skip out if the constant count is zero.
  1333. if (constantCount->isZero()) return;
  1334. // Otherwise, emit the check.
  1335. } else {
  1336. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  1337. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  1338. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  1339. EmitBlock(loopBB);
  1340. }
  1341. // Find the end of the array.
  1342. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  1343. "arrayctor.end");
  1344. // Enter the loop, setting up a phi for the current location to initialize.
  1345. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1346. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  1347. EmitBlock(loopBB);
  1348. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  1349. "arrayctor.cur");
  1350. cur->addIncoming(arrayBegin, entryBB);
  1351. // Inside the loop body, emit the constructor call on the array element.
  1352. QualType type = getContext().getTypeDeclType(ctor->getParent());
  1353. // Zero initialize the storage, if requested.
  1354. if (zeroInitialize)
  1355. EmitNullInitialization(cur, type);
  1356. // C++ [class.temporary]p4:
  1357. // There are two contexts in which temporaries are destroyed at a different
  1358. // point than the end of the full-expression. The first context is when a
  1359. // default constructor is called to initialize an element of an array.
  1360. // If the constructor has one or more default arguments, the destruction of
  1361. // every temporary created in a default argument expression is sequenced
  1362. // before the construction of the next array element, if any.
  1363. {
  1364. RunCleanupsScope Scope(*this);
  1365. // Evaluate the constructor and its arguments in a regular
  1366. // partial-destroy cleanup.
  1367. if (getLangOpts().Exceptions &&
  1368. !ctor->getParent()->hasTrivialDestructor()) {
  1369. Destroyer *destroyer = destroyCXXObject;
  1370. pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
  1371. }
  1372. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
  1373. /*Delegating=*/false, cur, argBegin, argEnd);
  1374. }
  1375. // Go to the next element.
  1376. llvm::Value *next =
  1377. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  1378. "arrayctor.next");
  1379. cur->addIncoming(next, Builder.GetInsertBlock());
  1380. // Check whether that's the end of the loop.
  1381. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  1382. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  1383. Builder.CreateCondBr(done, contBB, loopBB);
  1384. // Patch the earlier check to skip over the loop.
  1385. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  1386. EmitBlock(contBB);
  1387. }
  1388. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  1389. llvm::Value *addr,
  1390. QualType type) {
  1391. const RecordType *rtype = type->castAs<RecordType>();
  1392. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  1393. const CXXDestructorDecl *dtor = record->getDestructor();
  1394. assert(!dtor->isTrivial());
  1395. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  1396. /*Delegating=*/false, addr);
  1397. }
  1398. void
  1399. CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1400. CXXCtorType Type, bool ForVirtualBase,
  1401. bool Delegating,
  1402. llvm::Value *This,
  1403. CallExpr::const_arg_iterator ArgBeg,
  1404. CallExpr::const_arg_iterator ArgEnd) {
  1405. // If this is a trivial constructor, just emit what's needed.
  1406. if (D->isTrivial()) {
  1407. if (ArgBeg == ArgEnd) {
  1408. // Trivial default constructor, no codegen required.
  1409. assert(D->isDefaultConstructor() &&
  1410. "trivial 0-arg ctor not a default ctor");
  1411. return;
  1412. }
  1413. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1414. assert(D->isCopyOrMoveConstructor() &&
  1415. "trivial 1-arg ctor not a copy/move ctor");
  1416. const Expr *E = (*ArgBeg);
  1417. QualType Ty = E->getType();
  1418. llvm::Value *Src = EmitLValue(E).getAddress();
  1419. EmitAggregateCopy(This, Src, Ty);
  1420. return;
  1421. }
  1422. // Non-trivial constructors are handled in an ABI-specific manner.
  1423. CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
  1424. Delegating, This, ArgBeg, ArgEnd);
  1425. }
  1426. void
  1427. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1428. llvm::Value *This, llvm::Value *Src,
  1429. CallExpr::const_arg_iterator ArgBeg,
  1430. CallExpr::const_arg_iterator ArgEnd) {
  1431. if (D->isTrivial()) {
  1432. assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
  1433. assert(D->isCopyOrMoveConstructor() &&
  1434. "trivial 1-arg ctor not a copy/move ctor");
  1435. EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
  1436. return;
  1437. }
  1438. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, clang::Ctor_Complete);
  1439. assert(D->isInstance() &&
  1440. "Trying to emit a member call expr on a static method!");
  1441. const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
  1442. CallArgList Args;
  1443. // Push the this ptr.
  1444. Args.add(RValue::get(This), D->getThisType(getContext()));
  1445. // Push the src ptr.
  1446. QualType QT = *(FPT->arg_type_begin());
  1447. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1448. Src = Builder.CreateBitCast(Src, t);
  1449. Args.add(RValue::get(Src), QT);
  1450. // Skip over first argument (Src).
  1451. ++ArgBeg;
  1452. CallExpr::const_arg_iterator Arg = ArgBeg;
  1453. for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
  1454. E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
  1455. assert(Arg != ArgEnd && "Running over edge of argument list!");
  1456. EmitCallArg(Args, *Arg, *I);
  1457. }
  1458. // Either we've emitted all the call args, or we have a call to a
  1459. // variadic function.
  1460. assert((Arg == ArgEnd || FPT->isVariadic()) &&
  1461. "Extra arguments in non-variadic function!");
  1462. // If we still have any arguments, emit them using the type of the argument.
  1463. for (; Arg != ArgEnd; ++Arg) {
  1464. QualType ArgType = Arg->getType();
  1465. EmitCallArg(Args, *Arg, ArgType);
  1466. }
  1467. EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
  1468. Callee, ReturnValueSlot(), Args, D);
  1469. }
  1470. void
  1471. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1472. CXXCtorType CtorType,
  1473. const FunctionArgList &Args,
  1474. SourceLocation Loc) {
  1475. CallArgList DelegateArgs;
  1476. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1477. assert(I != E && "no parameters to constructor");
  1478. // this
  1479. DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
  1480. ++I;
  1481. // vtt
  1482. if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
  1483. /*ForVirtualBase=*/false,
  1484. /*Delegating=*/true)) {
  1485. QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
  1486. DelegateArgs.add(RValue::get(VTT), VoidPP);
  1487. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  1488. assert(I != E && "cannot skip vtt parameter, already done with args");
  1489. assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
  1490. ++I;
  1491. }
  1492. }
  1493. // Explicit arguments.
  1494. for (; I != E; ++I) {
  1495. const VarDecl *param = *I;
  1496. // FIXME: per-argument source location
  1497. EmitDelegateCallArg(DelegateArgs, param, Loc);
  1498. }
  1499. llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
  1500. EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
  1501. Callee, ReturnValueSlot(), DelegateArgs, Ctor);
  1502. }
  1503. namespace {
  1504. struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
  1505. const CXXDestructorDecl *Dtor;
  1506. llvm::Value *Addr;
  1507. CXXDtorType Type;
  1508. CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
  1509. CXXDtorType Type)
  1510. : Dtor(D), Addr(Addr), Type(Type) {}
  1511. void Emit(CodeGenFunction &CGF, Flags flags) {
  1512. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1513. /*Delegating=*/true, Addr);
  1514. }
  1515. };
  1516. }
  1517. void
  1518. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1519. const FunctionArgList &Args) {
  1520. assert(Ctor->isDelegatingConstructor());
  1521. llvm::Value *ThisPtr = LoadCXXThis();
  1522. QualType Ty = getContext().getTagDeclType(Ctor->getParent());
  1523. CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
  1524. AggValueSlot AggSlot =
  1525. AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
  1526. AggValueSlot::IsDestructed,
  1527. AggValueSlot::DoesNotNeedGCBarriers,
  1528. AggValueSlot::IsNotAliased);
  1529. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1530. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1531. if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1532. CXXDtorType Type =
  1533. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1534. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1535. ClassDecl->getDestructor(),
  1536. ThisPtr, Type);
  1537. }
  1538. }
  1539. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1540. CXXDtorType Type,
  1541. bool ForVirtualBase,
  1542. bool Delegating,
  1543. llvm::Value *This) {
  1544. GlobalDecl GD(DD, Type);
  1545. llvm::Value *VTT = GetVTTParameter(GD, ForVirtualBase, Delegating);
  1546. llvm::Value *Callee = 0;
  1547. if (getLangOpts().AppleKext)
  1548. Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
  1549. DD->getParent());
  1550. if (!Callee)
  1551. Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
  1552. if (DD->isVirtual())
  1553. This = CGM.getCXXABI().adjustThisArgumentForVirtualCall(*this, GD, This);
  1554. // FIXME: Provide a source location here.
  1555. EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
  1556. VTT, getContext().getPointerType(getContext().VoidPtrTy),
  1557. 0, 0);
  1558. }
  1559. namespace {
  1560. struct CallLocalDtor : EHScopeStack::Cleanup {
  1561. const CXXDestructorDecl *Dtor;
  1562. llvm::Value *Addr;
  1563. CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
  1564. : Dtor(D), Addr(Addr) {}
  1565. void Emit(CodeGenFunction &CGF, Flags flags) {
  1566. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1567. /*ForVirtualBase=*/false,
  1568. /*Delegating=*/false, Addr);
  1569. }
  1570. };
  1571. }
  1572. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1573. llvm::Value *Addr) {
  1574. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1575. }
  1576. void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
  1577. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1578. if (!ClassDecl) return;
  1579. if (ClassDecl->hasTrivialDestructor()) return;
  1580. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1581. assert(D && D->isUsed() && "destructor not marked as used!");
  1582. PushDestructorCleanup(D, Addr);
  1583. }
  1584. void
  1585. CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
  1586. const CXXRecordDecl *NearestVBase,
  1587. CharUnits OffsetFromNearestVBase,
  1588. const CXXRecordDecl *VTableClass) {
  1589. // Compute the address point.
  1590. bool NeedsVirtualOffset;
  1591. llvm::Value *VTableAddressPoint =
  1592. CGM.getCXXABI().getVTableAddressPointInStructor(
  1593. *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
  1594. if (!VTableAddressPoint)
  1595. return;
  1596. // Compute where to store the address point.
  1597. llvm::Value *VirtualOffset = 0;
  1598. CharUnits NonVirtualOffset = CharUnits::Zero();
  1599. if (NeedsVirtualOffset) {
  1600. // We need to use the virtual base offset offset because the virtual base
  1601. // might have a different offset in the most derived class.
  1602. VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
  1603. LoadCXXThis(),
  1604. VTableClass,
  1605. NearestVBase);
  1606. NonVirtualOffset = OffsetFromNearestVBase;
  1607. } else {
  1608. // We can just use the base offset in the complete class.
  1609. NonVirtualOffset = Base.getBaseOffset();
  1610. }
  1611. // Apply the offsets.
  1612. llvm::Value *VTableField = LoadCXXThis();
  1613. if (!NonVirtualOffset.isZero() || VirtualOffset)
  1614. VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
  1615. NonVirtualOffset,
  1616. VirtualOffset);
  1617. // Finally, store the address point.
  1618. llvm::Type *AddressPointPtrTy =
  1619. VTableAddressPoint->getType()->getPointerTo();
  1620. VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
  1621. llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
  1622. CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
  1623. }
  1624. void
  1625. CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
  1626. const CXXRecordDecl *NearestVBase,
  1627. CharUnits OffsetFromNearestVBase,
  1628. bool BaseIsNonVirtualPrimaryBase,
  1629. const CXXRecordDecl *VTableClass,
  1630. VisitedVirtualBasesSetTy& VBases) {
  1631. // If this base is a non-virtual primary base the address point has already
  1632. // been set.
  1633. if (!BaseIsNonVirtualPrimaryBase) {
  1634. // Initialize the vtable pointer for this base.
  1635. InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
  1636. VTableClass);
  1637. }
  1638. const CXXRecordDecl *RD = Base.getBase();
  1639. // Traverse bases.
  1640. for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
  1641. E = RD->bases_end(); I != E; ++I) {
  1642. CXXRecordDecl *BaseDecl
  1643. = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
  1644. // Ignore classes without a vtable.
  1645. if (!BaseDecl->isDynamicClass())
  1646. continue;
  1647. CharUnits BaseOffset;
  1648. CharUnits BaseOffsetFromNearestVBase;
  1649. bool BaseDeclIsNonVirtualPrimaryBase;
  1650. if (I->isVirtual()) {
  1651. // Check if we've visited this virtual base before.
  1652. if (!VBases.insert(BaseDecl))
  1653. continue;
  1654. const ASTRecordLayout &Layout =
  1655. getContext().getASTRecordLayout(VTableClass);
  1656. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  1657. BaseOffsetFromNearestVBase = CharUnits::Zero();
  1658. BaseDeclIsNonVirtualPrimaryBase = false;
  1659. } else {
  1660. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1661. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  1662. BaseOffsetFromNearestVBase =
  1663. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  1664. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  1665. }
  1666. InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
  1667. I->isVirtual() ? BaseDecl : NearestVBase,
  1668. BaseOffsetFromNearestVBase,
  1669. BaseDeclIsNonVirtualPrimaryBase,
  1670. VTableClass, VBases);
  1671. }
  1672. }
  1673. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  1674. // Ignore classes without a vtable.
  1675. if (!RD->isDynamicClass())
  1676. return;
  1677. // Initialize the vtable pointers for this class and all of its bases.
  1678. VisitedVirtualBasesSetTy VBases;
  1679. InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
  1680. /*NearestVBase=*/0,
  1681. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  1682. /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
  1683. if (RD->getNumVBases())
  1684. CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
  1685. }
  1686. llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
  1687. llvm::Type *Ty) {
  1688. llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
  1689. llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
  1690. CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
  1691. return VTable;
  1692. }
  1693. // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
  1694. // quite what we want.
  1695. static const Expr *skipNoOpCastsAndParens(const Expr *E) {
  1696. while (true) {
  1697. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
  1698. E = PE->getSubExpr();
  1699. continue;
  1700. }
  1701. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  1702. if (CE->getCastKind() == CK_NoOp) {
  1703. E = CE->getSubExpr();
  1704. continue;
  1705. }
  1706. }
  1707. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  1708. if (UO->getOpcode() == UO_Extension) {
  1709. E = UO->getSubExpr();
  1710. continue;
  1711. }
  1712. }
  1713. return E;
  1714. }
  1715. }
  1716. bool
  1717. CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
  1718. const CXXMethodDecl *MD) {
  1719. // When building with -fapple-kext, all calls must go through the vtable since
  1720. // the kernel linker can do runtime patching of vtables.
  1721. if (getLangOpts().AppleKext)
  1722. return false;
  1723. // If the most derived class is marked final, we know that no subclass can
  1724. // override this member function and so we can devirtualize it. For example:
  1725. //
  1726. // struct A { virtual void f(); }
  1727. // struct B final : A { };
  1728. //
  1729. // void f(B *b) {
  1730. // b->f();
  1731. // }
  1732. //
  1733. const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
  1734. if (MostDerivedClassDecl->hasAttr<FinalAttr>())
  1735. return true;
  1736. // If the member function is marked 'final', we know that it can't be
  1737. // overridden and can therefore devirtualize it.
  1738. if (MD->hasAttr<FinalAttr>())
  1739. return true;
  1740. // Similarly, if the class itself is marked 'final' it can't be overridden
  1741. // and we can therefore devirtualize the member function call.
  1742. if (MD->getParent()->hasAttr<FinalAttr>())
  1743. return true;
  1744. Base = skipNoOpCastsAndParens(Base);
  1745. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  1746. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1747. // This is a record decl. We know the type and can devirtualize it.
  1748. return VD->getType()->isRecordType();
  1749. }
  1750. return false;
  1751. }
  1752. // We can devirtualize calls on an object accessed by a class member access
  1753. // expression, since by C++11 [basic.life]p6 we know that it can't refer to
  1754. // a derived class object constructed in the same location.
  1755. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
  1756. if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
  1757. return VD->getType()->isRecordType();
  1758. // We can always devirtualize calls on temporary object expressions.
  1759. if (isa<CXXConstructExpr>(Base))
  1760. return true;
  1761. // And calls on bound temporaries.
  1762. if (isa<CXXBindTemporaryExpr>(Base))
  1763. return true;
  1764. // Check if this is a call expr that returns a record type.
  1765. if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
  1766. return CE->getCallReturnType()->isRecordType();
  1767. // We can't devirtualize the call.
  1768. return false;
  1769. }
  1770. llvm::Value *
  1771. CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1772. const CXXMethodDecl *MD,
  1773. llvm::Value *This) {
  1774. llvm::FunctionType *fnType =
  1775. CGM.getTypes().GetFunctionType(
  1776. CGM.getTypes().arrangeCXXMethodDeclaration(MD));
  1777. if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
  1778. return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
  1779. return CGM.GetAddrOfFunction(MD, fnType);
  1780. }
  1781. void CodeGenFunction::EmitForwardingCallToLambda(
  1782. const CXXMethodDecl *callOperator,
  1783. CallArgList &callArgs) {
  1784. // Get the address of the call operator.
  1785. const CGFunctionInfo &calleeFnInfo =
  1786. CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
  1787. llvm::Value *callee =
  1788. CGM.GetAddrOfFunction(GlobalDecl(callOperator),
  1789. CGM.getTypes().GetFunctionType(calleeFnInfo));
  1790. // Prepare the return slot.
  1791. const FunctionProtoType *FPT =
  1792. callOperator->getType()->castAs<FunctionProtoType>();
  1793. QualType resultType = FPT->getResultType();
  1794. ReturnValueSlot returnSlot;
  1795. if (!resultType->isVoidType() &&
  1796. calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  1797. !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
  1798. returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
  1799. // We don't need to separately arrange the call arguments because
  1800. // the call can't be variadic anyway --- it's impossible to forward
  1801. // variadic arguments.
  1802. // Now emit our call.
  1803. RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
  1804. callArgs, callOperator);
  1805. // If necessary, copy the returned value into the slot.
  1806. if (!resultType->isVoidType() && returnSlot.isNull())
  1807. EmitReturnOfRValue(RV, resultType);
  1808. else
  1809. EmitBranchThroughCleanup(ReturnBlock);
  1810. }
  1811. void CodeGenFunction::EmitLambdaBlockInvokeBody() {
  1812. const BlockDecl *BD = BlockInfo->getBlockDecl();
  1813. const VarDecl *variable = BD->capture_begin()->getVariable();
  1814. const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
  1815. // Start building arguments for forwarding call
  1816. CallArgList CallArgs;
  1817. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  1818. llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
  1819. CallArgs.add(RValue::get(ThisPtr), ThisType);
  1820. // Add the rest of the parameters.
  1821. for (BlockDecl::param_const_iterator I = BD->param_begin(),
  1822. E = BD->param_end(); I != E; ++I) {
  1823. ParmVarDecl *param = *I;
  1824. EmitDelegateCallArg(CallArgs, param, param->getLocStart());
  1825. }
  1826. assert(!Lambda->isGenericLambda() &&
  1827. "generic lambda interconversion to block not implemented");
  1828. EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
  1829. }
  1830. void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
  1831. if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
  1832. // FIXME: Making this work correctly is nasty because it requires either
  1833. // cloning the body of the call operator or making the call operator forward.
  1834. CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
  1835. return;
  1836. }
  1837. EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
  1838. }
  1839. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  1840. const CXXRecordDecl *Lambda = MD->getParent();
  1841. // Start building arguments for forwarding call
  1842. CallArgList CallArgs;
  1843. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  1844. llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
  1845. CallArgs.add(RValue::get(ThisPtr), ThisType);
  1846. // Add the rest of the parameters.
  1847. for (FunctionDecl::param_const_iterator I = MD->param_begin(),
  1848. E = MD->param_end(); I != E; ++I) {
  1849. ParmVarDecl *param = *I;
  1850. EmitDelegateCallArg(CallArgs, param, param->getLocStart());
  1851. }
  1852. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  1853. // For a generic lambda, find the corresponding call operator specialization
  1854. // to which the call to the static-invoker shall be forwarded.
  1855. if (Lambda->isGenericLambda()) {
  1856. assert(MD->isFunctionTemplateSpecialization());
  1857. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  1858. FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
  1859. void *InsertPos = 0;
  1860. FunctionDecl *CorrespondingCallOpSpecialization =
  1861. CallOpTemplate->findSpecialization(TAL->data(), TAL->size(), InsertPos);
  1862. assert(CorrespondingCallOpSpecialization);
  1863. CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  1864. }
  1865. EmitForwardingCallToLambda(CallOp, CallArgs);
  1866. }
  1867. void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
  1868. if (MD->isVariadic()) {
  1869. // FIXME: Making this work correctly is nasty because it requires either
  1870. // cloning the body of the call operator or making the call operator forward.
  1871. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  1872. return;
  1873. }
  1874. EmitLambdaDelegatingInvokeBody(MD);
  1875. }