CGClass.cpp 112 KB

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