CGExprAgg.cpp 74 KB

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