CGClass.cpp 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812
  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. LValueBaseInfo *BaseInfo) {
  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, BaseInfo);
  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. bool CodeGenFunction::IsConstructorDelegationValid(
  584. const CXXConstructorDecl *Ctor) {
  585. // Currently we disable the optimization for classes with virtual
  586. // bases because (1) the addresses of parameter variables need to be
  587. // consistent across all initializers but (2) the delegate function
  588. // call necessarily creates a second copy of the parameter variable.
  589. //
  590. // The limiting example (purely theoretical AFAIK):
  591. // struct A { A(int &c) { c++; } };
  592. // struct B : virtual A {
  593. // B(int count) : A(count) { printf("%d\n", count); }
  594. // };
  595. // ...although even this example could in principle be emitted as a
  596. // delegation since the address of the parameter doesn't escape.
  597. if (Ctor->getParent()->getNumVBases()) {
  598. // TODO: white-list trivial vbase initializers. This case wouldn't
  599. // be subject to the restrictions below.
  600. // TODO: white-list cases where:
  601. // - there are no non-reference parameters to the constructor
  602. // - the initializers don't access any non-reference parameters
  603. // - the initializers don't take the address of non-reference
  604. // parameters
  605. // - etc.
  606. // If we ever add any of the above cases, remember that:
  607. // - function-try-blocks will always blacklist this optimization
  608. // - we need to perform the constructor prologue and cleanup in
  609. // EmitConstructorBody.
  610. return false;
  611. }
  612. // We also disable the optimization for variadic functions because
  613. // it's impossible to "re-pass" varargs.
  614. if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
  615. return false;
  616. // FIXME: Decide if we can do a delegation of a delegating constructor.
  617. if (Ctor->isDelegatingConstructor())
  618. return false;
  619. return true;
  620. }
  621. // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
  622. // to poison the extra field paddings inserted under
  623. // -fsanitize-address-field-padding=1|2.
  624. void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
  625. ASTContext &Context = getContext();
  626. const CXXRecordDecl *ClassDecl =
  627. Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
  628. : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
  629. if (!ClassDecl->mayInsertExtraPadding()) return;
  630. struct SizeAndOffset {
  631. uint64_t Size;
  632. uint64_t Offset;
  633. };
  634. unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
  635. const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
  636. // Populate sizes and offsets of fields.
  637. SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
  638. for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
  639. SSV[i].Offset =
  640. Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
  641. size_t NumFields = 0;
  642. for (const auto *Field : ClassDecl->fields()) {
  643. const FieldDecl *D = Field;
  644. std::pair<CharUnits, CharUnits> FieldInfo =
  645. Context.getTypeInfoInChars(D->getType());
  646. CharUnits FieldSize = FieldInfo.first;
  647. assert(NumFields < SSV.size());
  648. SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
  649. NumFields++;
  650. }
  651. assert(NumFields == SSV.size());
  652. if (SSV.size() <= 1) return;
  653. // We will insert calls to __asan_* run-time functions.
  654. // LLVM AddressSanitizer pass may decide to inline them later.
  655. llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
  656. llvm::FunctionType *FTy =
  657. llvm::FunctionType::get(CGM.VoidTy, Args, false);
  658. llvm::Constant *F = CGM.CreateRuntimeFunction(
  659. FTy, Prologue ? "__asan_poison_intra_object_redzone"
  660. : "__asan_unpoison_intra_object_redzone");
  661. llvm::Value *ThisPtr = LoadCXXThis();
  662. ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
  663. uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
  664. // For each field check if it has sufficient padding,
  665. // if so (un)poison it with a call.
  666. for (size_t i = 0; i < SSV.size(); i++) {
  667. uint64_t AsanAlignment = 8;
  668. uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
  669. uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
  670. uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
  671. if (PoisonSize < AsanAlignment || !SSV[i].Size ||
  672. (NextField % AsanAlignment) != 0)
  673. continue;
  674. Builder.CreateCall(
  675. F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
  676. Builder.getIntN(PtrSize, PoisonSize)});
  677. }
  678. }
  679. /// EmitConstructorBody - Emits the body of the current constructor.
  680. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  681. EmitAsanPrologueOrEpilogue(true);
  682. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  683. CXXCtorType CtorType = CurGD.getCtorType();
  684. assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
  685. CtorType == Ctor_Complete) &&
  686. "can only generate complete ctor for this ABI");
  687. // Before we go any further, try the complete->base constructor
  688. // delegation optimization.
  689. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
  690. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  691. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
  692. return;
  693. }
  694. const FunctionDecl *Definition = nullptr;
  695. Stmt *Body = Ctor->getBody(Definition);
  696. assert(Definition == Ctor && "emitting wrong constructor body");
  697. // Enter the function-try-block before the constructor prologue if
  698. // applicable.
  699. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  700. if (IsTryBody)
  701. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  702. incrementProfileCounter(Body);
  703. RunCleanupsScope RunCleanups(*this);
  704. // TODO: in restricted cases, we can emit the vbase initializers of
  705. // a complete ctor and then delegate to the base ctor.
  706. // Emit the constructor prologue, i.e. the base and member
  707. // initializers.
  708. EmitCtorPrologue(Ctor, CtorType, Args);
  709. // Emit the body of the statement.
  710. if (IsTryBody)
  711. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  712. else if (Body)
  713. EmitStmt(Body);
  714. // Emit any cleanup blocks associated with the member or base
  715. // initializers, which includes (along the exceptional path) the
  716. // destructors for those members and bases that were fully
  717. // constructed.
  718. RunCleanups.ForceCleanup();
  719. if (IsTryBody)
  720. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  721. }
  722. namespace {
  723. /// RAII object to indicate that codegen is copying the value representation
  724. /// instead of the object representation. Useful when copying a struct or
  725. /// class which has uninitialized members and we're only performing
  726. /// lvalue-to-rvalue conversion on the object but not its members.
  727. class CopyingValueRepresentation {
  728. public:
  729. explicit CopyingValueRepresentation(CodeGenFunction &CGF)
  730. : CGF(CGF), OldSanOpts(CGF.SanOpts) {
  731. CGF.SanOpts.set(SanitizerKind::Bool, false);
  732. CGF.SanOpts.set(SanitizerKind::Enum, false);
  733. }
  734. ~CopyingValueRepresentation() {
  735. CGF.SanOpts = OldSanOpts;
  736. }
  737. private:
  738. CodeGenFunction &CGF;
  739. SanitizerSet OldSanOpts;
  740. };
  741. } // end anonymous namespace
  742. namespace {
  743. class FieldMemcpyizer {
  744. public:
  745. FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
  746. const VarDecl *SrcRec)
  747. : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
  748. RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
  749. FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
  750. LastFieldOffset(0), LastAddedFieldIndex(0) {}
  751. bool isMemcpyableField(FieldDecl *F) const {
  752. // Never memcpy fields when we are adding poisoned paddings.
  753. if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
  754. return false;
  755. Qualifiers Qual = F->getType().getQualifiers();
  756. if (Qual.hasVolatile() || Qual.hasObjCLifetime())
  757. return false;
  758. return true;
  759. }
  760. void addMemcpyableField(FieldDecl *F) {
  761. if (!FirstField)
  762. addInitialField(F);
  763. else
  764. addNextField(F);
  765. }
  766. CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
  767. unsigned LastFieldSize =
  768. LastField->isBitField() ?
  769. LastField->getBitWidthValue(CGF.getContext()) :
  770. CGF.getContext().getTypeSize(LastField->getType());
  771. uint64_t MemcpySizeBits =
  772. LastFieldOffset + LastFieldSize - FirstByteOffset +
  773. CGF.getContext().getCharWidth() - 1;
  774. CharUnits MemcpySize =
  775. CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
  776. return MemcpySize;
  777. }
  778. void emitMemcpy() {
  779. // Give the subclass a chance to bail out if it feels the memcpy isn't
  780. // worth it (e.g. Hasn't aggregated enough data).
  781. if (!FirstField) {
  782. return;
  783. }
  784. uint64_t FirstByteOffset;
  785. if (FirstField->isBitField()) {
  786. const CGRecordLayout &RL =
  787. CGF.getTypes().getCGRecordLayout(FirstField->getParent());
  788. const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
  789. // FirstFieldOffset is not appropriate for bitfields,
  790. // we need to use the storage offset instead.
  791. FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
  792. } else {
  793. FirstByteOffset = FirstFieldOffset;
  794. }
  795. CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
  796. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  797. Address ThisPtr = CGF.LoadCXXThisAddress();
  798. LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
  799. LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
  800. llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
  801. LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  802. LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
  803. emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(),
  804. Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(),
  805. MemcpySize);
  806. reset();
  807. }
  808. void reset() {
  809. FirstField = nullptr;
  810. }
  811. protected:
  812. CodeGenFunction &CGF;
  813. const CXXRecordDecl *ClassDecl;
  814. private:
  815. void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
  816. llvm::PointerType *DPT = DestPtr.getType();
  817. llvm::Type *DBP =
  818. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
  819. DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
  820. llvm::PointerType *SPT = SrcPtr.getType();
  821. llvm::Type *SBP =
  822. llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
  823. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
  824. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
  825. }
  826. void addInitialField(FieldDecl *F) {
  827. FirstField = F;
  828. LastField = F;
  829. FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  830. LastFieldOffset = FirstFieldOffset;
  831. LastAddedFieldIndex = F->getFieldIndex();
  832. }
  833. void addNextField(FieldDecl *F) {
  834. // For the most part, the following invariant will hold:
  835. // F->getFieldIndex() == LastAddedFieldIndex + 1
  836. // The one exception is that Sema won't add a copy-initializer for an
  837. // unnamed bitfield, which will show up here as a gap in the sequence.
  838. assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
  839. "Cannot aggregate fields out of order.");
  840. LastAddedFieldIndex = F->getFieldIndex();
  841. // The 'first' and 'last' fields are chosen by offset, rather than field
  842. // index. This allows the code to support bitfields, as well as regular
  843. // fields.
  844. uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  845. if (FOffset < FirstFieldOffset) {
  846. FirstField = F;
  847. FirstFieldOffset = FOffset;
  848. } else if (FOffset > LastFieldOffset) {
  849. LastField = F;
  850. LastFieldOffset = FOffset;
  851. }
  852. }
  853. const VarDecl *SrcRec;
  854. const ASTRecordLayout &RecLayout;
  855. FieldDecl *FirstField;
  856. FieldDecl *LastField;
  857. uint64_t FirstFieldOffset, LastFieldOffset;
  858. unsigned LastAddedFieldIndex;
  859. };
  860. class ConstructorMemcpyizer : public FieldMemcpyizer {
  861. private:
  862. /// Get source argument for copy constructor. Returns null if not a copy
  863. /// constructor.
  864. static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
  865. const CXXConstructorDecl *CD,
  866. FunctionArgList &Args) {
  867. if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
  868. return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
  869. return nullptr;
  870. }
  871. // Returns true if a CXXCtorInitializer represents a member initialization
  872. // that can be rolled into a memcpy.
  873. bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
  874. if (!MemcpyableCtor)
  875. return false;
  876. FieldDecl *Field = MemberInit->getMember();
  877. assert(Field && "No field for member init.");
  878. QualType FieldType = Field->getType();
  879. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  880. // Bail out on non-memcpyable, not-trivially-copyable members.
  881. if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
  882. !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
  883. FieldType->isReferenceType()))
  884. return false;
  885. // Bail out on volatile fields.
  886. if (!isMemcpyableField(Field))
  887. return false;
  888. // Otherwise we're good.
  889. return true;
  890. }
  891. public:
  892. ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
  893. FunctionArgList &Args)
  894. : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
  895. ConstructorDecl(CD),
  896. MemcpyableCtor(CD->isDefaulted() &&
  897. CD->isCopyOrMoveConstructor() &&
  898. CGF.getLangOpts().getGC() == LangOptions::NonGC),
  899. Args(Args) { }
  900. void addMemberInitializer(CXXCtorInitializer *MemberInit) {
  901. if (isMemberInitMemcpyable(MemberInit)) {
  902. AggregatedInits.push_back(MemberInit);
  903. addMemcpyableField(MemberInit->getMember());
  904. } else {
  905. emitAggregatedInits();
  906. EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
  907. ConstructorDecl, Args);
  908. }
  909. }
  910. void emitAggregatedInits() {
  911. if (AggregatedInits.size() <= 1) {
  912. // This memcpy is too small to be worthwhile. Fall back on default
  913. // codegen.
  914. if (!AggregatedInits.empty()) {
  915. CopyingValueRepresentation CVR(CGF);
  916. EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
  917. AggregatedInits[0], ConstructorDecl, Args);
  918. AggregatedInits.clear();
  919. }
  920. reset();
  921. return;
  922. }
  923. pushEHDestructors();
  924. emitMemcpy();
  925. AggregatedInits.clear();
  926. }
  927. void pushEHDestructors() {
  928. Address ThisPtr = CGF.LoadCXXThisAddress();
  929. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  930. LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
  931. for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
  932. CXXCtorInitializer *MemberInit = AggregatedInits[i];
  933. QualType FieldType = MemberInit->getAnyMember()->getType();
  934. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  935. if (!CGF.needsEHCleanup(dtorKind))
  936. continue;
  937. LValue FieldLHS = LHS;
  938. EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
  939. CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
  940. }
  941. }
  942. void finish() {
  943. emitAggregatedInits();
  944. }
  945. private:
  946. const CXXConstructorDecl *ConstructorDecl;
  947. bool MemcpyableCtor;
  948. FunctionArgList &Args;
  949. SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
  950. };
  951. class AssignmentMemcpyizer : public FieldMemcpyizer {
  952. private:
  953. // Returns the memcpyable field copied by the given statement, if one
  954. // exists. Otherwise returns null.
  955. FieldDecl *getMemcpyableField(Stmt *S) {
  956. if (!AssignmentsMemcpyable)
  957. return nullptr;
  958. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
  959. // Recognise trivial assignments.
  960. if (BO->getOpcode() != BO_Assign)
  961. return nullptr;
  962. MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
  963. if (!ME)
  964. return nullptr;
  965. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  966. if (!Field || !isMemcpyableField(Field))
  967. return nullptr;
  968. Stmt *RHS = BO->getRHS();
  969. if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
  970. RHS = EC->getSubExpr();
  971. if (!RHS)
  972. return nullptr;
  973. if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
  974. if (ME2->getMemberDecl() == Field)
  975. return Field;
  976. }
  977. return nullptr;
  978. } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
  979. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
  980. if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
  981. return nullptr;
  982. MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
  983. if (!IOA)
  984. return nullptr;
  985. FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
  986. if (!Field || !isMemcpyableField(Field))
  987. return nullptr;
  988. MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
  989. if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
  990. return nullptr;
  991. return Field;
  992. } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  993. FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  994. if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
  995. return nullptr;
  996. Expr *DstPtr = CE->getArg(0);
  997. if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
  998. DstPtr = DC->getSubExpr();
  999. UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
  1000. if (!DUO || DUO->getOpcode() != UO_AddrOf)
  1001. return nullptr;
  1002. MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
  1003. if (!ME)
  1004. return nullptr;
  1005. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  1006. if (!Field || !isMemcpyableField(Field))
  1007. return nullptr;
  1008. Expr *SrcPtr = CE->getArg(1);
  1009. if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
  1010. SrcPtr = SC->getSubExpr();
  1011. UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
  1012. if (!SUO || SUO->getOpcode() != UO_AddrOf)
  1013. return nullptr;
  1014. MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
  1015. if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
  1016. return nullptr;
  1017. return Field;
  1018. }
  1019. return nullptr;
  1020. }
  1021. bool AssignmentsMemcpyable;
  1022. SmallVector<Stmt*, 16> AggregatedStmts;
  1023. public:
  1024. AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
  1025. FunctionArgList &Args)
  1026. : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
  1027. AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
  1028. assert(Args.size() == 2);
  1029. }
  1030. void emitAssignment(Stmt *S) {
  1031. FieldDecl *F = getMemcpyableField(S);
  1032. if (F) {
  1033. addMemcpyableField(F);
  1034. AggregatedStmts.push_back(S);
  1035. } else {
  1036. emitAggregatedStmts();
  1037. CGF.EmitStmt(S);
  1038. }
  1039. }
  1040. void emitAggregatedStmts() {
  1041. if (AggregatedStmts.size() <= 1) {
  1042. if (!AggregatedStmts.empty()) {
  1043. CopyingValueRepresentation CVR(CGF);
  1044. CGF.EmitStmt(AggregatedStmts[0]);
  1045. }
  1046. reset();
  1047. }
  1048. emitMemcpy();
  1049. AggregatedStmts.clear();
  1050. }
  1051. void finish() {
  1052. emitAggregatedStmts();
  1053. }
  1054. };
  1055. } // end anonymous namespace
  1056. static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
  1057. const Type *BaseType = BaseInit->getBaseClass();
  1058. const auto *BaseClassDecl =
  1059. cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
  1060. return BaseClassDecl->isDynamicClass();
  1061. }
  1062. /// EmitCtorPrologue - This routine generates necessary code to initialize
  1063. /// base classes and non-static data members belonging to this constructor.
  1064. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  1065. CXXCtorType CtorType,
  1066. FunctionArgList &Args) {
  1067. if (CD->isDelegatingConstructor())
  1068. return EmitDelegatingCXXConstructorCall(CD, Args);
  1069. const CXXRecordDecl *ClassDecl = CD->getParent();
  1070. CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  1071. E = CD->init_end();
  1072. llvm::BasicBlock *BaseCtorContinueBB = nullptr;
  1073. if (ClassDecl->getNumVBases() &&
  1074. !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1075. // The ABIs that don't have constructor variants need to put a branch
  1076. // before the virtual base initialization code.
  1077. BaseCtorContinueBB =
  1078. CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
  1079. assert(BaseCtorContinueBB);
  1080. }
  1081. llvm::Value *const OldThis = CXXThisValue;
  1082. // Virtual base initializers first.
  1083. for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
  1084. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1085. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1086. isInitializerOfDynamicClass(*B))
  1087. CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
  1088. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1089. }
  1090. if (BaseCtorContinueBB) {
  1091. // Complete object handler should continue to the remaining initializers.
  1092. Builder.CreateBr(BaseCtorContinueBB);
  1093. EmitBlock(BaseCtorContinueBB);
  1094. }
  1095. // Then, non-virtual base initializers.
  1096. for (; B != E && (*B)->isBaseInitializer(); B++) {
  1097. assert(!(*B)->isBaseVirtual());
  1098. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1099. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1100. isInitializerOfDynamicClass(*B))
  1101. CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
  1102. EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
  1103. }
  1104. CXXThisValue = OldThis;
  1105. InitializeVTablePointers(ClassDecl);
  1106. // And finally, initialize class members.
  1107. FieldConstructionScope FCS(*this, LoadCXXThisAddress());
  1108. ConstructorMemcpyizer CM(*this, CD, Args);
  1109. for (; B != E; B++) {
  1110. CXXCtorInitializer *Member = (*B);
  1111. assert(!Member->isBaseInitializer());
  1112. assert(Member->isAnyMemberInitializer() &&
  1113. "Delegating initializer on non-delegating constructor");
  1114. CM.addMemberInitializer(Member);
  1115. }
  1116. CM.finish();
  1117. }
  1118. static bool
  1119. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  1120. static bool
  1121. HasTrivialDestructorBody(ASTContext &Context,
  1122. const CXXRecordDecl *BaseClassDecl,
  1123. const CXXRecordDecl *MostDerivedClassDecl)
  1124. {
  1125. // If the destructor is trivial we don't have to check anything else.
  1126. if (BaseClassDecl->hasTrivialDestructor())
  1127. return true;
  1128. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  1129. return false;
  1130. // Check fields.
  1131. for (const auto *Field : BaseClassDecl->fields())
  1132. if (!FieldHasTrivialDestructorBody(Context, Field))
  1133. return false;
  1134. // Check non-virtual bases.
  1135. for (const auto &I : BaseClassDecl->bases()) {
  1136. if (I.isVirtual())
  1137. continue;
  1138. const CXXRecordDecl *NonVirtualBase =
  1139. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1140. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  1141. MostDerivedClassDecl))
  1142. return false;
  1143. }
  1144. if (BaseClassDecl == MostDerivedClassDecl) {
  1145. // Check virtual bases.
  1146. for (const auto &I : BaseClassDecl->vbases()) {
  1147. const CXXRecordDecl *VirtualBase =
  1148. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1149. if (!HasTrivialDestructorBody(Context, VirtualBase,
  1150. MostDerivedClassDecl))
  1151. return false;
  1152. }
  1153. }
  1154. return true;
  1155. }
  1156. static bool
  1157. FieldHasTrivialDestructorBody(ASTContext &Context,
  1158. const FieldDecl *Field)
  1159. {
  1160. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  1161. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  1162. if (!RT)
  1163. return true;
  1164. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  1165. // The destructor for an implicit anonymous union member is never invoked.
  1166. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  1167. return false;
  1168. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  1169. }
  1170. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  1171. /// any vtable pointers before calling this destructor.
  1172. static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
  1173. const CXXDestructorDecl *Dtor) {
  1174. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1175. if (!ClassDecl->isDynamicClass())
  1176. return true;
  1177. if (!Dtor->hasTrivialBody())
  1178. return false;
  1179. // Check the fields.
  1180. for (const auto *Field : ClassDecl->fields())
  1181. if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
  1182. return false;
  1183. return true;
  1184. }
  1185. /// EmitDestructorBody - Emits the body of the current destructor.
  1186. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  1187. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  1188. CXXDtorType DtorType = CurGD.getDtorType();
  1189. // For an abstract class, non-base destructors are never used (and can't
  1190. // be emitted in general, because vbase dtors may not have been validated
  1191. // by Sema), but the Itanium ABI doesn't make them optional and Clang may
  1192. // in fact emit references to them from other compilations, so emit them
  1193. // as functions containing a trap instruction.
  1194. if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
  1195. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  1196. TrapCall->setDoesNotReturn();
  1197. TrapCall->setDoesNotThrow();
  1198. Builder.CreateUnreachable();
  1199. Builder.ClearInsertionPoint();
  1200. return;
  1201. }
  1202. Stmt *Body = Dtor->getBody();
  1203. if (Body)
  1204. incrementProfileCounter(Body);
  1205. // The call to operator delete in a deleting destructor happens
  1206. // outside of the function-try-block, which means it's always
  1207. // possible to delegate the destructor body to the complete
  1208. // destructor. Do so.
  1209. if (DtorType == Dtor_Deleting) {
  1210. EnterDtorCleanups(Dtor, Dtor_Deleting);
  1211. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  1212. /*Delegating=*/false, LoadCXXThisAddress());
  1213. PopCleanupBlock();
  1214. return;
  1215. }
  1216. // If the body is a function-try-block, enter the try before
  1217. // anything else.
  1218. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  1219. if (isTryBody)
  1220. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1221. EmitAsanPrologueOrEpilogue(false);
  1222. // Enter the epilogue cleanups.
  1223. RunCleanupsScope DtorEpilogue(*this);
  1224. // If this is the complete variant, just invoke the base variant;
  1225. // the epilogue will destruct the virtual bases. But we can't do
  1226. // this optimization if the body is a function-try-block, because
  1227. // we'd introduce *two* handler blocks. In the Microsoft ABI, we
  1228. // always delegate because we might not have a definition in this TU.
  1229. switch (DtorType) {
  1230. case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
  1231. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  1232. case Dtor_Complete:
  1233. assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
  1234. "can't emit a dtor without a body for non-Microsoft ABIs");
  1235. // Enter the cleanup scopes for virtual bases.
  1236. EnterDtorCleanups(Dtor, Dtor_Complete);
  1237. if (!isTryBody) {
  1238. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1239. /*Delegating=*/false, LoadCXXThisAddress());
  1240. break;
  1241. }
  1242. // Fallthrough: act like we're in the base variant.
  1243. LLVM_FALLTHROUGH;
  1244. case Dtor_Base:
  1245. assert(Body);
  1246. // Enter the cleanup scopes for fields and non-virtual bases.
  1247. EnterDtorCleanups(Dtor, Dtor_Base);
  1248. // Initialize the vtable pointers before entering the body.
  1249. if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
  1250. // Insert the llvm.invariant.group.barrier intrinsic before initializing
  1251. // the vptrs to cancel any previous assumptions we might have made.
  1252. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1253. CGM.getCodeGenOpts().OptimizationLevel > 0)
  1254. CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis());
  1255. InitializeVTablePointers(Dtor->getParent());
  1256. }
  1257. if (isTryBody)
  1258. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  1259. else if (Body)
  1260. EmitStmt(Body);
  1261. else {
  1262. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  1263. // nothing to do besides what's in the epilogue
  1264. }
  1265. // -fapple-kext must inline any call to this dtor into
  1266. // the caller's body.
  1267. if (getLangOpts().AppleKext)
  1268. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  1269. break;
  1270. }
  1271. // Jump out through the epilogue cleanups.
  1272. DtorEpilogue.ForceCleanup();
  1273. // Exit the try if applicable.
  1274. if (isTryBody)
  1275. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1276. }
  1277. void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
  1278. const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
  1279. const Stmt *RootS = AssignOp->getBody();
  1280. assert(isa<CompoundStmt>(RootS) &&
  1281. "Body of an implicit assignment operator should be compound stmt.");
  1282. const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
  1283. LexicalScope Scope(*this, RootCS->getSourceRange());
  1284. incrementProfileCounter(RootCS);
  1285. AssignmentMemcpyizer AM(*this, AssignOp, Args);
  1286. for (auto *I : RootCS->body())
  1287. AM.emitAssignment(I);
  1288. AM.finish();
  1289. }
  1290. namespace {
  1291. /// Call the operator delete associated with the current destructor.
  1292. struct CallDtorDelete final : EHScopeStack::Cleanup {
  1293. CallDtorDelete() {}
  1294. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1295. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1296. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1297. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1298. CGF.getContext().getTagDeclType(ClassDecl));
  1299. }
  1300. };
  1301. struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
  1302. llvm::Value *ShouldDeleteCondition;
  1303. public:
  1304. CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
  1305. : ShouldDeleteCondition(ShouldDeleteCondition) {
  1306. assert(ShouldDeleteCondition != nullptr);
  1307. }
  1308. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1309. llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
  1310. llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
  1311. llvm::Value *ShouldCallDelete
  1312. = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
  1313. CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
  1314. CGF.EmitBlock(callDeleteBB);
  1315. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1316. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1317. CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
  1318. CGF.getContext().getTagDeclType(ClassDecl));
  1319. CGF.Builder.CreateBr(continueBB);
  1320. CGF.EmitBlock(continueBB);
  1321. }
  1322. };
  1323. class DestroyField final : public EHScopeStack::Cleanup {
  1324. const FieldDecl *field;
  1325. CodeGenFunction::Destroyer *destroyer;
  1326. bool useEHCleanupForArray;
  1327. public:
  1328. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  1329. bool useEHCleanupForArray)
  1330. : field(field), destroyer(destroyer),
  1331. useEHCleanupForArray(useEHCleanupForArray) {}
  1332. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1333. // Find the address of the field.
  1334. Address thisValue = CGF.LoadCXXThisAddress();
  1335. QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
  1336. LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
  1337. LValue LV = CGF.EmitLValueForField(ThisLV, field);
  1338. assert(LV.isSimple());
  1339. CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
  1340. flags.isForNormalCleanup() && useEHCleanupForArray);
  1341. }
  1342. };
  1343. static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
  1344. CharUnits::QuantityType PoisonSize) {
  1345. CodeGenFunction::SanitizerScope SanScope(&CGF);
  1346. // Pass in void pointer and size of region as arguments to runtime
  1347. // function
  1348. llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy),
  1349. llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
  1350. llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
  1351. llvm::FunctionType *FnType =
  1352. llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
  1353. llvm::Value *Fn =
  1354. CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
  1355. CGF.EmitNounwindRuntimeCall(Fn, Args);
  1356. }
  1357. class SanitizeDtorMembers final : public EHScopeStack::Cleanup {
  1358. const CXXDestructorDecl *Dtor;
  1359. public:
  1360. SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1361. // Generate function call for handling object poisoning.
  1362. // Disables tail call elimination, to prevent the current stack frame
  1363. // from disappearing from the stack trace.
  1364. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1365. const ASTRecordLayout &Layout =
  1366. CGF.getContext().getASTRecordLayout(Dtor->getParent());
  1367. // Nothing to poison.
  1368. if (Layout.getFieldCount() == 0)
  1369. return;
  1370. // Prevent the current stack frame from disappearing from the stack trace.
  1371. CGF.CurFn->addFnAttr("disable-tail-calls", "true");
  1372. // Construct pointer to region to begin poisoning, and calculate poison
  1373. // size, so that only members declared in this class are poisoned.
  1374. ASTContext &Context = CGF.getContext();
  1375. unsigned fieldIndex = 0;
  1376. int startIndex = -1;
  1377. // RecordDecl::field_iterator Field;
  1378. for (const FieldDecl *Field : Dtor->getParent()->fields()) {
  1379. // Poison field if it is trivial
  1380. if (FieldHasTrivialDestructorBody(Context, Field)) {
  1381. // Start sanitizing at this field
  1382. if (startIndex < 0)
  1383. startIndex = fieldIndex;
  1384. // Currently on the last field, and it must be poisoned with the
  1385. // current block.
  1386. if (fieldIndex == Layout.getFieldCount() - 1) {
  1387. PoisonMembers(CGF, startIndex, Layout.getFieldCount());
  1388. }
  1389. } else if (startIndex >= 0) {
  1390. // No longer within a block of memory to poison, so poison the block
  1391. PoisonMembers(CGF, startIndex, fieldIndex);
  1392. // Re-set the start index
  1393. startIndex = -1;
  1394. }
  1395. fieldIndex += 1;
  1396. }
  1397. }
  1398. private:
  1399. /// \param layoutStartOffset index of the ASTRecordLayout field to
  1400. /// start poisoning (inclusive)
  1401. /// \param layoutEndOffset index of the ASTRecordLayout field to
  1402. /// end poisoning (exclusive)
  1403. void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset,
  1404. unsigned layoutEndOffset) {
  1405. ASTContext &Context = CGF.getContext();
  1406. const ASTRecordLayout &Layout =
  1407. Context.getASTRecordLayout(Dtor->getParent());
  1408. llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
  1409. CGF.SizeTy,
  1410. Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
  1411. .getQuantity());
  1412. llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
  1413. CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
  1414. OffsetSizePtr);
  1415. CharUnits::QuantityType PoisonSize;
  1416. if (layoutEndOffset >= Layout.getFieldCount()) {
  1417. PoisonSize = Layout.getNonVirtualSize().getQuantity() -
  1418. Context.toCharUnitsFromBits(
  1419. Layout.getFieldOffset(layoutStartOffset))
  1420. .getQuantity();
  1421. } else {
  1422. PoisonSize = Context.toCharUnitsFromBits(
  1423. Layout.getFieldOffset(layoutEndOffset) -
  1424. Layout.getFieldOffset(layoutStartOffset))
  1425. .getQuantity();
  1426. }
  1427. if (PoisonSize == 0)
  1428. return;
  1429. EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize);
  1430. }
  1431. };
  1432. class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
  1433. const CXXDestructorDecl *Dtor;
  1434. public:
  1435. SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1436. // Generate function call for handling vtable pointer poisoning.
  1437. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1438. assert(Dtor->getParent()->isDynamicClass());
  1439. (void)Dtor;
  1440. ASTContext &Context = CGF.getContext();
  1441. // Poison vtable and vtable ptr if they exist for this class.
  1442. llvm::Value *VTablePtr = CGF.LoadCXXThis();
  1443. CharUnits::QuantityType PoisonSize =
  1444. Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity();
  1445. // Pass in void pointer and size of region as arguments to runtime
  1446. // function
  1447. EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize);
  1448. }
  1449. };
  1450. } // end anonymous namespace
  1451. /// \brief Emit all code that comes at the end of class's
  1452. /// destructor. This is to call destructors on members and base classes
  1453. /// in reverse order of their construction.
  1454. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  1455. CXXDtorType DtorType) {
  1456. assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
  1457. "Should not emit dtor epilogue for non-exported trivial dtor!");
  1458. // The deleting-destructor phase just needs to call the appropriate
  1459. // operator delete that Sema picked up.
  1460. if (DtorType == Dtor_Deleting) {
  1461. assert(DD->getOperatorDelete() &&
  1462. "operator delete missing - EnterDtorCleanups");
  1463. if (CXXStructorImplicitParamValue) {
  1464. // If there is an implicit param to the deleting dtor, it's a boolean
  1465. // telling whether we should call delete at the end of the dtor.
  1466. EHStack.pushCleanup<CallDtorDeleteConditional>(
  1467. NormalAndEHCleanup, CXXStructorImplicitParamValue);
  1468. } else {
  1469. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  1470. }
  1471. return;
  1472. }
  1473. const CXXRecordDecl *ClassDecl = DD->getParent();
  1474. // Unions have no bases and do not call field destructors.
  1475. if (ClassDecl->isUnion())
  1476. return;
  1477. // The complete-destructor phase just destructs all the virtual bases.
  1478. if (DtorType == Dtor_Complete) {
  1479. // Poison the vtable pointer such that access after the base
  1480. // and member destructors are invoked is invalid.
  1481. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1482. SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
  1483. ClassDecl->isPolymorphic())
  1484. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1485. // We push them in the forward order so that they'll be popped in
  1486. // the reverse order.
  1487. for (const auto &Base : ClassDecl->vbases()) {
  1488. CXXRecordDecl *BaseClassDecl
  1489. = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
  1490. // Ignore trivial destructors.
  1491. if (BaseClassDecl->hasTrivialDestructor())
  1492. continue;
  1493. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1494. BaseClassDecl,
  1495. /*BaseIsVirtual*/ true);
  1496. }
  1497. return;
  1498. }
  1499. assert(DtorType == Dtor_Base);
  1500. // Poison the vtable pointer if it has no virtual bases, but inherits
  1501. // virtual functions.
  1502. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1503. SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
  1504. ClassDecl->isPolymorphic())
  1505. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1506. // Destroy non-virtual bases.
  1507. for (const auto &Base : ClassDecl->bases()) {
  1508. // Ignore virtual bases.
  1509. if (Base.isVirtual())
  1510. continue;
  1511. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  1512. // Ignore trivial destructors.
  1513. if (BaseClassDecl->hasTrivialDestructor())
  1514. continue;
  1515. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
  1516. BaseClassDecl,
  1517. /*BaseIsVirtual*/ false);
  1518. }
  1519. // Poison fields such that access after their destructors are
  1520. // invoked, and before the base class destructor runs, is invalid.
  1521. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1522. SanOpts.has(SanitizerKind::Memory))
  1523. EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD);
  1524. // Destroy direct fields.
  1525. for (const auto *Field : ClassDecl->fields()) {
  1526. QualType type = Field->getType();
  1527. QualType::DestructionKind dtorKind = type.isDestructedType();
  1528. if (!dtorKind) continue;
  1529. // Anonymous union members do not have their destructors called.
  1530. const RecordType *RT = type->getAsUnionType();
  1531. if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
  1532. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1533. EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
  1534. getDestroyer(dtorKind),
  1535. cleanupKind & EHCleanup);
  1536. }
  1537. }
  1538. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1539. /// constructor for each of several members of an array.
  1540. ///
  1541. /// \param ctor the constructor to call for each element
  1542. /// \param arrayType the type of the array to initialize
  1543. /// \param arrayBegin an arrayType*
  1544. /// \param zeroInitialize true if each element should be
  1545. /// zero-initialized before it is constructed
  1546. void CodeGenFunction::EmitCXXAggrConstructorCall(
  1547. const CXXConstructorDecl *ctor, const ArrayType *arrayType,
  1548. Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
  1549. QualType elementType;
  1550. llvm::Value *numElements =
  1551. emitArrayLength(arrayType, elementType, arrayBegin);
  1552. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
  1553. }
  1554. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1555. /// constructor for each of several members of an array.
  1556. ///
  1557. /// \param ctor the constructor to call for each element
  1558. /// \param numElements the number of elements in the array;
  1559. /// may be zero
  1560. /// \param arrayBase a T*, where T is the type constructed by ctor
  1561. /// \param zeroInitialize true if each element should be
  1562. /// zero-initialized before it is constructed
  1563. void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1564. llvm::Value *numElements,
  1565. Address arrayBase,
  1566. const CXXConstructExpr *E,
  1567. bool zeroInitialize) {
  1568. // It's legal for numElements to be zero. This can happen both
  1569. // dynamically, because x can be zero in 'new A[x]', and statically,
  1570. // because of GCC extensions that permit zero-length arrays. There
  1571. // are probably legitimate places where we could assume that this
  1572. // doesn't happen, but it's not clear that it's worth it.
  1573. llvm::BranchInst *zeroCheckBranch = nullptr;
  1574. // Optimize for a constant count.
  1575. llvm::ConstantInt *constantCount
  1576. = dyn_cast<llvm::ConstantInt>(numElements);
  1577. if (constantCount) {
  1578. // Just skip out if the constant count is zero.
  1579. if (constantCount->isZero()) return;
  1580. // Otherwise, emit the check.
  1581. } else {
  1582. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  1583. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  1584. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  1585. EmitBlock(loopBB);
  1586. }
  1587. // Find the end of the array.
  1588. llvm::Value *arrayBegin = arrayBase.getPointer();
  1589. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
  1590. "arrayctor.end");
  1591. // Enter the loop, setting up a phi for the current location to initialize.
  1592. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1593. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  1594. EmitBlock(loopBB);
  1595. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  1596. "arrayctor.cur");
  1597. cur->addIncoming(arrayBegin, entryBB);
  1598. // Inside the loop body, emit the constructor call on the array element.
  1599. // The alignment of the base, adjusted by the size of a single element,
  1600. // provides a conservative estimate of the alignment of every element.
  1601. // (This assumes we never start tracking offsetted alignments.)
  1602. //
  1603. // Note that these are complete objects and so we don't need to
  1604. // use the non-virtual size or alignment.
  1605. QualType type = getContext().getTypeDeclType(ctor->getParent());
  1606. CharUnits eltAlignment =
  1607. arrayBase.getAlignment()
  1608. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1609. Address curAddr = Address(cur, eltAlignment);
  1610. // Zero initialize the storage, if requested.
  1611. if (zeroInitialize)
  1612. EmitNullInitialization(curAddr, type);
  1613. // C++ [class.temporary]p4:
  1614. // There are two contexts in which temporaries are destroyed at a different
  1615. // point than the end of the full-expression. The first context is when a
  1616. // default constructor is called to initialize an element of an array.
  1617. // If the constructor has one or more default arguments, the destruction of
  1618. // every temporary created in a default argument expression is sequenced
  1619. // before the construction of the next array element, if any.
  1620. {
  1621. RunCleanupsScope Scope(*this);
  1622. // Evaluate the constructor and its arguments in a regular
  1623. // partial-destroy cleanup.
  1624. if (getLangOpts().Exceptions &&
  1625. !ctor->getParent()->hasTrivialDestructor()) {
  1626. Destroyer *destroyer = destroyCXXObject;
  1627. pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
  1628. *destroyer);
  1629. }
  1630. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
  1631. /*Delegating=*/false, curAddr, E);
  1632. }
  1633. // Go to the next element.
  1634. llvm::Value *next =
  1635. Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
  1636. "arrayctor.next");
  1637. cur->addIncoming(next, Builder.GetInsertBlock());
  1638. // Check whether that's the end of the loop.
  1639. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  1640. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  1641. Builder.CreateCondBr(done, contBB, loopBB);
  1642. // Patch the earlier check to skip over the loop.
  1643. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  1644. EmitBlock(contBB);
  1645. }
  1646. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  1647. Address addr,
  1648. QualType type) {
  1649. const RecordType *rtype = type->castAs<RecordType>();
  1650. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  1651. const CXXDestructorDecl *dtor = record->getDestructor();
  1652. assert(!dtor->isTrivial());
  1653. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  1654. /*Delegating=*/false, addr);
  1655. }
  1656. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1657. CXXCtorType Type,
  1658. bool ForVirtualBase,
  1659. bool Delegating, Address This,
  1660. const CXXConstructExpr *E) {
  1661. CallArgList Args;
  1662. // Push the this ptr.
  1663. Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1664. // If this is a trivial constructor, emit a memcpy now before we lose
  1665. // the alignment information on the argument.
  1666. // FIXME: It would be better to preserve alignment information into CallArg.
  1667. if (isMemcpyEquivalentSpecialMember(D)) {
  1668. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1669. const Expr *Arg = E->getArg(0);
  1670. QualType SrcTy = Arg->getType();
  1671. Address Src = EmitLValue(Arg).getAddress();
  1672. QualType DestTy = getContext().getTypeDeclType(D->getParent());
  1673. EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
  1674. return;
  1675. }
  1676. // Add the rest of the user-supplied arguments.
  1677. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1678. EvaluationOrder Order = E->isListInitialization()
  1679. ? EvaluationOrder::ForceLeftToRight
  1680. : EvaluationOrder::Default;
  1681. EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
  1682. /*ParamsToSkip*/ 0, Order);
  1683. EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args);
  1684. }
  1685. static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
  1686. const CXXConstructorDecl *Ctor,
  1687. CXXCtorType Type, CallArgList &Args) {
  1688. // We can't forward a variadic call.
  1689. if (Ctor->isVariadic())
  1690. return false;
  1691. if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1692. // If the parameters are callee-cleanup, it's not safe to forward.
  1693. for (auto *P : Ctor->parameters())
  1694. if (P->getType().isDestructedType())
  1695. return false;
  1696. // Likewise if they're inalloca.
  1697. const CGFunctionInfo &Info =
  1698. CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
  1699. if (Info.usesInAlloca())
  1700. return false;
  1701. }
  1702. // Anything else should be OK.
  1703. return true;
  1704. }
  1705. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1706. CXXCtorType Type,
  1707. bool ForVirtualBase,
  1708. bool Delegating,
  1709. Address This,
  1710. CallArgList &Args) {
  1711. const CXXRecordDecl *ClassDecl = D->getParent();
  1712. // C++11 [class.mfct.non-static]p2:
  1713. // If a non-static member function of a class X is called for an object that
  1714. // is not of type X, or of a type derived from X, the behavior is undefined.
  1715. // FIXME: Provide a source location here.
  1716. EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(),
  1717. This.getPointer(), getContext().getRecordType(ClassDecl));
  1718. if (D->isTrivial() && D->isDefaultConstructor()) {
  1719. assert(Args.size() == 1 && "trivial default ctor with args");
  1720. return;
  1721. }
  1722. // If this is a trivial constructor, just emit what's needed. If this is a
  1723. // union copy constructor, we must emit a memcpy, because the AST does not
  1724. // model that copy.
  1725. if (isMemcpyEquivalentSpecialMember(D)) {
  1726. assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
  1727. QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
  1728. Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy));
  1729. QualType DestTy = getContext().getTypeDeclType(ClassDecl);
  1730. EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
  1731. return;
  1732. }
  1733. bool PassPrototypeArgs = true;
  1734. // Check whether we can actually emit the constructor before trying to do so.
  1735. if (auto Inherited = D->getInheritedConstructor()) {
  1736. PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
  1737. if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
  1738. EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
  1739. Delegating, Args);
  1740. return;
  1741. }
  1742. }
  1743. // Insert any ABI-specific implicit constructor arguments.
  1744. CGCXXABI::AddedStructorArgs ExtraArgs =
  1745. CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
  1746. Delegating, Args);
  1747. // Emit the call.
  1748. llvm::Constant *CalleePtr =
  1749. CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
  1750. const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
  1751. Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
  1752. CGCallee Callee = CGCallee::forDirect(CalleePtr, D);
  1753. EmitCall(Info, Callee, ReturnValueSlot(), Args);
  1754. // Generate vtable assumptions if we're constructing a complete object
  1755. // with a vtable. We don't do this for base subobjects for two reasons:
  1756. // first, it's incorrect for classes with virtual bases, and second, we're
  1757. // about to overwrite the vptrs anyway.
  1758. // We also have to make sure if we can refer to vtable:
  1759. // - Otherwise we can refer to vtable if it's safe to speculatively emit.
  1760. // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
  1761. // sure that definition of vtable is not hidden,
  1762. // then we are always safe to refer to it.
  1763. // FIXME: It looks like InstCombine is very inefficient on dealing with
  1764. // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
  1765. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1766. ClassDecl->isDynamicClass() && Type != Ctor_Base &&
  1767. CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
  1768. CGM.getCodeGenOpts().StrictVTablePointers)
  1769. EmitVTableAssumptionLoads(ClassDecl, This);
  1770. }
  1771. void CodeGenFunction::EmitInheritedCXXConstructorCall(
  1772. const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
  1773. bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
  1774. CallArgList Args;
  1775. CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()),
  1776. /*NeedsCopy=*/false);
  1777. // Forward the parameters.
  1778. if (InheritedFromVBase &&
  1779. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1780. // Nothing to do; this construction is not responsible for constructing
  1781. // the base class containing the inherited constructor.
  1782. // FIXME: Can we just pass undef's for the remaining arguments if we don't
  1783. // have constructor variants?
  1784. Args.push_back(ThisArg);
  1785. } else if (!CXXInheritedCtorInitExprArgs.empty()) {
  1786. // The inheriting constructor was inlined; just inject its arguments.
  1787. assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
  1788. "wrong number of parameters for inherited constructor call");
  1789. Args = CXXInheritedCtorInitExprArgs;
  1790. Args[0] = ThisArg;
  1791. } else {
  1792. // The inheriting constructor was not inlined. Emit delegating arguments.
  1793. Args.push_back(ThisArg);
  1794. const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
  1795. assert(OuterCtor->getNumParams() == D->getNumParams());
  1796. assert(!OuterCtor->isVariadic() && "should have been inlined");
  1797. for (const auto *Param : OuterCtor->parameters()) {
  1798. assert(getContext().hasSameUnqualifiedType(
  1799. OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
  1800. Param->getType()));
  1801. EmitDelegateCallArg(Args, Param, E->getLocation());
  1802. // Forward __attribute__(pass_object_size).
  1803. if (Param->hasAttr<PassObjectSizeAttr>()) {
  1804. auto *POSParam = SizeArguments[Param];
  1805. assert(POSParam && "missing pass_object_size value for forwarding");
  1806. EmitDelegateCallArg(Args, POSParam, E->getLocation());
  1807. }
  1808. }
  1809. }
  1810. EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
  1811. This, Args);
  1812. }
  1813. void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
  1814. const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
  1815. bool Delegating, CallArgList &Args) {
  1816. GlobalDecl GD(Ctor, CtorType);
  1817. InlinedInheritingConstructorScope Scope(*this, GD);
  1818. ApplyInlineDebugLocation DebugScope(*this, GD);
  1819. // Save the arguments to be passed to the inherited constructor.
  1820. CXXInheritedCtorInitExprArgs = Args;
  1821. FunctionArgList Params;
  1822. QualType RetType = BuildFunctionArgList(CurGD, Params);
  1823. FnRetTy = RetType;
  1824. // Insert any ABI-specific implicit constructor arguments.
  1825. CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
  1826. ForVirtualBase, Delegating, Args);
  1827. // Emit a simplified prolog. We only need to emit the implicit params.
  1828. assert(Args.size() >= Params.size() && "too few arguments for call");
  1829. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  1830. if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
  1831. const RValue &RV = Args[I].RV;
  1832. assert(!RV.isComplex() && "complex indirect params not supported");
  1833. ParamValue Val = RV.isScalar()
  1834. ? ParamValue::forDirect(RV.getScalarVal())
  1835. : ParamValue::forIndirect(RV.getAggregateAddress());
  1836. EmitParmDecl(*Params[I], Val, I + 1);
  1837. }
  1838. }
  1839. // Create a return value slot if the ABI implementation wants one.
  1840. // FIXME: This is dumb, we should ask the ABI not to try to set the return
  1841. // value instead.
  1842. if (!RetType->isVoidType())
  1843. ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
  1844. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  1845. CXXThisValue = CXXABIThisValue;
  1846. // Directly emit the constructor initializers.
  1847. EmitCtorPrologue(Ctor, CtorType, Params);
  1848. }
  1849. void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
  1850. llvm::Value *VTableGlobal =
  1851. CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
  1852. if (!VTableGlobal)
  1853. return;
  1854. // We can just use the base offset in the complete class.
  1855. CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
  1856. if (!NonVirtualOffset.isZero())
  1857. This =
  1858. ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
  1859. Vptr.VTableClass, Vptr.NearestVBase);
  1860. llvm::Value *VPtrValue =
  1861. GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
  1862. llvm::Value *Cmp =
  1863. Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
  1864. Builder.CreateAssumption(Cmp);
  1865. }
  1866. void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
  1867. Address This) {
  1868. if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
  1869. for (const VPtr &Vptr : getVTablePointers(ClassDecl))
  1870. EmitVTableAssumptionLoad(Vptr, This);
  1871. }
  1872. void
  1873. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1874. Address This, Address Src,
  1875. const CXXConstructExpr *E) {
  1876. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1877. CallArgList Args;
  1878. // Push the this ptr.
  1879. Args.add(RValue::get(This.getPointer()), D->getThisType(getContext()));
  1880. // Push the src ptr.
  1881. QualType QT = *(FPT->param_type_begin());
  1882. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  1883. Src = Builder.CreateBitCast(Src, t);
  1884. Args.add(RValue::get(Src.getPointer()), QT);
  1885. // Skip over first argument (Src).
  1886. EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
  1887. /*ParamsToSkip*/ 1);
  1888. EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args);
  1889. }
  1890. void
  1891. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1892. CXXCtorType CtorType,
  1893. const FunctionArgList &Args,
  1894. SourceLocation Loc) {
  1895. CallArgList DelegateArgs;
  1896. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  1897. assert(I != E && "no parameters to constructor");
  1898. // this
  1899. Address This = LoadCXXThisAddress();
  1900. DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
  1901. ++I;
  1902. // FIXME: The location of the VTT parameter in the parameter list is
  1903. // specific to the Itanium ABI and shouldn't be hardcoded here.
  1904. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  1905. assert(I != E && "cannot skip vtt parameter, already done with args");
  1906. assert((*I)->getType()->isPointerType() &&
  1907. "skipping parameter not of vtt type");
  1908. ++I;
  1909. }
  1910. // Explicit arguments.
  1911. for (; I != E; ++I) {
  1912. const VarDecl *param = *I;
  1913. // FIXME: per-argument source location
  1914. EmitDelegateCallArg(DelegateArgs, param, Loc);
  1915. }
  1916. EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
  1917. /*Delegating=*/true, This, DelegateArgs);
  1918. }
  1919. namespace {
  1920. struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
  1921. const CXXDestructorDecl *Dtor;
  1922. Address Addr;
  1923. CXXDtorType Type;
  1924. CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
  1925. CXXDtorType Type)
  1926. : Dtor(D), Addr(Addr), Type(Type) {}
  1927. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1928. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  1929. /*Delegating=*/true, Addr);
  1930. }
  1931. };
  1932. } // end anonymous namespace
  1933. void
  1934. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1935. const FunctionArgList &Args) {
  1936. assert(Ctor->isDelegatingConstructor());
  1937. Address ThisPtr = LoadCXXThisAddress();
  1938. AggValueSlot AggSlot =
  1939. AggValueSlot::forAddr(ThisPtr, Qualifiers(),
  1940. AggValueSlot::IsDestructed,
  1941. AggValueSlot::DoesNotNeedGCBarriers,
  1942. AggValueSlot::IsNotAliased);
  1943. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  1944. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  1945. if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  1946. CXXDtorType Type =
  1947. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  1948. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  1949. ClassDecl->getDestructor(),
  1950. ThisPtr, Type);
  1951. }
  1952. }
  1953. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  1954. CXXDtorType Type,
  1955. bool ForVirtualBase,
  1956. bool Delegating,
  1957. Address This) {
  1958. CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
  1959. Delegating, This);
  1960. }
  1961. namespace {
  1962. struct CallLocalDtor final : EHScopeStack::Cleanup {
  1963. const CXXDestructorDecl *Dtor;
  1964. Address Addr;
  1965. CallLocalDtor(const CXXDestructorDecl *D, Address Addr)
  1966. : Dtor(D), Addr(Addr) {}
  1967. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1968. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  1969. /*ForVirtualBase=*/false,
  1970. /*Delegating=*/false, Addr);
  1971. }
  1972. };
  1973. } // end anonymous namespace
  1974. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  1975. Address Addr) {
  1976. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
  1977. }
  1978. void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
  1979. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  1980. if (!ClassDecl) return;
  1981. if (ClassDecl->hasTrivialDestructor()) return;
  1982. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  1983. assert(D && D->isUsed() && "destructor not marked as used!");
  1984. PushDestructorCleanup(D, Addr);
  1985. }
  1986. void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
  1987. // Compute the address point.
  1988. llvm::Value *VTableAddressPoint =
  1989. CGM.getCXXABI().getVTableAddressPointInStructor(
  1990. *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
  1991. if (!VTableAddressPoint)
  1992. return;
  1993. // Compute where to store the address point.
  1994. llvm::Value *VirtualOffset = nullptr;
  1995. CharUnits NonVirtualOffset = CharUnits::Zero();
  1996. if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
  1997. // We need to use the virtual base offset offset because the virtual base
  1998. // might have a different offset in the most derived class.
  1999. VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
  2000. *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
  2001. NonVirtualOffset = Vptr.OffsetFromNearestVBase;
  2002. } else {
  2003. // We can just use the base offset in the complete class.
  2004. NonVirtualOffset = Vptr.Base.getBaseOffset();
  2005. }
  2006. // Apply the offsets.
  2007. Address VTableField = LoadCXXThisAddress();
  2008. if (!NonVirtualOffset.isZero() || VirtualOffset)
  2009. VTableField = ApplyNonVirtualAndVirtualOffset(
  2010. *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
  2011. Vptr.NearestVBase);
  2012. // Finally, store the address point. Use the same LLVM types as the field to
  2013. // support optimization.
  2014. llvm::Type *VTablePtrTy =
  2015. llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
  2016. ->getPointerTo()
  2017. ->getPointerTo();
  2018. VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
  2019. VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
  2020. llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
  2021. CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAVTablePtrAccessInfo());
  2022. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2023. CGM.getCodeGenOpts().StrictVTablePointers)
  2024. CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
  2025. }
  2026. CodeGenFunction::VPtrsVector
  2027. CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
  2028. CodeGenFunction::VPtrsVector VPtrsResult;
  2029. VisitedVirtualBasesSetTy VBases;
  2030. getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
  2031. /*NearestVBase=*/nullptr,
  2032. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  2033. /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
  2034. VPtrsResult);
  2035. return VPtrsResult;
  2036. }
  2037. void CodeGenFunction::getVTablePointers(BaseSubobject Base,
  2038. const CXXRecordDecl *NearestVBase,
  2039. CharUnits OffsetFromNearestVBase,
  2040. bool BaseIsNonVirtualPrimaryBase,
  2041. const CXXRecordDecl *VTableClass,
  2042. VisitedVirtualBasesSetTy &VBases,
  2043. VPtrsVector &Vptrs) {
  2044. // If this base is a non-virtual primary base the address point has already
  2045. // been set.
  2046. if (!BaseIsNonVirtualPrimaryBase) {
  2047. // Initialize the vtable pointer for this base.
  2048. VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
  2049. Vptrs.push_back(Vptr);
  2050. }
  2051. const CXXRecordDecl *RD = Base.getBase();
  2052. // Traverse bases.
  2053. for (const auto &I : RD->bases()) {
  2054. CXXRecordDecl *BaseDecl
  2055. = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
  2056. // Ignore classes without a vtable.
  2057. if (!BaseDecl->isDynamicClass())
  2058. continue;
  2059. CharUnits BaseOffset;
  2060. CharUnits BaseOffsetFromNearestVBase;
  2061. bool BaseDeclIsNonVirtualPrimaryBase;
  2062. if (I.isVirtual()) {
  2063. // Check if we've visited this virtual base before.
  2064. if (!VBases.insert(BaseDecl).second)
  2065. continue;
  2066. const ASTRecordLayout &Layout =
  2067. getContext().getASTRecordLayout(VTableClass);
  2068. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  2069. BaseOffsetFromNearestVBase = CharUnits::Zero();
  2070. BaseDeclIsNonVirtualPrimaryBase = false;
  2071. } else {
  2072. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  2073. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  2074. BaseOffsetFromNearestVBase =
  2075. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  2076. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  2077. }
  2078. getVTablePointers(
  2079. BaseSubobject(BaseDecl, BaseOffset),
  2080. I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
  2081. BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
  2082. }
  2083. }
  2084. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  2085. // Ignore classes without a vtable.
  2086. if (!RD->isDynamicClass())
  2087. return;
  2088. // Initialize the vtable pointers for this class and all of its bases.
  2089. if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
  2090. for (const VPtr &Vptr : getVTablePointers(RD))
  2091. InitializeVTablePointer(Vptr);
  2092. if (RD->getNumVBases())
  2093. CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
  2094. }
  2095. llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
  2096. llvm::Type *VTableTy,
  2097. const CXXRecordDecl *RD) {
  2098. Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
  2099. llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
  2100. CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAVTablePtrAccessInfo());
  2101. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2102. CGM.getCodeGenOpts().StrictVTablePointers)
  2103. CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
  2104. return VTable;
  2105. }
  2106. // If a class has a single non-virtual base and does not introduce or override
  2107. // virtual member functions or fields, it will have the same layout as its base.
  2108. // This function returns the least derived such class.
  2109. //
  2110. // Casting an instance of a base class to such a derived class is technically
  2111. // undefined behavior, but it is a relatively common hack for introducing member
  2112. // functions on class instances with specific properties (e.g. llvm::Operator)
  2113. // that works under most compilers and should not have security implications, so
  2114. // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
  2115. static const CXXRecordDecl *
  2116. LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
  2117. if (!RD->field_empty())
  2118. return RD;
  2119. if (RD->getNumVBases() != 0)
  2120. return RD;
  2121. if (RD->getNumBases() != 1)
  2122. return RD;
  2123. for (const CXXMethodDecl *MD : RD->methods()) {
  2124. if (MD->isVirtual()) {
  2125. // Virtual member functions are only ok if they are implicit destructors
  2126. // because the implicit destructor will have the same semantics as the
  2127. // base class's destructor if no fields are added.
  2128. if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
  2129. continue;
  2130. return RD;
  2131. }
  2132. }
  2133. return LeastDerivedClassWithSameLayout(
  2134. RD->bases_begin()->getType()->getAsCXXRecordDecl());
  2135. }
  2136. void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  2137. llvm::Value *VTable,
  2138. SourceLocation Loc) {
  2139. if (SanOpts.has(SanitizerKind::CFIVCall))
  2140. EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
  2141. else if (CGM.getCodeGenOpts().WholeProgramVTables &&
  2142. CGM.HasHiddenLTOVisibility(RD)) {
  2143. llvm::Metadata *MD =
  2144. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2145. llvm::Value *TypeId =
  2146. llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
  2147. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2148. llvm::Value *TypeTest =
  2149. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  2150. {CastedVTable, TypeId});
  2151. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
  2152. }
  2153. }
  2154. void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
  2155. llvm::Value *VTable,
  2156. CFITypeCheckKind TCK,
  2157. SourceLocation Loc) {
  2158. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2159. RD = LeastDerivedClassWithSameLayout(RD);
  2160. EmitVTablePtrCheck(RD, VTable, TCK, Loc);
  2161. }
  2162. void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
  2163. llvm::Value *Derived,
  2164. bool MayBeNull,
  2165. CFITypeCheckKind TCK,
  2166. SourceLocation Loc) {
  2167. if (!getLangOpts().CPlusPlus)
  2168. return;
  2169. auto *ClassTy = T->getAs<RecordType>();
  2170. if (!ClassTy)
  2171. return;
  2172. const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
  2173. if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
  2174. return;
  2175. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2176. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  2177. llvm::BasicBlock *ContBlock = nullptr;
  2178. if (MayBeNull) {
  2179. llvm::Value *DerivedNotNull =
  2180. Builder.CreateIsNotNull(Derived, "cast.nonnull");
  2181. llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
  2182. ContBlock = createBasicBlock("cast.cont");
  2183. Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
  2184. EmitBlock(CheckBlock);
  2185. }
  2186. llvm::Value *VTable =
  2187. GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl);
  2188. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  2189. if (MayBeNull) {
  2190. Builder.CreateBr(ContBlock);
  2191. EmitBlock(ContBlock);
  2192. }
  2193. }
  2194. void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
  2195. llvm::Value *VTable,
  2196. CFITypeCheckKind TCK,
  2197. SourceLocation Loc) {
  2198. if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
  2199. !CGM.HasHiddenLTOVisibility(RD))
  2200. return;
  2201. SanitizerMask M;
  2202. llvm::SanitizerStatKind SSK;
  2203. switch (TCK) {
  2204. case CFITCK_VCall:
  2205. M = SanitizerKind::CFIVCall;
  2206. SSK = llvm::SanStat_CFI_VCall;
  2207. break;
  2208. case CFITCK_NVCall:
  2209. M = SanitizerKind::CFINVCall;
  2210. SSK = llvm::SanStat_CFI_NVCall;
  2211. break;
  2212. case CFITCK_DerivedCast:
  2213. M = SanitizerKind::CFIDerivedCast;
  2214. SSK = llvm::SanStat_CFI_DerivedCast;
  2215. break;
  2216. case CFITCK_UnrelatedCast:
  2217. M = SanitizerKind::CFIUnrelatedCast;
  2218. SSK = llvm::SanStat_CFI_UnrelatedCast;
  2219. break;
  2220. case CFITCK_ICall:
  2221. llvm_unreachable("not expecting CFITCK_ICall");
  2222. }
  2223. std::string TypeName = RD->getQualifiedNameAsString();
  2224. if (getContext().getSanitizerBlacklist().isBlacklistedType(M, TypeName))
  2225. return;
  2226. SanitizerScope SanScope(this);
  2227. EmitSanitizerStatReport(SSK);
  2228. llvm::Metadata *MD =
  2229. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2230. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  2231. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2232. llvm::Value *TypeTest = Builder.CreateCall(
  2233. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
  2234. llvm::Constant *StaticData[] = {
  2235. llvm::ConstantInt::get(Int8Ty, TCK),
  2236. EmitCheckSourceLocation(Loc),
  2237. EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
  2238. };
  2239. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  2240. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  2241. EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
  2242. return;
  2243. }
  2244. if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
  2245. EmitTrapCheck(TypeTest);
  2246. return;
  2247. }
  2248. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  2249. CGM.getLLVMContext(),
  2250. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  2251. llvm::Value *ValidVtable = Builder.CreateCall(
  2252. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
  2253. EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
  2254. StaticData, {CastedVTable, ValidVtable});
  2255. }
  2256. bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
  2257. if (!CGM.getCodeGenOpts().WholeProgramVTables ||
  2258. !SanOpts.has(SanitizerKind::CFIVCall) ||
  2259. !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) ||
  2260. !CGM.HasHiddenLTOVisibility(RD))
  2261. return false;
  2262. std::string TypeName = RD->getQualifiedNameAsString();
  2263. return !getContext().getSanitizerBlacklist().isBlacklistedType(
  2264. SanitizerKind::CFIVCall, TypeName);
  2265. }
  2266. llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
  2267. const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) {
  2268. SanitizerScope SanScope(this);
  2269. EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
  2270. llvm::Metadata *MD =
  2271. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2272. llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
  2273. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2274. llvm::Value *CheckedLoad = Builder.CreateCall(
  2275. CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
  2276. {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
  2277. TypeId});
  2278. llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
  2279. EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
  2280. SanitizerHandler::CFICheckFail, nullptr, nullptr);
  2281. return Builder.CreateBitCast(
  2282. Builder.CreateExtractValue(CheckedLoad, 0),
  2283. cast<llvm::PointerType>(VTable->getType())->getElementType());
  2284. }
  2285. void CodeGenFunction::EmitForwardingCallToLambda(
  2286. const CXXMethodDecl *callOperator,
  2287. CallArgList &callArgs) {
  2288. // Get the address of the call operator.
  2289. const CGFunctionInfo &calleeFnInfo =
  2290. CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
  2291. llvm::Constant *calleePtr =
  2292. CGM.GetAddrOfFunction(GlobalDecl(callOperator),
  2293. CGM.getTypes().GetFunctionType(calleeFnInfo));
  2294. // Prepare the return slot.
  2295. const FunctionProtoType *FPT =
  2296. callOperator->getType()->castAs<FunctionProtoType>();
  2297. QualType resultType = FPT->getReturnType();
  2298. ReturnValueSlot returnSlot;
  2299. if (!resultType->isVoidType() &&
  2300. calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2301. !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
  2302. returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
  2303. // We don't need to separately arrange the call arguments because
  2304. // the call can't be variadic anyway --- it's impossible to forward
  2305. // variadic arguments.
  2306. // Now emit our call.
  2307. auto callee = CGCallee::forDirect(calleePtr, callOperator);
  2308. RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
  2309. // If necessary, copy the returned value into the slot.
  2310. if (!resultType->isVoidType() && returnSlot.isNull())
  2311. EmitReturnOfRValue(RV, resultType);
  2312. else
  2313. EmitBranchThroughCleanup(ReturnBlock);
  2314. }
  2315. void CodeGenFunction::EmitLambdaBlockInvokeBody() {
  2316. const BlockDecl *BD = BlockInfo->getBlockDecl();
  2317. const VarDecl *variable = BD->capture_begin()->getVariable();
  2318. const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
  2319. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2320. if (CallOp->isVariadic()) {
  2321. // FIXME: Making this work correctly is nasty because it requires either
  2322. // cloning the body of the call operator or making the call operator
  2323. // forward.
  2324. CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
  2325. return;
  2326. }
  2327. // Start building arguments for forwarding call
  2328. CallArgList CallArgs;
  2329. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2330. Address ThisPtr = GetAddrOfBlockDecl(variable, false);
  2331. CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
  2332. // Add the rest of the parameters.
  2333. for (auto param : BD->parameters())
  2334. EmitDelegateCallArg(CallArgs, param, param->getLocStart());
  2335. assert(!Lambda->isGenericLambda() &&
  2336. "generic lambda interconversion to block not implemented");
  2337. EmitForwardingCallToLambda(CallOp, CallArgs);
  2338. }
  2339. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  2340. const CXXRecordDecl *Lambda = MD->getParent();
  2341. // Start building arguments for forwarding call
  2342. CallArgList CallArgs;
  2343. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2344. llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
  2345. CallArgs.add(RValue::get(ThisPtr), ThisType);
  2346. // Add the rest of the parameters.
  2347. for (auto Param : MD->parameters())
  2348. EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
  2349. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2350. // For a generic lambda, find the corresponding call operator specialization
  2351. // to which the call to the static-invoker shall be forwarded.
  2352. if (Lambda->isGenericLambda()) {
  2353. assert(MD->isFunctionTemplateSpecialization());
  2354. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  2355. FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
  2356. void *InsertPos = nullptr;
  2357. FunctionDecl *CorrespondingCallOpSpecialization =
  2358. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  2359. assert(CorrespondingCallOpSpecialization);
  2360. CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  2361. }
  2362. EmitForwardingCallToLambda(CallOp, CallArgs);
  2363. }
  2364. void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
  2365. if (MD->isVariadic()) {
  2366. // FIXME: Making this work correctly is nasty because it requires either
  2367. // cloning the body of the call operator or making the call operator forward.
  2368. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  2369. return;
  2370. }
  2371. EmitLambdaDelegatingInvokeBody(MD);
  2372. }