CGClass.cpp 93 KB

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