CGClass.cpp 109 KB

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