CGExprAgg.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180
  1. //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Aggregate Expr nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGObjCRuntime.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "ConstantEmitter.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/GlobalVariable.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/Intrinsics.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. //===----------------------------------------------------------------------===//
  31. // Aggregate Expression Emitter
  32. //===----------------------------------------------------------------------===//
  33. namespace {
  34. class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
  35. CodeGenFunction &CGF;
  36. CGBuilderTy &Builder;
  37. AggValueSlot Dest;
  38. bool IsResultUnused;
  39. AggValueSlot EnsureSlot(QualType T) {
  40. if (!Dest.isIgnored()) return Dest;
  41. return CGF.CreateAggTemp(T, "agg.tmp.ensured");
  42. }
  43. void EnsureDest(QualType T) {
  44. if (!Dest.isIgnored()) return;
  45. Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
  46. }
  47. // Calls `Fn` with a valid return value slot, potentially creating a temporary
  48. // to do so. If a temporary is created, an appropriate copy into `Dest` will
  49. // be emitted, as will lifetime markers.
  50. //
  51. // The given function should take a ReturnValueSlot, and return an RValue that
  52. // points to said slot.
  53. void withReturnValueSlot(const Expr *E,
  54. llvm::function_ref<RValue(ReturnValueSlot)> Fn);
  55. public:
  56. AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
  57. : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
  58. IsResultUnused(IsResultUnused) { }
  59. //===--------------------------------------------------------------------===//
  60. // Utilities
  61. //===--------------------------------------------------------------------===//
  62. /// EmitAggLoadOfLValue - Given an expression with aggregate type that
  63. /// represents a value lvalue, this method emits the address of the lvalue,
  64. /// then loads the result into DestPtr.
  65. void EmitAggLoadOfLValue(const Expr *E);
  66. enum ExprValueKind {
  67. EVK_RValue,
  68. EVK_NonRValue
  69. };
  70. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  71. /// SrcIsRValue is true if source comes from an RValue.
  72. void EmitFinalDestCopy(QualType type, const LValue &src,
  73. ExprValueKind SrcValueKind = EVK_NonRValue);
  74. void EmitFinalDestCopy(QualType type, RValue src);
  75. void EmitCopy(QualType type, const AggValueSlot &dest,
  76. const AggValueSlot &src);
  77. void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
  78. void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
  79. QualType ArrayQTy, InitListExpr *E);
  80. AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
  81. if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
  82. return AggValueSlot::NeedsGCBarriers;
  83. return AggValueSlot::DoesNotNeedGCBarriers;
  84. }
  85. bool TypeRequiresGCollection(QualType T);
  86. //===--------------------------------------------------------------------===//
  87. // Visitor Methods
  88. //===--------------------------------------------------------------------===//
  89. void Visit(Expr *E) {
  90. ApplyDebugLocation DL(CGF, E);
  91. StmtVisitor<AggExprEmitter>::Visit(E);
  92. }
  93. void VisitStmt(Stmt *S) {
  94. CGF.ErrorUnsupported(S, "aggregate expression");
  95. }
  96. void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
  97. void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  98. Visit(GE->getResultExpr());
  99. }
  100. void VisitCoawaitExpr(CoawaitExpr *E) {
  101. CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
  102. }
  103. void VisitCoyieldExpr(CoyieldExpr *E) {
  104. CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
  105. }
  106. void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
  107. void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
  108. void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  109. return Visit(E->getReplacement());
  110. }
  111. void VisitConstantExpr(ConstantExpr *E) {
  112. EnsureDest(E->getType());
  113. if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
  114. CGF.EmitAggregateStore(Result, Dest.getAddress(),
  115. E->getType().isVolatileQualified());
  116. return;
  117. }
  118. return Visit(E->getSubExpr());
  119. }
  120. // l-values.
  121. void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
  122. void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
  123. void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
  124. void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
  125. void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
  126. void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  127. EmitAggLoadOfLValue(E);
  128. }
  129. void VisitPredefinedExpr(const PredefinedExpr *E) {
  130. EmitAggLoadOfLValue(E);
  131. }
  132. // Operators.
  133. void VisitCastExpr(CastExpr *E);
  134. void VisitCallExpr(const CallExpr *E);
  135. void VisitStmtExpr(const StmtExpr *E);
  136. void VisitBinaryOperator(const BinaryOperator *BO);
  137. void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
  138. void VisitBinAssign(const BinaryOperator *E);
  139. void VisitBinComma(const BinaryOperator *E);
  140. void VisitBinCmp(const BinaryOperator *E);
  141. void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
  142. Visit(E->getSemanticForm());
  143. }
  144. void VisitObjCMessageExpr(ObjCMessageExpr *E);
  145. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  146. EmitAggLoadOfLValue(E);
  147. }
  148. void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
  149. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
  150. void VisitChooseExpr(const ChooseExpr *CE);
  151. void VisitInitListExpr(InitListExpr *E);
  152. void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
  153. llvm::Value *outerBegin = nullptr);
  154. void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
  155. void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
  156. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  157. CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
  158. Visit(DAE->getExpr());
  159. }
  160. void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  161. CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
  162. Visit(DIE->getExpr());
  163. }
  164. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
  165. void VisitCXXConstructExpr(const CXXConstructExpr *E);
  166. void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
  167. void VisitLambdaExpr(LambdaExpr *E);
  168. void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
  169. void VisitExprWithCleanups(ExprWithCleanups *E);
  170. void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
  171. void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
  172. void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
  173. void VisitOpaqueValueExpr(OpaqueValueExpr *E);
  174. void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  175. if (E->isGLValue()) {
  176. LValue LV = CGF.EmitPseudoObjectLValue(E);
  177. return EmitFinalDestCopy(E->getType(), LV);
  178. }
  179. CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
  180. }
  181. void VisitVAArgExpr(VAArgExpr *E);
  182. void EmitInitializationToLValue(Expr *E, LValue Address);
  183. void EmitNullInitializationToLValue(LValue Address);
  184. // case Expr::ChooseExprClass:
  185. void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
  186. void VisitAtomicExpr(AtomicExpr *E) {
  187. RValue Res = CGF.EmitAtomicExpr(E);
  188. EmitFinalDestCopy(E->getType(), Res);
  189. }
  190. };
  191. } // end anonymous namespace.
  192. //===----------------------------------------------------------------------===//
  193. // Utilities
  194. //===----------------------------------------------------------------------===//
  195. /// EmitAggLoadOfLValue - Given an expression with aggregate type that
  196. /// represents a value lvalue, this method emits the address of the lvalue,
  197. /// then loads the result into DestPtr.
  198. void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
  199. LValue LV = CGF.EmitLValue(E);
  200. // If the type of the l-value is atomic, then do an atomic load.
  201. if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
  202. CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
  203. return;
  204. }
  205. EmitFinalDestCopy(E->getType(), LV);
  206. }
  207. /// True if the given aggregate type requires special GC API calls.
  208. bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
  209. // Only record types have members that might require garbage collection.
  210. const RecordType *RecordTy = T->getAs<RecordType>();
  211. if (!RecordTy) return false;
  212. // Don't mess with non-trivial C++ types.
  213. RecordDecl *Record = RecordTy->getDecl();
  214. if (isa<CXXRecordDecl>(Record) &&
  215. (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
  216. !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
  217. return false;
  218. // Check whether the type has an object member.
  219. return Record->hasObjectMember();
  220. }
  221. void AggExprEmitter::withReturnValueSlot(
  222. const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
  223. QualType RetTy = E->getType();
  224. bool RequiresDestruction =
  225. !Dest.isExternallyDestructed() &&
  226. RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
  227. // If it makes no observable difference, save a memcpy + temporary.
  228. //
  229. // We need to always provide our own temporary if destruction is required.
  230. // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
  231. // its lifetime before we have the chance to emit a proper destructor call.
  232. bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
  233. (RequiresDestruction && !Dest.getAddress().isValid());
  234. Address RetAddr = Address::invalid();
  235. Address RetAllocaAddr = Address::invalid();
  236. EHScopeStack::stable_iterator LifetimeEndBlock;
  237. llvm::Value *LifetimeSizePtr = nullptr;
  238. llvm::IntrinsicInst *LifetimeStartInst = nullptr;
  239. if (!UseTemp) {
  240. RetAddr = Dest.getAddress();
  241. } else {
  242. RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr);
  243. llvm::TypeSize Size =
  244. CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
  245. LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer());
  246. if (LifetimeSizePtr) {
  247. LifetimeStartInst =
  248. cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
  249. assert(LifetimeStartInst->getIntrinsicID() ==
  250. llvm::Intrinsic::lifetime_start &&
  251. "Last insertion wasn't a lifetime.start?");
  252. CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
  253. NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr);
  254. LifetimeEndBlock = CGF.EHStack.stable_begin();
  255. }
  256. }
  257. RValue Src =
  258. EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
  259. Dest.isExternallyDestructed()));
  260. if (!UseTemp)
  261. return;
  262. assert(Dest.isIgnored() || Dest.getPointer() != Src.getAggregatePointer());
  263. EmitFinalDestCopy(E->getType(), Src);
  264. if (!RequiresDestruction && LifetimeStartInst) {
  265. // If there's no dtor to run, the copy was the last use of our temporary.
  266. // Since we're not guaranteed to be in an ExprWithCleanups, clean up
  267. // eagerly.
  268. CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
  269. CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer());
  270. }
  271. }
  272. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  273. void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
  274. assert(src.isAggregate() && "value must be aggregate value!");
  275. LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
  276. EmitFinalDestCopy(type, srcLV, EVK_RValue);
  277. }
  278. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  279. void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src,
  280. ExprValueKind SrcValueKind) {
  281. // If Dest is ignored, then we're evaluating an aggregate expression
  282. // in a context that doesn't care about the result. Note that loads
  283. // from volatile l-values force the existence of a non-ignored
  284. // destination.
  285. if (Dest.isIgnored())
  286. return;
  287. // Copy non-trivial C structs here.
  288. LValue DstLV = CGF.MakeAddrLValue(
  289. Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
  290. if (SrcValueKind == EVK_RValue) {
  291. if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
  292. if (Dest.isPotentiallyAliased())
  293. CGF.callCStructMoveAssignmentOperator(DstLV, src);
  294. else
  295. CGF.callCStructMoveConstructor(DstLV, src);
  296. return;
  297. }
  298. } else {
  299. if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
  300. if (Dest.isPotentiallyAliased())
  301. CGF.callCStructCopyAssignmentOperator(DstLV, src);
  302. else
  303. CGF.callCStructCopyConstructor(DstLV, src);
  304. return;
  305. }
  306. }
  307. AggValueSlot srcAgg = AggValueSlot::forLValue(
  308. src, CGF, AggValueSlot::IsDestructed, needsGC(type),
  309. AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
  310. EmitCopy(type, Dest, srcAgg);
  311. }
  312. /// Perform a copy from the source into the destination.
  313. ///
  314. /// \param type - the type of the aggregate being copied; qualifiers are
  315. /// ignored
  316. void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
  317. const AggValueSlot &src) {
  318. if (dest.requiresGCollection()) {
  319. CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
  320. llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
  321. CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
  322. dest.getAddress(),
  323. src.getAddress(),
  324. size);
  325. return;
  326. }
  327. // If the result of the assignment is used, copy the LHS there also.
  328. // It's volatile if either side is. Use the minimum alignment of
  329. // the two sides.
  330. LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
  331. LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
  332. CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
  333. dest.isVolatile() || src.isVolatile());
  334. }
  335. /// Emit the initializer for a std::initializer_list initialized with a
  336. /// real initializer list.
  337. void
  338. AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
  339. // Emit an array containing the elements. The array is externally destructed
  340. // if the std::initializer_list object is.
  341. ASTContext &Ctx = CGF.getContext();
  342. LValue Array = CGF.EmitLValue(E->getSubExpr());
  343. assert(Array.isSimple() && "initializer_list array not a simple lvalue");
  344. Address ArrayPtr = Array.getAddress(CGF);
  345. const ConstantArrayType *ArrayType =
  346. Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
  347. assert(ArrayType && "std::initializer_list constructed from non-array");
  348. // FIXME: Perform the checks on the field types in SemaInit.
  349. RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
  350. RecordDecl::field_iterator Field = Record->field_begin();
  351. if (Field == Record->field_end()) {
  352. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  353. return;
  354. }
  355. // Start pointer.
  356. if (!Field->getType()->isPointerType() ||
  357. !Ctx.hasSameType(Field->getType()->getPointeeType(),
  358. ArrayType->getElementType())) {
  359. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  360. return;
  361. }
  362. AggValueSlot Dest = EnsureSlot(E->getType());
  363. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  364. LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
  365. llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
  366. llvm::Value *IdxStart[] = { Zero, Zero };
  367. llvm::Value *ArrayStart = Builder.CreateInBoundsGEP(
  368. ArrayPtr.getElementType(), ArrayPtr.getPointer(), IdxStart, "arraystart");
  369. CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
  370. ++Field;
  371. if (Field == Record->field_end()) {
  372. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  373. return;
  374. }
  375. llvm::Value *Size = Builder.getInt(ArrayType->getSize());
  376. LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
  377. if (Field->getType()->isPointerType() &&
  378. Ctx.hasSameType(Field->getType()->getPointeeType(),
  379. ArrayType->getElementType())) {
  380. // End pointer.
  381. llvm::Value *IdxEnd[] = { Zero, Size };
  382. llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(
  383. ArrayPtr.getElementType(), ArrayPtr.getPointer(), IdxEnd, "arrayend");
  384. CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
  385. } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
  386. // Length.
  387. CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
  388. } else {
  389. CGF.ErrorUnsupported(E, "weird std::initializer_list");
  390. return;
  391. }
  392. }
  393. /// Determine if E is a trivial array filler, that is, one that is
  394. /// equivalent to zero-initialization.
  395. static bool isTrivialFiller(Expr *E) {
  396. if (!E)
  397. return true;
  398. if (isa<ImplicitValueInitExpr>(E))
  399. return true;
  400. if (auto *ILE = dyn_cast<InitListExpr>(E)) {
  401. if (ILE->getNumInits())
  402. return false;
  403. return isTrivialFiller(ILE->getArrayFiller());
  404. }
  405. if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
  406. return Cons->getConstructor()->isDefaultConstructor() &&
  407. Cons->getConstructor()->isTrivial();
  408. // FIXME: Are there other cases where we can avoid emitting an initializer?
  409. return false;
  410. }
  411. /// Emit initialization of an array from an initializer list.
  412. void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
  413. QualType ArrayQTy, InitListExpr *E) {
  414. uint64_t NumInitElements = E->getNumInits();
  415. uint64_t NumArrayElements = AType->getNumElements();
  416. assert(NumInitElements <= NumArrayElements);
  417. QualType elementType =
  418. CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
  419. // DestPtr is an array*. Construct an elementType* by drilling
  420. // down a level.
  421. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  422. llvm::Value *indices[] = { zero, zero };
  423. llvm::Value *begin = Builder.CreateInBoundsGEP(
  424. DestPtr.getElementType(), DestPtr.getPointer(), indices,
  425. "arrayinit.begin");
  426. CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  427. CharUnits elementAlign =
  428. DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
  429. llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
  430. // Consider initializing the array by copying from a global. For this to be
  431. // more efficient than per-element initialization, the size of the elements
  432. // with explicit initializers should be large enough.
  433. if (NumInitElements * elementSize.getQuantity() > 16 &&
  434. elementType.isTriviallyCopyableType(CGF.getContext())) {
  435. CodeGen::CodeGenModule &CGM = CGF.CGM;
  436. ConstantEmitter Emitter(CGF);
  437. LangAS AS = ArrayQTy.getAddressSpace();
  438. if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) {
  439. auto GV = new llvm::GlobalVariable(
  440. CGM.getModule(), C->getType(),
  441. CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true),
  442. llvm::GlobalValue::PrivateLinkage, C, "constinit",
  443. /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
  444. CGM.getContext().getTargetAddressSpace(AS));
  445. Emitter.finalize(GV);
  446. CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
  447. GV->setAlignment(Align.getAsAlign());
  448. Address GVAddr(GV, GV->getValueType(), Align);
  449. EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, ArrayQTy));
  450. return;
  451. }
  452. }
  453. // Exception safety requires us to destroy all the
  454. // already-constructed members if an initializer throws.
  455. // For that, we'll need an EH cleanup.
  456. QualType::DestructionKind dtorKind = elementType.isDestructedType();
  457. Address endOfInit = Address::invalid();
  458. EHScopeStack::stable_iterator cleanup;
  459. llvm::Instruction *cleanupDominator = nullptr;
  460. if (CGF.needsEHCleanup(dtorKind)) {
  461. // In principle we could tell the cleanup where we are more
  462. // directly, but the control flow can get so varied here that it
  463. // would actually be quite complex. Therefore we go through an
  464. // alloca.
  465. endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
  466. "arrayinit.endOfInit");
  467. cleanupDominator = Builder.CreateStore(begin, endOfInit);
  468. CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
  469. elementAlign,
  470. CGF.getDestroyer(dtorKind));
  471. cleanup = CGF.EHStack.stable_begin();
  472. // Otherwise, remember that we didn't need a cleanup.
  473. } else {
  474. dtorKind = QualType::DK_none;
  475. }
  476. llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
  477. // The 'current element to initialize'. The invariants on this
  478. // variable are complicated. Essentially, after each iteration of
  479. // the loop, it points to the last initialized element, except
  480. // that it points to the beginning of the array before any
  481. // elements have been initialized.
  482. llvm::Value *element = begin;
  483. // Emit the explicit initializers.
  484. for (uint64_t i = 0; i != NumInitElements; ++i) {
  485. // Advance to the next element.
  486. if (i > 0) {
  487. element = Builder.CreateInBoundsGEP(
  488. llvmElementType, element, one, "arrayinit.element");
  489. // Tell the cleanup that it needs to destroy up to this
  490. // element. TODO: some of these stores can be trivially
  491. // observed to be unnecessary.
  492. if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
  493. }
  494. LValue elementLV = CGF.MakeAddrLValue(
  495. Address(element, llvmElementType, elementAlign), elementType);
  496. EmitInitializationToLValue(E->getInit(i), elementLV);
  497. }
  498. // Check whether there's a non-trivial array-fill expression.
  499. Expr *filler = E->getArrayFiller();
  500. bool hasTrivialFiller = isTrivialFiller(filler);
  501. // Any remaining elements need to be zero-initialized, possibly
  502. // using the filler expression. We can skip this if the we're
  503. // emitting to zeroed memory.
  504. if (NumInitElements != NumArrayElements &&
  505. !(Dest.isZeroed() && hasTrivialFiller &&
  506. CGF.getTypes().isZeroInitializable(elementType))) {
  507. // Use an actual loop. This is basically
  508. // do { *array++ = filler; } while (array != end);
  509. // Advance to the start of the rest of the array.
  510. if (NumInitElements) {
  511. element = Builder.CreateInBoundsGEP(
  512. llvmElementType, element, one, "arrayinit.start");
  513. if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
  514. }
  515. // Compute the end of the array.
  516. llvm::Value *end = Builder.CreateInBoundsGEP(
  517. llvmElementType, begin,
  518. llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");
  519. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  520. llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
  521. // Jump into the body.
  522. CGF.EmitBlock(bodyBB);
  523. llvm::PHINode *currentElement =
  524. Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
  525. currentElement->addIncoming(element, entryBB);
  526. // Emit the actual filler expression.
  527. {
  528. // C++1z [class.temporary]p5:
  529. // when a default constructor is called to initialize an element of
  530. // an array with no corresponding initializer [...] the destruction of
  531. // every temporary created in a default argument is sequenced before
  532. // the construction of the next array element, if any
  533. CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
  534. LValue elementLV = CGF.MakeAddrLValue(
  535. Address(currentElement, llvmElementType, elementAlign), elementType);
  536. if (filler)
  537. EmitInitializationToLValue(filler, elementLV);
  538. else
  539. EmitNullInitializationToLValue(elementLV);
  540. }
  541. // Move on to the next element.
  542. llvm::Value *nextElement = Builder.CreateInBoundsGEP(
  543. llvmElementType, currentElement, one, "arrayinit.next");
  544. // Tell the EH cleanup that we finished with the last element.
  545. if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
  546. // Leave the loop if we're done.
  547. llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
  548. "arrayinit.done");
  549. llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
  550. Builder.CreateCondBr(done, endBB, bodyBB);
  551. currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
  552. CGF.EmitBlock(endBB);
  553. }
  554. // Leave the partial-array cleanup if we entered one.
  555. if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
  556. }
  557. //===----------------------------------------------------------------------===//
  558. // Visitor Methods
  559. //===----------------------------------------------------------------------===//
  560. void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
  561. Visit(E->getSubExpr());
  562. }
  563. void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
  564. // If this is a unique OVE, just visit its source expression.
  565. if (e->isUnique())
  566. Visit(e->getSourceExpr());
  567. else
  568. EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
  569. }
  570. void
  571. AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  572. if (Dest.isPotentiallyAliased() &&
  573. E->getType().isPODType(CGF.getContext())) {
  574. // For a POD type, just emit a load of the lvalue + a copy, because our
  575. // compound literal might alias the destination.
  576. EmitAggLoadOfLValue(E);
  577. return;
  578. }
  579. AggValueSlot Slot = EnsureSlot(E->getType());
  580. // Block-scope compound literals are destroyed at the end of the enclosing
  581. // scope in C.
  582. bool Destruct =
  583. !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();
  584. if (Destruct)
  585. Slot.setExternallyDestructed();
  586. CGF.EmitAggExpr(E->getInitializer(), Slot);
  587. if (Destruct)
  588. if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
  589. CGF.pushLifetimeExtendedDestroy(
  590. CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
  591. CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
  592. }
  593. /// Attempt to look through various unimportant expressions to find a
  594. /// cast of the given kind.
  595. static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
  596. op = op->IgnoreParenNoopCasts(ctx);
  597. if (auto castE = dyn_cast<CastExpr>(op)) {
  598. if (castE->getCastKind() == kind)
  599. return castE->getSubExpr();
  600. }
  601. return nullptr;
  602. }
  603. void AggExprEmitter::VisitCastExpr(CastExpr *E) {
  604. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
  605. CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
  606. switch (E->getCastKind()) {
  607. case CK_Dynamic: {
  608. // FIXME: Can this actually happen? We have no test coverage for it.
  609. assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
  610. LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
  611. CodeGenFunction::TCK_Load);
  612. // FIXME: Do we also need to handle property references here?
  613. if (LV.isSimple())
  614. CGF.EmitDynamicCast(LV.getAddress(CGF), cast<CXXDynamicCastExpr>(E));
  615. else
  616. CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
  617. if (!Dest.isIgnored())
  618. CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
  619. break;
  620. }
  621. case CK_ToUnion: {
  622. // Evaluate even if the destination is ignored.
  623. if (Dest.isIgnored()) {
  624. CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
  625. /*ignoreResult=*/true);
  626. break;
  627. }
  628. // GCC union extension
  629. QualType Ty = E->getSubExpr()->getType();
  630. Address CastPtr =
  631. Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
  632. EmitInitializationToLValue(E->getSubExpr(),
  633. CGF.MakeAddrLValue(CastPtr, Ty));
  634. break;
  635. }
  636. case CK_LValueToRValueBitCast: {
  637. if (Dest.isIgnored()) {
  638. CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
  639. /*ignoreResult=*/true);
  640. break;
  641. }
  642. LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
  643. Address SourceAddress =
  644. Builder.CreateElementBitCast(SourceLV.getAddress(CGF), CGF.Int8Ty);
  645. Address DestAddress =
  646. Builder.CreateElementBitCast(Dest.getAddress(), CGF.Int8Ty);
  647. llvm::Value *SizeVal = llvm::ConstantInt::get(
  648. CGF.SizeTy,
  649. CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());
  650. Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
  651. break;
  652. }
  653. case CK_DerivedToBase:
  654. case CK_BaseToDerived:
  655. case CK_UncheckedDerivedToBase: {
  656. llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
  657. "should have been unpacked before we got here");
  658. }
  659. case CK_NonAtomicToAtomic:
  660. case CK_AtomicToNonAtomic: {
  661. bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
  662. // Determine the atomic and value types.
  663. QualType atomicType = E->getSubExpr()->getType();
  664. QualType valueType = E->getType();
  665. if (isToAtomic) std::swap(atomicType, valueType);
  666. assert(atomicType->isAtomicType());
  667. assert(CGF.getContext().hasSameUnqualifiedType(valueType,
  668. atomicType->castAs<AtomicType>()->getValueType()));
  669. // Just recurse normally if we're ignoring the result or the
  670. // atomic type doesn't change representation.
  671. if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
  672. return Visit(E->getSubExpr());
  673. }
  674. CastKind peepholeTarget =
  675. (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
  676. // These two cases are reverses of each other; try to peephole them.
  677. if (Expr *op =
  678. findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
  679. assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
  680. E->getType()) &&
  681. "peephole significantly changed types?");
  682. return Visit(op);
  683. }
  684. // If we're converting an r-value of non-atomic type to an r-value
  685. // of atomic type, just emit directly into the relevant sub-object.
  686. if (isToAtomic) {
  687. AggValueSlot valueDest = Dest;
  688. if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
  689. // Zero-initialize. (Strictly speaking, we only need to initialize
  690. // the padding at the end, but this is simpler.)
  691. if (!Dest.isZeroed())
  692. CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
  693. // Build a GEP to refer to the subobject.
  694. Address valueAddr =
  695. CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
  696. valueDest = AggValueSlot::forAddr(valueAddr,
  697. valueDest.getQualifiers(),
  698. valueDest.isExternallyDestructed(),
  699. valueDest.requiresGCollection(),
  700. valueDest.isPotentiallyAliased(),
  701. AggValueSlot::DoesNotOverlap,
  702. AggValueSlot::IsZeroed);
  703. }
  704. CGF.EmitAggExpr(E->getSubExpr(), valueDest);
  705. return;
  706. }
  707. // Otherwise, we're converting an atomic type to a non-atomic type.
  708. // Make an atomic temporary, emit into that, and then copy the value out.
  709. AggValueSlot atomicSlot =
  710. CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
  711. CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
  712. Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
  713. RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
  714. return EmitFinalDestCopy(valueType, rvalue);
  715. }
  716. case CK_AddressSpaceConversion:
  717. return Visit(E->getSubExpr());
  718. case CK_LValueToRValue:
  719. // If we're loading from a volatile type, force the destination
  720. // into existence.
  721. if (E->getSubExpr()->getType().isVolatileQualified()) {
  722. bool Destruct =
  723. !Dest.isExternallyDestructed() &&
  724. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
  725. if (Destruct)
  726. Dest.setExternallyDestructed();
  727. EnsureDest(E->getType());
  728. Visit(E->getSubExpr());
  729. if (Destruct)
  730. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
  731. E->getType());
  732. return;
  733. }
  734. LLVM_FALLTHROUGH;
  735. case CK_NoOp:
  736. case CK_UserDefinedConversion:
  737. case CK_ConstructorConversion:
  738. assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
  739. E->getType()) &&
  740. "Implicit cast types must be compatible");
  741. Visit(E->getSubExpr());
  742. break;
  743. case CK_LValueBitCast:
  744. llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
  745. case CK_Dependent:
  746. case CK_BitCast:
  747. case CK_ArrayToPointerDecay:
  748. case CK_FunctionToPointerDecay:
  749. case CK_NullToPointer:
  750. case CK_NullToMemberPointer:
  751. case CK_BaseToDerivedMemberPointer:
  752. case CK_DerivedToBaseMemberPointer:
  753. case CK_MemberPointerToBoolean:
  754. case CK_ReinterpretMemberPointer:
  755. case CK_IntegralToPointer:
  756. case CK_PointerToIntegral:
  757. case CK_PointerToBoolean:
  758. case CK_ToVoid:
  759. case CK_VectorSplat:
  760. case CK_IntegralCast:
  761. case CK_BooleanToSignedIntegral:
  762. case CK_IntegralToBoolean:
  763. case CK_IntegralToFloating:
  764. case CK_FloatingToIntegral:
  765. case CK_FloatingToBoolean:
  766. case CK_FloatingCast:
  767. case CK_CPointerToObjCPointerCast:
  768. case CK_BlockPointerToObjCPointerCast:
  769. case CK_AnyPointerToBlockPointerCast:
  770. case CK_ObjCObjectLValueCast:
  771. case CK_FloatingRealToComplex:
  772. case CK_FloatingComplexToReal:
  773. case CK_FloatingComplexToBoolean:
  774. case CK_FloatingComplexCast:
  775. case CK_FloatingComplexToIntegralComplex:
  776. case CK_IntegralRealToComplex:
  777. case CK_IntegralComplexToReal:
  778. case CK_IntegralComplexToBoolean:
  779. case CK_IntegralComplexCast:
  780. case CK_IntegralComplexToFloatingComplex:
  781. case CK_ARCProduceObject:
  782. case CK_ARCConsumeObject:
  783. case CK_ARCReclaimReturnedObject:
  784. case CK_ARCExtendBlockObject:
  785. case CK_CopyAndAutoreleaseBlockObject:
  786. case CK_BuiltinFnToFnPtr:
  787. case CK_ZeroToOCLOpaqueType:
  788. case CK_MatrixCast:
  789. case CK_IntToOCLSampler:
  790. case CK_FloatingToFixedPoint:
  791. case CK_FixedPointToFloating:
  792. case CK_FixedPointCast:
  793. case CK_FixedPointToBoolean:
  794. case CK_FixedPointToIntegral:
  795. case CK_IntegralToFixedPoint:
  796. llvm_unreachable("cast kind invalid for aggregate types");
  797. }
  798. }
  799. void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
  800. if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
  801. EmitAggLoadOfLValue(E);
  802. return;
  803. }
  804. withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
  805. return CGF.EmitCallExpr(E, Slot);
  806. });
  807. }
  808. void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  809. withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
  810. return CGF.EmitObjCMessageExpr(E, Slot);
  811. });
  812. }
  813. void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
  814. CGF.EmitIgnoredExpr(E->getLHS());
  815. Visit(E->getRHS());
  816. }
  817. void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  818. CodeGenFunction::StmtExprEvaluation eval(CGF);
  819. CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
  820. }
  821. enum CompareKind {
  822. CK_Less,
  823. CK_Greater,
  824. CK_Equal,
  825. };
  826. static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
  827. const BinaryOperator *E, llvm::Value *LHS,
  828. llvm::Value *RHS, CompareKind Kind,
  829. const char *NameSuffix = "") {
  830. QualType ArgTy = E->getLHS()->getType();
  831. if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
  832. ArgTy = CT->getElementType();
  833. if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
  834. assert(Kind == CK_Equal &&
  835. "member pointers may only be compared for equality");
  836. return CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  837. CGF, LHS, RHS, MPT, /*IsInequality*/ false);
  838. }
  839. // Compute the comparison instructions for the specified comparison kind.
  840. struct CmpInstInfo {
  841. const char *Name;
  842. llvm::CmpInst::Predicate FCmp;
  843. llvm::CmpInst::Predicate SCmp;
  844. llvm::CmpInst::Predicate UCmp;
  845. };
  846. CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
  847. using FI = llvm::FCmpInst;
  848. using II = llvm::ICmpInst;
  849. switch (Kind) {
  850. case CK_Less:
  851. return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
  852. case CK_Greater:
  853. return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
  854. case CK_Equal:
  855. return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
  856. }
  857. llvm_unreachable("Unrecognised CompareKind enum");
  858. }();
  859. if (ArgTy->hasFloatingRepresentation())
  860. return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
  861. llvm::Twine(InstInfo.Name) + NameSuffix);
  862. if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
  863. auto Inst =
  864. ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
  865. return Builder.CreateICmp(Inst, LHS, RHS,
  866. llvm::Twine(InstInfo.Name) + NameSuffix);
  867. }
  868. llvm_unreachable("unsupported aggregate binary expression should have "
  869. "already been handled");
  870. }
  871. void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
  872. using llvm::BasicBlock;
  873. using llvm::PHINode;
  874. using llvm::Value;
  875. assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
  876. E->getRHS()->getType()));
  877. const ComparisonCategoryInfo &CmpInfo =
  878. CGF.getContext().CompCategories.getInfoForType(E->getType());
  879. assert(CmpInfo.Record->isTriviallyCopyable() &&
  880. "cannot copy non-trivially copyable aggregate");
  881. QualType ArgTy = E->getLHS()->getType();
  882. if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
  883. !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
  884. !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
  885. return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
  886. }
  887. bool IsComplex = ArgTy->isAnyComplexType();
  888. // Evaluate the operands to the expression and extract their values.
  889. auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
  890. RValue RV = CGF.EmitAnyExpr(E);
  891. if (RV.isScalar())
  892. return {RV.getScalarVal(), nullptr};
  893. if (RV.isAggregate())
  894. return {RV.getAggregatePointer(), nullptr};
  895. assert(RV.isComplex());
  896. return RV.getComplexVal();
  897. };
  898. auto LHSValues = EmitOperand(E->getLHS()),
  899. RHSValues = EmitOperand(E->getRHS());
  900. auto EmitCmp = [&](CompareKind K) {
  901. Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
  902. K, IsComplex ? ".r" : "");
  903. if (!IsComplex)
  904. return Cmp;
  905. assert(K == CompareKind::CK_Equal);
  906. Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
  907. RHSValues.second, K, ".i");
  908. return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
  909. };
  910. auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
  911. return Builder.getInt(VInfo->getIntValue());
  912. };
  913. Value *Select;
  914. if (ArgTy->isNullPtrType()) {
  915. Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
  916. } else if (!CmpInfo.isPartial()) {
  917. Value *SelectOne =
  918. Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
  919. EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
  920. Select = Builder.CreateSelect(EmitCmp(CK_Equal),
  921. EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  922. SelectOne, "sel.eq");
  923. } else {
  924. Value *SelectEq = Builder.CreateSelect(
  925. EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  926. EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
  927. Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
  928. EmitCmpRes(CmpInfo.getGreater()),
  929. SelectEq, "sel.gt");
  930. Select = Builder.CreateSelect(
  931. EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
  932. }
  933. // Create the return value in the destination slot.
  934. EnsureDest(E->getType());
  935. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  936. // Emit the address of the first (and only) field in the comparison category
  937. // type, and initialize it from the constant integer value selected above.
  938. LValue FieldLV = CGF.EmitLValueForFieldInitialization(
  939. DestLV, *CmpInfo.Record->field_begin());
  940. CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
  941. // All done! The result is in the Dest slot.
  942. }
  943. void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
  944. if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
  945. VisitPointerToDataMemberBinaryOperator(E);
  946. else
  947. CGF.ErrorUnsupported(E, "aggregate binary expression");
  948. }
  949. void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
  950. const BinaryOperator *E) {
  951. LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
  952. EmitFinalDestCopy(E->getType(), LV);
  953. }
  954. /// Is the value of the given expression possibly a reference to or
  955. /// into a __block variable?
  956. static bool isBlockVarRef(const Expr *E) {
  957. // Make sure we look through parens.
  958. E = E->IgnoreParens();
  959. // Check for a direct reference to a __block variable.
  960. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  961. const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  962. return (var && var->hasAttr<BlocksAttr>());
  963. }
  964. // More complicated stuff.
  965. // Binary operators.
  966. if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
  967. // For an assignment or pointer-to-member operation, just care
  968. // about the LHS.
  969. if (op->isAssignmentOp() || op->isPtrMemOp())
  970. return isBlockVarRef(op->getLHS());
  971. // For a comma, just care about the RHS.
  972. if (op->getOpcode() == BO_Comma)
  973. return isBlockVarRef(op->getRHS());
  974. // FIXME: pointer arithmetic?
  975. return false;
  976. // Check both sides of a conditional operator.
  977. } else if (const AbstractConditionalOperator *op
  978. = dyn_cast<AbstractConditionalOperator>(E)) {
  979. return isBlockVarRef(op->getTrueExpr())
  980. || isBlockVarRef(op->getFalseExpr());
  981. // OVEs are required to support BinaryConditionalOperators.
  982. } else if (const OpaqueValueExpr *op
  983. = dyn_cast<OpaqueValueExpr>(E)) {
  984. if (const Expr *src = op->getSourceExpr())
  985. return isBlockVarRef(src);
  986. // Casts are necessary to get things like (*(int*)&var) = foo().
  987. // We don't really care about the kind of cast here, except
  988. // we don't want to look through l2r casts, because it's okay
  989. // to get the *value* in a __block variable.
  990. } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
  991. if (cast->getCastKind() == CK_LValueToRValue)
  992. return false;
  993. return isBlockVarRef(cast->getSubExpr());
  994. // Handle unary operators. Again, just aggressively look through
  995. // it, ignoring the operation.
  996. } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
  997. return isBlockVarRef(uop->getSubExpr());
  998. // Look into the base of a field access.
  999. } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  1000. return isBlockVarRef(mem->getBase());
  1001. // Look into the base of a subscript.
  1002. } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
  1003. return isBlockVarRef(sub->getBase());
  1004. }
  1005. return false;
  1006. }
  1007. void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  1008. // For an assignment to work, the value on the right has
  1009. // to be compatible with the value on the left.
  1010. assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
  1011. E->getRHS()->getType())
  1012. && "Invalid assignment");
  1013. // If the LHS might be a __block variable, and the RHS can
  1014. // potentially cause a block copy, we need to evaluate the RHS first
  1015. // so that the assignment goes the right place.
  1016. // This is pretty semantically fragile.
  1017. if (isBlockVarRef(E->getLHS()) &&
  1018. E->getRHS()->HasSideEffects(CGF.getContext())) {
  1019. // Ensure that we have a destination, and evaluate the RHS into that.
  1020. EnsureDest(E->getRHS()->getType());
  1021. Visit(E->getRHS());
  1022. // Now emit the LHS and copy into it.
  1023. LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  1024. // That copy is an atomic copy if the LHS is atomic.
  1025. if (LHS.getType()->isAtomicType() ||
  1026. CGF.LValueIsSuitableForInlineAtomic(LHS)) {
  1027. CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
  1028. return;
  1029. }
  1030. EmitCopy(E->getLHS()->getType(),
  1031. AggValueSlot::forLValue(LHS, CGF, AggValueSlot::IsDestructed,
  1032. needsGC(E->getLHS()->getType()),
  1033. AggValueSlot::IsAliased,
  1034. AggValueSlot::MayOverlap),
  1035. Dest);
  1036. return;
  1037. }
  1038. LValue LHS = CGF.EmitLValue(E->getLHS());
  1039. // If we have an atomic type, evaluate into the destination and then
  1040. // do an atomic copy.
  1041. if (LHS.getType()->isAtomicType() ||
  1042. CGF.LValueIsSuitableForInlineAtomic(LHS)) {
  1043. EnsureDest(E->getRHS()->getType());
  1044. Visit(E->getRHS());
  1045. CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
  1046. return;
  1047. }
  1048. // Codegen the RHS so that it stores directly into the LHS.
  1049. AggValueSlot LHSSlot = AggValueSlot::forLValue(
  1050. LHS, CGF, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
  1051. AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
  1052. // A non-volatile aggregate destination might have volatile member.
  1053. if (!LHSSlot.isVolatile() &&
  1054. CGF.hasVolatileMember(E->getLHS()->getType()))
  1055. LHSSlot.setVolatile(true);
  1056. CGF.EmitAggExpr(E->getRHS(), LHSSlot);
  1057. // Copy into the destination if the assignment isn't ignored.
  1058. EmitFinalDestCopy(E->getType(), LHS);
  1059. if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
  1060. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  1061. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
  1062. E->getType());
  1063. }
  1064. void AggExprEmitter::
  1065. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  1066. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  1067. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  1068. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  1069. // Bind the common expression if necessary.
  1070. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  1071. CodeGenFunction::ConditionalEvaluation eval(CGF);
  1072. CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
  1073. CGF.getProfileCount(E));
  1074. // Save whether the destination's lifetime is externally managed.
  1075. bool isExternallyDestructed = Dest.isExternallyDestructed();
  1076. bool destructNonTrivialCStruct =
  1077. !isExternallyDestructed &&
  1078. E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
  1079. isExternallyDestructed |= destructNonTrivialCStruct;
  1080. Dest.setExternallyDestructed(isExternallyDestructed);
  1081. eval.begin(CGF);
  1082. CGF.EmitBlock(LHSBlock);
  1083. CGF.incrementProfileCounter(E);
  1084. Visit(E->getTrueExpr());
  1085. eval.end(CGF);
  1086. assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
  1087. CGF.Builder.CreateBr(ContBlock);
  1088. // If the result of an agg expression is unused, then the emission
  1089. // of the LHS might need to create a destination slot. That's fine
  1090. // with us, and we can safely emit the RHS into the same slot, but
  1091. // we shouldn't claim that it's already being destructed.
  1092. Dest.setExternallyDestructed(isExternallyDestructed);
  1093. eval.begin(CGF);
  1094. CGF.EmitBlock(RHSBlock);
  1095. Visit(E->getFalseExpr());
  1096. eval.end(CGF);
  1097. if (destructNonTrivialCStruct)
  1098. CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
  1099. E->getType());
  1100. CGF.EmitBlock(ContBlock);
  1101. }
  1102. void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
  1103. Visit(CE->getChosenSubExpr());
  1104. }
  1105. void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  1106. Address ArgValue = Address::invalid();
  1107. Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
  1108. // If EmitVAArg fails, emit an error.
  1109. if (!ArgPtr.isValid()) {
  1110. CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
  1111. return;
  1112. }
  1113. EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
  1114. }
  1115. void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1116. // Ensure that we have a slot, but if we already do, remember
  1117. // whether it was externally destructed.
  1118. bool wasExternallyDestructed = Dest.isExternallyDestructed();
  1119. EnsureDest(E->getType());
  1120. // We're going to push a destructor if there isn't already one.
  1121. Dest.setExternallyDestructed();
  1122. Visit(E->getSubExpr());
  1123. // Push that destructor we promised.
  1124. if (!wasExternallyDestructed)
  1125. CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
  1126. }
  1127. void
  1128. AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  1129. AggValueSlot Slot = EnsureSlot(E->getType());
  1130. CGF.EmitCXXConstructExpr(E, Slot);
  1131. }
  1132. void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
  1133. const CXXInheritedCtorInitExpr *E) {
  1134. AggValueSlot Slot = EnsureSlot(E->getType());
  1135. CGF.EmitInheritedCXXConstructorCall(
  1136. E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
  1137. E->inheritedFromVBase(), E);
  1138. }
  1139. void
  1140. AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
  1141. AggValueSlot Slot = EnsureSlot(E->getType());
  1142. LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
  1143. // We'll need to enter cleanup scopes in case any of the element
  1144. // initializers throws an exception.
  1145. SmallVector<EHScopeStack::stable_iterator, 16> Cleanups;
  1146. llvm::Instruction *CleanupDominator = nullptr;
  1147. CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
  1148. for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
  1149. e = E->capture_init_end();
  1150. i != e; ++i, ++CurField) {
  1151. // Emit initialization
  1152. LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
  1153. if (CurField->hasCapturedVLAType()) {
  1154. CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
  1155. continue;
  1156. }
  1157. EmitInitializationToLValue(*i, LV);
  1158. // Push a destructor if necessary.
  1159. if (QualType::DestructionKind DtorKind =
  1160. CurField->getType().isDestructedType()) {
  1161. assert(LV.isSimple());
  1162. if (CGF.needsEHCleanup(DtorKind)) {
  1163. if (!CleanupDominator)
  1164. CleanupDominator = CGF.Builder.CreateAlignedLoad(
  1165. CGF.Int8Ty,
  1166. llvm::Constant::getNullValue(CGF.Int8PtrTy),
  1167. CharUnits::One()); // placeholder
  1168. CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), CurField->getType(),
  1169. CGF.getDestroyer(DtorKind), false);
  1170. Cleanups.push_back(CGF.EHStack.stable_begin());
  1171. }
  1172. }
  1173. }
  1174. // Deactivate all the partial cleanups in reverse order, which
  1175. // generally means popping them.
  1176. for (unsigned i = Cleanups.size(); i != 0; --i)
  1177. CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator);
  1178. // Destroy the placeholder if we made one.
  1179. if (CleanupDominator)
  1180. CleanupDominator->eraseFromParent();
  1181. }
  1182. void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  1183. CodeGenFunction::RunCleanupsScope cleanups(CGF);
  1184. Visit(E->getSubExpr());
  1185. }
  1186. void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
  1187. QualType T = E->getType();
  1188. AggValueSlot Slot = EnsureSlot(T);
  1189. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
  1190. }
  1191. void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
  1192. QualType T = E->getType();
  1193. AggValueSlot Slot = EnsureSlot(T);
  1194. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
  1195. }
  1196. /// Determine whether the given cast kind is known to always convert values
  1197. /// with all zero bits in their value representation to values with all zero
  1198. /// bits in their value representation.
  1199. static bool castPreservesZero(const CastExpr *CE) {
  1200. switch (CE->getCastKind()) {
  1201. // No-ops.
  1202. case CK_NoOp:
  1203. case CK_UserDefinedConversion:
  1204. case CK_ConstructorConversion:
  1205. case CK_BitCast:
  1206. case CK_ToUnion:
  1207. case CK_ToVoid:
  1208. // Conversions between (possibly-complex) integral, (possibly-complex)
  1209. // floating-point, and bool.
  1210. case CK_BooleanToSignedIntegral:
  1211. case CK_FloatingCast:
  1212. case CK_FloatingComplexCast:
  1213. case CK_FloatingComplexToBoolean:
  1214. case CK_FloatingComplexToIntegralComplex:
  1215. case CK_FloatingComplexToReal:
  1216. case CK_FloatingRealToComplex:
  1217. case CK_FloatingToBoolean:
  1218. case CK_FloatingToIntegral:
  1219. case CK_IntegralCast:
  1220. case CK_IntegralComplexCast:
  1221. case CK_IntegralComplexToBoolean:
  1222. case CK_IntegralComplexToFloatingComplex:
  1223. case CK_IntegralComplexToReal:
  1224. case CK_IntegralRealToComplex:
  1225. case CK_IntegralToBoolean:
  1226. case CK_IntegralToFloating:
  1227. // Reinterpreting integers as pointers and vice versa.
  1228. case CK_IntegralToPointer:
  1229. case CK_PointerToIntegral:
  1230. // Language extensions.
  1231. case CK_VectorSplat:
  1232. case CK_MatrixCast:
  1233. case CK_NonAtomicToAtomic:
  1234. case CK_AtomicToNonAtomic:
  1235. return true;
  1236. case CK_BaseToDerivedMemberPointer:
  1237. case CK_DerivedToBaseMemberPointer:
  1238. case CK_MemberPointerToBoolean:
  1239. case CK_NullToMemberPointer:
  1240. case CK_ReinterpretMemberPointer:
  1241. // FIXME: ABI-dependent.
  1242. return false;
  1243. case CK_AnyPointerToBlockPointerCast:
  1244. case CK_BlockPointerToObjCPointerCast:
  1245. case CK_CPointerToObjCPointerCast:
  1246. case CK_ObjCObjectLValueCast:
  1247. case CK_IntToOCLSampler:
  1248. case CK_ZeroToOCLOpaqueType:
  1249. // FIXME: Check these.
  1250. return false;
  1251. case CK_FixedPointCast:
  1252. case CK_FixedPointToBoolean:
  1253. case CK_FixedPointToFloating:
  1254. case CK_FixedPointToIntegral:
  1255. case CK_FloatingToFixedPoint:
  1256. case CK_IntegralToFixedPoint:
  1257. // FIXME: Do all fixed-point types represent zero as all 0 bits?
  1258. return false;
  1259. case CK_AddressSpaceConversion:
  1260. case CK_BaseToDerived:
  1261. case CK_DerivedToBase:
  1262. case CK_Dynamic:
  1263. case CK_NullToPointer:
  1264. case CK_PointerToBoolean:
  1265. // FIXME: Preserves zeroes only if zero pointers and null pointers have the
  1266. // same representation in all involved address spaces.
  1267. return false;
  1268. case CK_ARCConsumeObject:
  1269. case CK_ARCExtendBlockObject:
  1270. case CK_ARCProduceObject:
  1271. case CK_ARCReclaimReturnedObject:
  1272. case CK_CopyAndAutoreleaseBlockObject:
  1273. case CK_ArrayToPointerDecay:
  1274. case CK_FunctionToPointerDecay:
  1275. case CK_BuiltinFnToFnPtr:
  1276. case CK_Dependent:
  1277. case CK_LValueBitCast:
  1278. case CK_LValueToRValue:
  1279. case CK_LValueToRValueBitCast:
  1280. case CK_UncheckedDerivedToBase:
  1281. return false;
  1282. }
  1283. llvm_unreachable("Unhandled clang::CastKind enum");
  1284. }
  1285. /// isSimpleZero - If emitting this value will obviously just cause a store of
  1286. /// zero to memory, return true. This can return false if uncertain, so it just
  1287. /// handles simple cases.
  1288. static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
  1289. E = E->IgnoreParens();
  1290. while (auto *CE = dyn_cast<CastExpr>(E)) {
  1291. if (!castPreservesZero(CE))
  1292. break;
  1293. E = CE->getSubExpr()->IgnoreParens();
  1294. }
  1295. // 0
  1296. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
  1297. return IL->getValue() == 0;
  1298. // +0.0
  1299. if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
  1300. return FL->getValue().isPosZero();
  1301. // int()
  1302. if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
  1303. CGF.getTypes().isZeroInitializable(E->getType()))
  1304. return true;
  1305. // (int*)0 - Null pointer expressions.
  1306. if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
  1307. return ICE->getCastKind() == CK_NullToPointer &&
  1308. CGF.getTypes().isPointerZeroInitializable(E->getType()) &&
  1309. !E->HasSideEffects(CGF.getContext());
  1310. // '\0'
  1311. if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
  1312. return CL->getValue() == 0;
  1313. // Otherwise, hard case: conservatively return false.
  1314. return false;
  1315. }
  1316. void
  1317. AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
  1318. QualType type = LV.getType();
  1319. // FIXME: Ignore result?
  1320. // FIXME: Are initializers affected by volatile?
  1321. if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
  1322. // Storing "i32 0" to a zero'd memory location is a noop.
  1323. return;
  1324. } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
  1325. return EmitNullInitializationToLValue(LV);
  1326. } else if (isa<NoInitExpr>(E)) {
  1327. // Do nothing.
  1328. return;
  1329. } else if (type->isReferenceType()) {
  1330. RValue RV = CGF.EmitReferenceBindingToExpr(E);
  1331. return CGF.EmitStoreThroughLValue(RV, LV);
  1332. }
  1333. switch (CGF.getEvaluationKind(type)) {
  1334. case TEK_Complex:
  1335. CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
  1336. return;
  1337. case TEK_Aggregate:
  1338. CGF.EmitAggExpr(
  1339. E, AggValueSlot::forLValue(LV, CGF, AggValueSlot::IsDestructed,
  1340. AggValueSlot::DoesNotNeedGCBarriers,
  1341. AggValueSlot::IsNotAliased,
  1342. AggValueSlot::MayOverlap, Dest.isZeroed()));
  1343. return;
  1344. case TEK_Scalar:
  1345. if (LV.isSimple()) {
  1346. CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
  1347. } else {
  1348. CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
  1349. }
  1350. return;
  1351. }
  1352. llvm_unreachable("bad evaluation kind");
  1353. }
  1354. void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
  1355. QualType type = lv.getType();
  1356. // If the destination slot is already zeroed out before the aggregate is
  1357. // copied into it, we don't have to emit any zeros here.
  1358. if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
  1359. return;
  1360. if (CGF.hasScalarEvaluationKind(type)) {
  1361. // For non-aggregates, we can store the appropriate null constant.
  1362. llvm::Value *null = CGF.CGM.EmitNullConstant(type);
  1363. // Note that the following is not equivalent to
  1364. // EmitStoreThroughBitfieldLValue for ARC types.
  1365. if (lv.isBitField()) {
  1366. CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
  1367. } else {
  1368. assert(lv.isSimple());
  1369. CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
  1370. }
  1371. } else {
  1372. // There's a potential optimization opportunity in combining
  1373. // memsets; that would be easy for arrays, but relatively
  1374. // difficult for structures with the current code.
  1375. CGF.EmitNullInitialization(lv.getAddress(CGF), lv.getType());
  1376. }
  1377. }
  1378. void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
  1379. #if 0
  1380. // FIXME: Assess perf here? Figure out what cases are worth optimizing here
  1381. // (Length of globals? Chunks of zeroed-out space?).
  1382. //
  1383. // If we can, prefer a copy from a global; this is a lot less code for long
  1384. // globals, and it's easier for the current optimizers to analyze.
  1385. if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
  1386. llvm::GlobalVariable* GV =
  1387. new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
  1388. llvm::GlobalValue::InternalLinkage, C, "");
  1389. EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
  1390. return;
  1391. }
  1392. #endif
  1393. if (E->hadArrayRangeDesignator())
  1394. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  1395. if (E->isTransparent())
  1396. return Visit(E->getInit(0));
  1397. AggValueSlot Dest = EnsureSlot(E->getType());
  1398. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  1399. // Handle initialization of an array.
  1400. if (E->getType()->isArrayType()) {
  1401. auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
  1402. EmitArrayInit(Dest.getAddress(), AType, E->getType(), E);
  1403. return;
  1404. }
  1405. assert(E->getType()->isRecordType() && "Only support structs/unions here!");
  1406. // Do struct initialization; this code just sets each individual member
  1407. // to the approprate value. This makes bitfield support automatic;
  1408. // the disadvantage is that the generated code is more difficult for
  1409. // the optimizer, especially with bitfields.
  1410. unsigned NumInitElements = E->getNumInits();
  1411. RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
  1412. // We'll need to enter cleanup scopes in case any of the element
  1413. // initializers throws an exception.
  1414. SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
  1415. llvm::Instruction *cleanupDominator = nullptr;
  1416. auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) {
  1417. cleanups.push_back(cleanup);
  1418. if (!cleanupDominator) // create placeholder once needed
  1419. cleanupDominator = CGF.Builder.CreateAlignedLoad(
  1420. CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy),
  1421. CharUnits::One());
  1422. };
  1423. unsigned curInitIndex = 0;
  1424. // Emit initialization of base classes.
  1425. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
  1426. assert(E->getNumInits() >= CXXRD->getNumBases() &&
  1427. "missing initializer for base class");
  1428. for (auto &Base : CXXRD->bases()) {
  1429. assert(!Base.isVirtual() && "should not see vbases here");
  1430. auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
  1431. Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
  1432. Dest.getAddress(), CXXRD, BaseRD,
  1433. /*isBaseVirtual*/ false);
  1434. AggValueSlot AggSlot = AggValueSlot::forAddr(
  1435. V, Qualifiers(),
  1436. AggValueSlot::IsDestructed,
  1437. AggValueSlot::DoesNotNeedGCBarriers,
  1438. AggValueSlot::IsNotAliased,
  1439. CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
  1440. CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
  1441. if (QualType::DestructionKind dtorKind =
  1442. Base.getType().isDestructedType()) {
  1443. CGF.pushDestroy(dtorKind, V, Base.getType());
  1444. addCleanup(CGF.EHStack.stable_begin());
  1445. }
  1446. }
  1447. }
  1448. // Prepare a 'this' for CXXDefaultInitExprs.
  1449. CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
  1450. if (record->isUnion()) {
  1451. // Only initialize one field of a union. The field itself is
  1452. // specified by the initializer list.
  1453. if (!E->getInitializedFieldInUnion()) {
  1454. // Empty union; we have nothing to do.
  1455. #ifndef NDEBUG
  1456. // Make sure that it's really an empty and not a failure of
  1457. // semantic analysis.
  1458. for (const auto *Field : record->fields())
  1459. assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
  1460. #endif
  1461. return;
  1462. }
  1463. // FIXME: volatility
  1464. FieldDecl *Field = E->getInitializedFieldInUnion();
  1465. LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
  1466. if (NumInitElements) {
  1467. // Store the initializer into the field
  1468. EmitInitializationToLValue(E->getInit(0), FieldLoc);
  1469. } else {
  1470. // Default-initialize to null.
  1471. EmitNullInitializationToLValue(FieldLoc);
  1472. }
  1473. return;
  1474. }
  1475. // Here we iterate over the fields; this makes it simpler to both
  1476. // default-initialize fields and skip over unnamed fields.
  1477. for (const auto *field : record->fields()) {
  1478. // We're done once we hit the flexible array member.
  1479. if (field->getType()->isIncompleteArrayType())
  1480. break;
  1481. // Always skip anonymous bitfields.
  1482. if (field->isUnnamedBitfield())
  1483. continue;
  1484. // We're done if we reach the end of the explicit initializers, we
  1485. // have a zeroed object, and the rest of the fields are
  1486. // zero-initializable.
  1487. if (curInitIndex == NumInitElements && Dest.isZeroed() &&
  1488. CGF.getTypes().isZeroInitializable(E->getType()))
  1489. break;
  1490. LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
  1491. // We never generate write-barries for initialized fields.
  1492. LV.setNonGC(true);
  1493. if (curInitIndex < NumInitElements) {
  1494. // Store the initializer into the field.
  1495. EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
  1496. } else {
  1497. // We're out of initializers; default-initialize to null
  1498. EmitNullInitializationToLValue(LV);
  1499. }
  1500. // Push a destructor if necessary.
  1501. // FIXME: if we have an array of structures, all explicitly
  1502. // initialized, we can end up pushing a linear number of cleanups.
  1503. bool pushedCleanup = false;
  1504. if (QualType::DestructionKind dtorKind
  1505. = field->getType().isDestructedType()) {
  1506. assert(LV.isSimple());
  1507. if (CGF.needsEHCleanup(dtorKind)) {
  1508. CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), field->getType(),
  1509. CGF.getDestroyer(dtorKind), false);
  1510. addCleanup(CGF.EHStack.stable_begin());
  1511. pushedCleanup = true;
  1512. }
  1513. }
  1514. // If the GEP didn't get used because of a dead zero init or something
  1515. // else, clean it up for -O0 builds and general tidiness.
  1516. if (!pushedCleanup && LV.isSimple())
  1517. if (llvm::GetElementPtrInst *GEP =
  1518. dyn_cast<llvm::GetElementPtrInst>(LV.getPointer(CGF)))
  1519. if (GEP->use_empty())
  1520. GEP->eraseFromParent();
  1521. }
  1522. // Deactivate all the partial cleanups in reverse order, which
  1523. // generally means popping them.
  1524. assert((cleanupDominator || cleanups.empty()) &&
  1525. "Missing cleanupDominator before deactivating cleanup blocks");
  1526. for (unsigned i = cleanups.size(); i != 0; --i)
  1527. CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
  1528. // Destroy the placeholder if we made one.
  1529. if (cleanupDominator)
  1530. cleanupDominator->eraseFromParent();
  1531. }
  1532. void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
  1533. llvm::Value *outerBegin) {
  1534. // Emit the common subexpression.
  1535. CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
  1536. Address destPtr = EnsureSlot(E->getType()).getAddress();
  1537. uint64_t numElements = E->getArraySize().getZExtValue();
  1538. if (!numElements)
  1539. return;
  1540. // destPtr is an array*. Construct an elementType* by drilling down a level.
  1541. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1542. llvm::Value *indices[] = {zero, zero};
  1543. llvm::Value *begin = Builder.CreateInBoundsGEP(
  1544. destPtr.getElementType(), destPtr.getPointer(), indices,
  1545. "arrayinit.begin");
  1546. // Prepare to special-case multidimensional array initialization: we avoid
  1547. // emitting multiple destructor loops in that case.
  1548. if (!outerBegin)
  1549. outerBegin = begin;
  1550. ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
  1551. QualType elementType =
  1552. CGF.getContext().getAsArrayType(E->getType())->getElementType();
  1553. CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  1554. CharUnits elementAlign =
  1555. destPtr.getAlignment().alignmentOfArrayElement(elementSize);
  1556. llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
  1557. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1558. llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
  1559. // Jump into the body.
  1560. CGF.EmitBlock(bodyBB);
  1561. llvm::PHINode *index =
  1562. Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
  1563. index->addIncoming(zero, entryBB);
  1564. llvm::Value *element =
  1565. Builder.CreateInBoundsGEP(llvmElementType, begin, index);
  1566. // Prepare for a cleanup.
  1567. QualType::DestructionKind dtorKind = elementType.isDestructedType();
  1568. EHScopeStack::stable_iterator cleanup;
  1569. if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
  1570. if (outerBegin->getType() != element->getType())
  1571. outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
  1572. CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
  1573. elementAlign,
  1574. CGF.getDestroyer(dtorKind));
  1575. cleanup = CGF.EHStack.stable_begin();
  1576. } else {
  1577. dtorKind = QualType::DK_none;
  1578. }
  1579. // Emit the actual filler expression.
  1580. {
  1581. // Temporaries created in an array initialization loop are destroyed
  1582. // at the end of each iteration.
  1583. CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
  1584. CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
  1585. LValue elementLV = CGF.MakeAddrLValue(
  1586. Address(element, llvmElementType, elementAlign), elementType);
  1587. if (InnerLoop) {
  1588. // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
  1589. auto elementSlot = AggValueSlot::forLValue(
  1590. elementLV, CGF, AggValueSlot::IsDestructed,
  1591. AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
  1592. AggValueSlot::DoesNotOverlap);
  1593. AggExprEmitter(CGF, elementSlot, false)
  1594. .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
  1595. } else
  1596. EmitInitializationToLValue(E->getSubExpr(), elementLV);
  1597. }
  1598. // Move on to the next element.
  1599. llvm::Value *nextIndex = Builder.CreateNUWAdd(
  1600. index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
  1601. index->addIncoming(nextIndex, Builder.GetInsertBlock());
  1602. // Leave the loop if we're done.
  1603. llvm::Value *done = Builder.CreateICmpEQ(
  1604. nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
  1605. "arrayinit.done");
  1606. llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
  1607. Builder.CreateCondBr(done, endBB, bodyBB);
  1608. CGF.EmitBlock(endBB);
  1609. // Leave the partial-array cleanup if we entered one.
  1610. if (dtorKind)
  1611. CGF.DeactivateCleanupBlock(cleanup, index);
  1612. }
  1613. void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
  1614. AggValueSlot Dest = EnsureSlot(E->getType());
  1615. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  1616. EmitInitializationToLValue(E->getBase(), DestLV);
  1617. VisitInitListExpr(E->getUpdater());
  1618. }
  1619. //===----------------------------------------------------------------------===//
  1620. // Entry Points into this File
  1621. //===----------------------------------------------------------------------===//
  1622. /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
  1623. /// non-zero bytes that will be stored when outputting the initializer for the
  1624. /// specified initializer expression.
  1625. static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
  1626. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  1627. E = MTE->getSubExpr();
  1628. E = E->IgnoreParenNoopCasts(CGF.getContext());
  1629. // 0 and 0.0 won't require any non-zero stores!
  1630. if (isSimpleZero(E, CGF)) return CharUnits::Zero();
  1631. // If this is an initlist expr, sum up the size of sizes of the (present)
  1632. // elements. If this is something weird, assume the whole thing is non-zero.
  1633. const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  1634. while (ILE && ILE->isTransparent())
  1635. ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
  1636. if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
  1637. return CGF.getContext().getTypeSizeInChars(E->getType());
  1638. // InitListExprs for structs have to be handled carefully. If there are
  1639. // reference members, we need to consider the size of the reference, not the
  1640. // referencee. InitListExprs for unions and arrays can't have references.
  1641. if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
  1642. if (!RT->isUnionType()) {
  1643. RecordDecl *SD = RT->getDecl();
  1644. CharUnits NumNonZeroBytes = CharUnits::Zero();
  1645. unsigned ILEElement = 0;
  1646. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
  1647. while (ILEElement != CXXRD->getNumBases())
  1648. NumNonZeroBytes +=
  1649. GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
  1650. for (const auto *Field : SD->fields()) {
  1651. // We're done once we hit the flexible array member or run out of
  1652. // InitListExpr elements.
  1653. if (Field->getType()->isIncompleteArrayType() ||
  1654. ILEElement == ILE->getNumInits())
  1655. break;
  1656. if (Field->isUnnamedBitfield())
  1657. continue;
  1658. const Expr *E = ILE->getInit(ILEElement++);
  1659. // Reference values are always non-null and have the width of a pointer.
  1660. if (Field->getType()->isReferenceType())
  1661. NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
  1662. CGF.getTarget().getPointerWidth(0));
  1663. else
  1664. NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
  1665. }
  1666. return NumNonZeroBytes;
  1667. }
  1668. }
  1669. // FIXME: This overestimates the number of non-zero bytes for bit-fields.
  1670. CharUnits NumNonZeroBytes = CharUnits::Zero();
  1671. for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
  1672. NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
  1673. return NumNonZeroBytes;
  1674. }
  1675. /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
  1676. /// zeros in it, emit a memset and avoid storing the individual zeros.
  1677. ///
  1678. static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
  1679. CodeGenFunction &CGF) {
  1680. // If the slot is already known to be zeroed, nothing to do. Don't mess with
  1681. // volatile stores.
  1682. if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
  1683. return;
  1684. // C++ objects with a user-declared constructor don't need zero'ing.
  1685. if (CGF.getLangOpts().CPlusPlus)
  1686. if (const RecordType *RT = CGF.getContext()
  1687. .getBaseElementType(E->getType())->getAs<RecordType>()) {
  1688. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  1689. if (RD->hasUserDeclaredConstructor())
  1690. return;
  1691. }
  1692. // If the type is 16-bytes or smaller, prefer individual stores over memset.
  1693. CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
  1694. if (Size <= CharUnits::fromQuantity(16))
  1695. return;
  1696. // Check to see if over 3/4 of the initializer are known to be zero. If so,
  1697. // we prefer to emit memset + individual stores for the rest.
  1698. CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
  1699. if (NumNonZeroBytes*4 > Size)
  1700. return;
  1701. // Okay, it seems like a good idea to use an initial memset, emit the call.
  1702. llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
  1703. Address Loc = Slot.getAddress();
  1704. Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
  1705. CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
  1706. // Tell the AggExprEmitter that the slot is known zero.
  1707. Slot.setZeroed();
  1708. }
  1709. /// EmitAggExpr - Emit the computation of the specified expression of aggregate
  1710. /// type. The result is computed into DestPtr. Note that if DestPtr is null,
  1711. /// the value of the aggregate expression is not needed. If VolatileDest is
  1712. /// true, DestPtr cannot be 0.
  1713. void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
  1714. assert(E && hasAggregateEvaluationKind(E->getType()) &&
  1715. "Invalid aggregate expression to emit");
  1716. assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
  1717. "slot has bits but no address");
  1718. // Optimize the slot if possible.
  1719. CheckAggExprForMemSetUse(Slot, E, *this);
  1720. AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
  1721. }
  1722. LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
  1723. assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
  1724. Address Temp = CreateMemTemp(E->getType());
  1725. LValue LV = MakeAddrLValue(Temp, E->getType());
  1726. EmitAggExpr(E, AggValueSlot::forLValue(
  1727. LV, *this, AggValueSlot::IsNotDestructed,
  1728. AggValueSlot::DoesNotNeedGCBarriers,
  1729. AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap));
  1730. return LV;
  1731. }
  1732. AggValueSlot::Overlap_t
  1733. CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {
  1734. if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
  1735. return AggValueSlot::DoesNotOverlap;
  1736. // If the field lies entirely within the enclosing class's nvsize, its tail
  1737. // padding cannot overlap any already-initialized object. (The only subobjects
  1738. // with greater addresses that might already be initialized are vbases.)
  1739. const RecordDecl *ClassRD = FD->getParent();
  1740. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
  1741. if (Layout.getFieldOffset(FD->getFieldIndex()) +
  1742. getContext().getTypeSize(FD->getType()) <=
  1743. (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
  1744. return AggValueSlot::DoesNotOverlap;
  1745. // The tail padding may contain values we need to preserve.
  1746. return AggValueSlot::MayOverlap;
  1747. }
  1748. AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(
  1749. const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
  1750. // If the most-derived object is a field declared with [[no_unique_address]],
  1751. // the tail padding of any virtual base could be reused for other subobjects
  1752. // of that field's class.
  1753. if (IsVirtual)
  1754. return AggValueSlot::MayOverlap;
  1755. // If the base class is laid out entirely within the nvsize of the derived
  1756. // class, its tail padding cannot yet be initialized, so we can issue
  1757. // stores at the full width of the base class.
  1758. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1759. if (Layout.getBaseClassOffset(BaseRD) +
  1760. getContext().getASTRecordLayout(BaseRD).getSize() <=
  1761. Layout.getNonVirtualSize())
  1762. return AggValueSlot::DoesNotOverlap;
  1763. // The tail padding may contain values we need to preserve.
  1764. return AggValueSlot::MayOverlap;
  1765. }
  1766. void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
  1767. AggValueSlot::Overlap_t MayOverlap,
  1768. bool isVolatile) {
  1769. assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
  1770. Address DestPtr = Dest.getAddress(*this);
  1771. Address SrcPtr = Src.getAddress(*this);
  1772. if (getLangOpts().CPlusPlus) {
  1773. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1774. CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
  1775. assert((Record->hasTrivialCopyConstructor() ||
  1776. Record->hasTrivialCopyAssignment() ||
  1777. Record->hasTrivialMoveConstructor() ||
  1778. Record->hasTrivialMoveAssignment() ||
  1779. Record->hasAttr<TrivialABIAttr>() || Record->isUnion()) &&
  1780. "Trying to aggregate-copy a type without a trivial copy/move "
  1781. "constructor or assignment operator");
  1782. // Ignore empty classes in C++.
  1783. if (Record->isEmpty())
  1784. return;
  1785. }
  1786. }
  1787. if (getLangOpts().CUDAIsDevice) {
  1788. if (Ty->isCUDADeviceBuiltinSurfaceType()) {
  1789. if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
  1790. Src))
  1791. return;
  1792. } else if (Ty->isCUDADeviceBuiltinTextureType()) {
  1793. if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
  1794. Src))
  1795. return;
  1796. }
  1797. }
  1798. // Aggregate assignment turns into llvm.memcpy. This is almost valid per
  1799. // C99 6.5.16.1p3, which states "If the value being stored in an object is
  1800. // read from another object that overlaps in anyway the storage of the first
  1801. // object, then the overlap shall be exact and the two objects shall have
  1802. // qualified or unqualified versions of a compatible type."
  1803. //
  1804. // memcpy is not defined if the source and destination pointers are exactly
  1805. // equal, but other compilers do this optimization, and almost every memcpy
  1806. // implementation handles this case safely. If there is a libc that does not
  1807. // safely handle this, we can add a target hook.
  1808. // Get data size info for this aggregate. Don't copy the tail padding if this
  1809. // might be a potentially-overlapping subobject, since the tail padding might
  1810. // be occupied by a different object. Otherwise, copying it is fine.
  1811. TypeInfoChars TypeInfo;
  1812. if (MayOverlap)
  1813. TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
  1814. else
  1815. TypeInfo = getContext().getTypeInfoInChars(Ty);
  1816. llvm::Value *SizeVal = nullptr;
  1817. if (TypeInfo.Width.isZero()) {
  1818. // But note that getTypeInfo returns 0 for a VLA.
  1819. if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
  1820. getContext().getAsArrayType(Ty))) {
  1821. QualType BaseEltTy;
  1822. SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
  1823. TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
  1824. assert(!TypeInfo.Width.isZero());
  1825. SizeVal = Builder.CreateNUWMul(
  1826. SizeVal,
  1827. llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));
  1828. }
  1829. }
  1830. if (!SizeVal) {
  1831. SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());
  1832. }
  1833. // FIXME: If we have a volatile struct, the optimizer can remove what might
  1834. // appear to be `extra' memory ops:
  1835. //
  1836. // volatile struct { int i; } a, b;
  1837. //
  1838. // int main() {
  1839. // a = b;
  1840. // a = b;
  1841. // }
  1842. //
  1843. // we need to use a different call here. We use isVolatile to indicate when
  1844. // either the source or the destination is volatile.
  1845. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1846. SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
  1847. // Don't do any of the memmove_collectable tests if GC isn't set.
  1848. if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
  1849. // fall through
  1850. } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1851. RecordDecl *Record = RecordTy->getDecl();
  1852. if (Record->hasObjectMember()) {
  1853. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1854. SizeVal);
  1855. return;
  1856. }
  1857. } else if (Ty->isArrayType()) {
  1858. QualType BaseType = getContext().getBaseElementType(Ty);
  1859. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  1860. if (RecordTy->getDecl()->hasObjectMember()) {
  1861. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1862. SizeVal);
  1863. return;
  1864. }
  1865. }
  1866. }
  1867. auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
  1868. // Determine the metadata to describe the position of any padding in this
  1869. // memcpy, as well as the TBAA tags for the members of the struct, in case
  1870. // the optimizer wishes to expand it in to scalar memory operations.
  1871. if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
  1872. Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
  1873. if (CGM.getCodeGenOpts().NewStructPathTBAA) {
  1874. TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
  1875. Dest.getTBAAInfo(), Src.getTBAAInfo());
  1876. CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
  1877. }
  1878. }