CGClass.cpp 99 KB

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