CGExprAgg.cpp 76 KB

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