CGExprAgg.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023
  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.getAsAlign());
  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_LValueToRValueBitCast: {
  616. if (Dest.isIgnored()) {
  617. CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
  618. /*ignoreResult=*/true);
  619. break;
  620. }
  621. LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
  622. Address SourceAddress =
  623. Builder.CreateElementBitCast(SourceLV.getAddress(), CGF.Int8Ty);
  624. Address DestAddress =
  625. Builder.CreateElementBitCast(Dest.getAddress(), CGF.Int8Ty);
  626. llvm::Value *SizeVal = llvm::ConstantInt::get(
  627. CGF.SizeTy,
  628. CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());
  629. Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
  630. break;
  631. }
  632. case CK_DerivedToBase:
  633. case CK_BaseToDerived:
  634. case CK_UncheckedDerivedToBase: {
  635. llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
  636. "should have been unpacked before we got here");
  637. }
  638. case CK_NonAtomicToAtomic:
  639. case CK_AtomicToNonAtomic: {
  640. bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
  641. // Determine the atomic and value types.
  642. QualType atomicType = E->getSubExpr()->getType();
  643. QualType valueType = E->getType();
  644. if (isToAtomic) std::swap(atomicType, valueType);
  645. assert(atomicType->isAtomicType());
  646. assert(CGF.getContext().hasSameUnqualifiedType(valueType,
  647. atomicType->castAs<AtomicType>()->getValueType()));
  648. // Just recurse normally if we're ignoring the result or the
  649. // atomic type doesn't change representation.
  650. if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
  651. return Visit(E->getSubExpr());
  652. }
  653. CastKind peepholeTarget =
  654. (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
  655. // These two cases are reverses of each other; try to peephole them.
  656. if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
  657. assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
  658. E->getType()) &&
  659. "peephole significantly changed types?");
  660. return Visit(op);
  661. }
  662. // If we're converting an r-value of non-atomic type to an r-value
  663. // of atomic type, just emit directly into the relevant sub-object.
  664. if (isToAtomic) {
  665. AggValueSlot valueDest = Dest;
  666. if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
  667. // Zero-initialize. (Strictly speaking, we only need to initialize
  668. // the padding at the end, but this is simpler.)
  669. if (!Dest.isZeroed())
  670. CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
  671. // Build a GEP to refer to the subobject.
  672. Address valueAddr =
  673. CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
  674. valueDest = AggValueSlot::forAddr(valueAddr,
  675. valueDest.getQualifiers(),
  676. valueDest.isExternallyDestructed(),
  677. valueDest.requiresGCollection(),
  678. valueDest.isPotentiallyAliased(),
  679. AggValueSlot::DoesNotOverlap,
  680. AggValueSlot::IsZeroed);
  681. }
  682. CGF.EmitAggExpr(E->getSubExpr(), valueDest);
  683. return;
  684. }
  685. // Otherwise, we're converting an atomic type to a non-atomic type.
  686. // Make an atomic temporary, emit into that, and then copy the value out.
  687. AggValueSlot atomicSlot =
  688. CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
  689. CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
  690. Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
  691. RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
  692. return EmitFinalDestCopy(valueType, rvalue);
  693. }
  694. case CK_AddressSpaceConversion:
  695. return Visit(E->getSubExpr());
  696. case CK_LValueToRValue:
  697. // If we're loading from a volatile type, force the destination
  698. // into existence.
  699. if (E->getSubExpr()->getType().isVolatileQualified()) {
  700. EnsureDest(E->getType());
  701. return Visit(E->getSubExpr());
  702. }
  703. LLVM_FALLTHROUGH;
  704. case CK_NoOp:
  705. case CK_UserDefinedConversion:
  706. case CK_ConstructorConversion:
  707. assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
  708. E->getType()) &&
  709. "Implicit cast types must be compatible");
  710. Visit(E->getSubExpr());
  711. break;
  712. case CK_LValueBitCast:
  713. llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
  714. case CK_Dependent:
  715. case CK_BitCast:
  716. case CK_ArrayToPointerDecay:
  717. case CK_FunctionToPointerDecay:
  718. case CK_NullToPointer:
  719. case CK_NullToMemberPointer:
  720. case CK_BaseToDerivedMemberPointer:
  721. case CK_DerivedToBaseMemberPointer:
  722. case CK_MemberPointerToBoolean:
  723. case CK_ReinterpretMemberPointer:
  724. case CK_IntegralToPointer:
  725. case CK_PointerToIntegral:
  726. case CK_PointerToBoolean:
  727. case CK_ToVoid:
  728. case CK_VectorSplat:
  729. case CK_IntegralCast:
  730. case CK_BooleanToSignedIntegral:
  731. case CK_IntegralToBoolean:
  732. case CK_IntegralToFloating:
  733. case CK_FloatingToIntegral:
  734. case CK_FloatingToBoolean:
  735. case CK_FloatingCast:
  736. case CK_CPointerToObjCPointerCast:
  737. case CK_BlockPointerToObjCPointerCast:
  738. case CK_AnyPointerToBlockPointerCast:
  739. case CK_ObjCObjectLValueCast:
  740. case CK_FloatingRealToComplex:
  741. case CK_FloatingComplexToReal:
  742. case CK_FloatingComplexToBoolean:
  743. case CK_FloatingComplexCast:
  744. case CK_FloatingComplexToIntegralComplex:
  745. case CK_IntegralRealToComplex:
  746. case CK_IntegralComplexToReal:
  747. case CK_IntegralComplexToBoolean:
  748. case CK_IntegralComplexCast:
  749. case CK_IntegralComplexToFloatingComplex:
  750. case CK_ARCProduceObject:
  751. case CK_ARCConsumeObject:
  752. case CK_ARCReclaimReturnedObject:
  753. case CK_ARCExtendBlockObject:
  754. case CK_CopyAndAutoreleaseBlockObject:
  755. case CK_BuiltinFnToFnPtr:
  756. case CK_ZeroToOCLOpaqueType:
  757. case CK_IntToOCLSampler:
  758. case CK_FixedPointCast:
  759. case CK_FixedPointToBoolean:
  760. case CK_FixedPointToIntegral:
  761. case CK_IntegralToFixedPoint:
  762. llvm_unreachable("cast kind invalid for aggregate types");
  763. }
  764. }
  765. void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
  766. if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
  767. EmitAggLoadOfLValue(E);
  768. return;
  769. }
  770. withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
  771. return CGF.EmitCallExpr(E, Slot);
  772. });
  773. }
  774. void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  775. withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
  776. return CGF.EmitObjCMessageExpr(E, Slot);
  777. });
  778. }
  779. void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
  780. CGF.EmitIgnoredExpr(E->getLHS());
  781. Visit(E->getRHS());
  782. }
  783. void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  784. CodeGenFunction::StmtExprEvaluation eval(CGF);
  785. CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
  786. }
  787. enum CompareKind {
  788. CK_Less,
  789. CK_Greater,
  790. CK_Equal,
  791. };
  792. static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
  793. const BinaryOperator *E, llvm::Value *LHS,
  794. llvm::Value *RHS, CompareKind Kind,
  795. const char *NameSuffix = "") {
  796. QualType ArgTy = E->getLHS()->getType();
  797. if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
  798. ArgTy = CT->getElementType();
  799. if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
  800. assert(Kind == CK_Equal &&
  801. "member pointers may only be compared for equality");
  802. return CGF.CGM.getCXXABI().EmitMemberPointerComparison(
  803. CGF, LHS, RHS, MPT, /*IsInequality*/ false);
  804. }
  805. // Compute the comparison instructions for the specified comparison kind.
  806. struct CmpInstInfo {
  807. const char *Name;
  808. llvm::CmpInst::Predicate FCmp;
  809. llvm::CmpInst::Predicate SCmp;
  810. llvm::CmpInst::Predicate UCmp;
  811. };
  812. CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
  813. using FI = llvm::FCmpInst;
  814. using II = llvm::ICmpInst;
  815. switch (Kind) {
  816. case CK_Less:
  817. return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
  818. case CK_Greater:
  819. return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
  820. case CK_Equal:
  821. return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
  822. }
  823. llvm_unreachable("Unrecognised CompareKind enum");
  824. }();
  825. if (ArgTy->hasFloatingRepresentation())
  826. return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
  827. llvm::Twine(InstInfo.Name) + NameSuffix);
  828. if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
  829. auto Inst =
  830. ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
  831. return Builder.CreateICmp(Inst, LHS, RHS,
  832. llvm::Twine(InstInfo.Name) + NameSuffix);
  833. }
  834. llvm_unreachable("unsupported aggregate binary expression should have "
  835. "already been handled");
  836. }
  837. void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
  838. using llvm::BasicBlock;
  839. using llvm::PHINode;
  840. using llvm::Value;
  841. assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
  842. E->getRHS()->getType()));
  843. const ComparisonCategoryInfo &CmpInfo =
  844. CGF.getContext().CompCategories.getInfoForType(E->getType());
  845. assert(CmpInfo.Record->isTriviallyCopyable() &&
  846. "cannot copy non-trivially copyable aggregate");
  847. QualType ArgTy = E->getLHS()->getType();
  848. // TODO: Handle comparing these types.
  849. if (ArgTy->isVectorType())
  850. return CGF.ErrorUnsupported(
  851. E, "aggregate three-way comparison with vector arguments");
  852. if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
  853. !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
  854. !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
  855. return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
  856. }
  857. bool IsComplex = ArgTy->isAnyComplexType();
  858. // Evaluate the operands to the expression and extract their values.
  859. auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
  860. RValue RV = CGF.EmitAnyExpr(E);
  861. if (RV.isScalar())
  862. return {RV.getScalarVal(), nullptr};
  863. if (RV.isAggregate())
  864. return {RV.getAggregatePointer(), nullptr};
  865. assert(RV.isComplex());
  866. return RV.getComplexVal();
  867. };
  868. auto LHSValues = EmitOperand(E->getLHS()),
  869. RHSValues = EmitOperand(E->getRHS());
  870. auto EmitCmp = [&](CompareKind K) {
  871. Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
  872. K, IsComplex ? ".r" : "");
  873. if (!IsComplex)
  874. return Cmp;
  875. assert(K == CompareKind::CK_Equal);
  876. Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
  877. RHSValues.second, K, ".i");
  878. return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
  879. };
  880. auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
  881. return Builder.getInt(VInfo->getIntValue());
  882. };
  883. Value *Select;
  884. if (ArgTy->isNullPtrType()) {
  885. Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
  886. } else if (CmpInfo.isEquality()) {
  887. Select = Builder.CreateSelect(
  888. EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  889. EmitCmpRes(CmpInfo.getNonequalOrNonequiv()), "sel.eq");
  890. } else if (!CmpInfo.isPartial()) {
  891. Value *SelectOne =
  892. Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
  893. EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
  894. Select = Builder.CreateSelect(EmitCmp(CK_Equal),
  895. EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  896. SelectOne, "sel.eq");
  897. } else {
  898. Value *SelectEq = Builder.CreateSelect(
  899. EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
  900. EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
  901. Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
  902. EmitCmpRes(CmpInfo.getGreater()),
  903. SelectEq, "sel.gt");
  904. Select = Builder.CreateSelect(
  905. EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
  906. }
  907. // Create the return value in the destination slot.
  908. EnsureDest(E->getType());
  909. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  910. // Emit the address of the first (and only) field in the comparison category
  911. // type, and initialize it from the constant integer value selected above.
  912. LValue FieldLV = CGF.EmitLValueForFieldInitialization(
  913. DestLV, *CmpInfo.Record->field_begin());
  914. CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
  915. // All done! The result is in the Dest slot.
  916. }
  917. void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
  918. if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
  919. VisitPointerToDataMemberBinaryOperator(E);
  920. else
  921. CGF.ErrorUnsupported(E, "aggregate binary expression");
  922. }
  923. void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
  924. const BinaryOperator *E) {
  925. LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
  926. EmitFinalDestCopy(E->getType(), LV);
  927. }
  928. /// Is the value of the given expression possibly a reference to or
  929. /// into a __block variable?
  930. static bool isBlockVarRef(const Expr *E) {
  931. // Make sure we look through parens.
  932. E = E->IgnoreParens();
  933. // Check for a direct reference to a __block variable.
  934. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  935. const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  936. return (var && var->hasAttr<BlocksAttr>());
  937. }
  938. // More complicated stuff.
  939. // Binary operators.
  940. if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
  941. // For an assignment or pointer-to-member operation, just care
  942. // about the LHS.
  943. if (op->isAssignmentOp() || op->isPtrMemOp())
  944. return isBlockVarRef(op->getLHS());
  945. // For a comma, just care about the RHS.
  946. if (op->getOpcode() == BO_Comma)
  947. return isBlockVarRef(op->getRHS());
  948. // FIXME: pointer arithmetic?
  949. return false;
  950. // Check both sides of a conditional operator.
  951. } else if (const AbstractConditionalOperator *op
  952. = dyn_cast<AbstractConditionalOperator>(E)) {
  953. return isBlockVarRef(op->getTrueExpr())
  954. || isBlockVarRef(op->getFalseExpr());
  955. // OVEs are required to support BinaryConditionalOperators.
  956. } else if (const OpaqueValueExpr *op
  957. = dyn_cast<OpaqueValueExpr>(E)) {
  958. if (const Expr *src = op->getSourceExpr())
  959. return isBlockVarRef(src);
  960. // Casts are necessary to get things like (*(int*)&var) = foo().
  961. // We don't really care about the kind of cast here, except
  962. // we don't want to look through l2r casts, because it's okay
  963. // to get the *value* in a __block variable.
  964. } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
  965. if (cast->getCastKind() == CK_LValueToRValue)
  966. return false;
  967. return isBlockVarRef(cast->getSubExpr());
  968. // Handle unary operators. Again, just aggressively look through
  969. // it, ignoring the operation.
  970. } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
  971. return isBlockVarRef(uop->getSubExpr());
  972. // Look into the base of a field access.
  973. } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  974. return isBlockVarRef(mem->getBase());
  975. // Look into the base of a subscript.
  976. } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
  977. return isBlockVarRef(sub->getBase());
  978. }
  979. return false;
  980. }
  981. void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  982. // For an assignment to work, the value on the right has
  983. // to be compatible with the value on the left.
  984. assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
  985. E->getRHS()->getType())
  986. && "Invalid assignment");
  987. // If the LHS might be a __block variable, and the RHS can
  988. // potentially cause a block copy, we need to evaluate the RHS first
  989. // so that the assignment goes the right place.
  990. // This is pretty semantically fragile.
  991. if (isBlockVarRef(E->getLHS()) &&
  992. E->getRHS()->HasSideEffects(CGF.getContext())) {
  993. // Ensure that we have a destination, and evaluate the RHS into that.
  994. EnsureDest(E->getRHS()->getType());
  995. Visit(E->getRHS());
  996. // Now emit the LHS and copy into it.
  997. LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
  998. // That copy is an atomic copy if the LHS is atomic.
  999. if (LHS.getType()->isAtomicType() ||
  1000. CGF.LValueIsSuitableForInlineAtomic(LHS)) {
  1001. CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
  1002. return;
  1003. }
  1004. EmitCopy(E->getLHS()->getType(),
  1005. AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
  1006. needsGC(E->getLHS()->getType()),
  1007. AggValueSlot::IsAliased,
  1008. AggValueSlot::MayOverlap),
  1009. Dest);
  1010. return;
  1011. }
  1012. LValue LHS = CGF.EmitLValue(E->getLHS());
  1013. // If we have an atomic type, evaluate into the destination and then
  1014. // do an atomic copy.
  1015. if (LHS.getType()->isAtomicType() ||
  1016. CGF.LValueIsSuitableForInlineAtomic(LHS)) {
  1017. EnsureDest(E->getRHS()->getType());
  1018. Visit(E->getRHS());
  1019. CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
  1020. return;
  1021. }
  1022. // Codegen the RHS so that it stores directly into the LHS.
  1023. AggValueSlot LHSSlot =
  1024. AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
  1025. needsGC(E->getLHS()->getType()),
  1026. AggValueSlot::IsAliased,
  1027. AggValueSlot::MayOverlap);
  1028. // A non-volatile aggregate destination might have volatile member.
  1029. if (!LHSSlot.isVolatile() &&
  1030. CGF.hasVolatileMember(E->getLHS()->getType()))
  1031. LHSSlot.setVolatile(true);
  1032. CGF.EmitAggExpr(E->getRHS(), LHSSlot);
  1033. // Copy into the destination if the assignment isn't ignored.
  1034. EmitFinalDestCopy(E->getType(), LHS);
  1035. }
  1036. void AggExprEmitter::
  1037. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  1038. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  1039. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  1040. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  1041. // Bind the common expression if necessary.
  1042. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  1043. CodeGenFunction::ConditionalEvaluation eval(CGF);
  1044. CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
  1045. CGF.getProfileCount(E));
  1046. // Save whether the destination's lifetime is externally managed.
  1047. bool isExternallyDestructed = Dest.isExternallyDestructed();
  1048. eval.begin(CGF);
  1049. CGF.EmitBlock(LHSBlock);
  1050. CGF.incrementProfileCounter(E);
  1051. Visit(E->getTrueExpr());
  1052. eval.end(CGF);
  1053. assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
  1054. CGF.Builder.CreateBr(ContBlock);
  1055. // If the result of an agg expression is unused, then the emission
  1056. // of the LHS might need to create a destination slot. That's fine
  1057. // with us, and we can safely emit the RHS into the same slot, but
  1058. // we shouldn't claim that it's already being destructed.
  1059. Dest.setExternallyDestructed(isExternallyDestructed);
  1060. eval.begin(CGF);
  1061. CGF.EmitBlock(RHSBlock);
  1062. Visit(E->getFalseExpr());
  1063. eval.end(CGF);
  1064. CGF.EmitBlock(ContBlock);
  1065. }
  1066. void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
  1067. Visit(CE->getChosenSubExpr());
  1068. }
  1069. void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  1070. Address ArgValue = Address::invalid();
  1071. Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
  1072. // If EmitVAArg fails, emit an error.
  1073. if (!ArgPtr.isValid()) {
  1074. CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
  1075. return;
  1076. }
  1077. EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
  1078. }
  1079. void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1080. // Ensure that we have a slot, but if we already do, remember
  1081. // whether it was externally destructed.
  1082. bool wasExternallyDestructed = Dest.isExternallyDestructed();
  1083. EnsureDest(E->getType());
  1084. // We're going to push a destructor if there isn't already one.
  1085. Dest.setExternallyDestructed();
  1086. Visit(E->getSubExpr());
  1087. // Push that destructor we promised.
  1088. if (!wasExternallyDestructed)
  1089. CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
  1090. }
  1091. void
  1092. AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  1093. AggValueSlot Slot = EnsureSlot(E->getType());
  1094. CGF.EmitCXXConstructExpr(E, Slot);
  1095. }
  1096. void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
  1097. const CXXInheritedCtorInitExpr *E) {
  1098. AggValueSlot Slot = EnsureSlot(E->getType());
  1099. CGF.EmitInheritedCXXConstructorCall(
  1100. E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
  1101. E->inheritedFromVBase(), E);
  1102. }
  1103. void
  1104. AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
  1105. AggValueSlot Slot = EnsureSlot(E->getType());
  1106. LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
  1107. // We'll need to enter cleanup scopes in case any of the element
  1108. // initializers throws an exception.
  1109. SmallVector<EHScopeStack::stable_iterator, 16> Cleanups;
  1110. llvm::Instruction *CleanupDominator = nullptr;
  1111. CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
  1112. for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
  1113. e = E->capture_init_end();
  1114. i != e; ++i, ++CurField) {
  1115. // Emit initialization
  1116. LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
  1117. if (CurField->hasCapturedVLAType()) {
  1118. CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
  1119. continue;
  1120. }
  1121. EmitInitializationToLValue(*i, LV);
  1122. // Push a destructor if necessary.
  1123. if (QualType::DestructionKind DtorKind =
  1124. CurField->getType().isDestructedType()) {
  1125. assert(LV.isSimple());
  1126. if (CGF.needsEHCleanup(DtorKind)) {
  1127. if (!CleanupDominator)
  1128. CleanupDominator = CGF.Builder.CreateAlignedLoad(
  1129. CGF.Int8Ty,
  1130. llvm::Constant::getNullValue(CGF.Int8PtrTy),
  1131. CharUnits::One()); // placeholder
  1132. CGF.pushDestroy(EHCleanup, LV.getAddress(), CurField->getType(),
  1133. CGF.getDestroyer(DtorKind), false);
  1134. Cleanups.push_back(CGF.EHStack.stable_begin());
  1135. }
  1136. }
  1137. }
  1138. // Deactivate all the partial cleanups in reverse order, which
  1139. // generally means popping them.
  1140. for (unsigned i = Cleanups.size(); i != 0; --i)
  1141. CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator);
  1142. // Destroy the placeholder if we made one.
  1143. if (CleanupDominator)
  1144. CleanupDominator->eraseFromParent();
  1145. }
  1146. void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  1147. CGF.enterFullExpression(E);
  1148. CodeGenFunction::RunCleanupsScope cleanups(CGF);
  1149. Visit(E->getSubExpr());
  1150. }
  1151. void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
  1152. QualType T = E->getType();
  1153. AggValueSlot Slot = EnsureSlot(T);
  1154. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
  1155. }
  1156. void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
  1157. QualType T = E->getType();
  1158. AggValueSlot Slot = EnsureSlot(T);
  1159. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
  1160. }
  1161. /// isSimpleZero - If emitting this value will obviously just cause a store of
  1162. /// zero to memory, return true. This can return false if uncertain, so it just
  1163. /// handles simple cases.
  1164. static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
  1165. E = E->IgnoreParens();
  1166. // 0
  1167. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
  1168. return IL->getValue() == 0;
  1169. // +0.0
  1170. if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
  1171. return FL->getValue().isPosZero();
  1172. // int()
  1173. if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
  1174. CGF.getTypes().isZeroInitializable(E->getType()))
  1175. return true;
  1176. // (int*)0 - Null pointer expressions.
  1177. if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
  1178. return ICE->getCastKind() == CK_NullToPointer &&
  1179. CGF.getTypes().isPointerZeroInitializable(E->getType()) &&
  1180. !E->HasSideEffects(CGF.getContext());
  1181. // '\0'
  1182. if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
  1183. return CL->getValue() == 0;
  1184. // Otherwise, hard case: conservatively return false.
  1185. return false;
  1186. }
  1187. void
  1188. AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
  1189. QualType type = LV.getType();
  1190. // FIXME: Ignore result?
  1191. // FIXME: Are initializers affected by volatile?
  1192. if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
  1193. // Storing "i32 0" to a zero'd memory location is a noop.
  1194. return;
  1195. } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
  1196. return EmitNullInitializationToLValue(LV);
  1197. } else if (isa<NoInitExpr>(E)) {
  1198. // Do nothing.
  1199. return;
  1200. } else if (type->isReferenceType()) {
  1201. RValue RV = CGF.EmitReferenceBindingToExpr(E);
  1202. return CGF.EmitStoreThroughLValue(RV, LV);
  1203. }
  1204. switch (CGF.getEvaluationKind(type)) {
  1205. case TEK_Complex:
  1206. CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
  1207. return;
  1208. case TEK_Aggregate:
  1209. CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
  1210. AggValueSlot::IsDestructed,
  1211. AggValueSlot::DoesNotNeedGCBarriers,
  1212. AggValueSlot::IsNotAliased,
  1213. AggValueSlot::MayOverlap,
  1214. Dest.isZeroed()));
  1215. return;
  1216. case TEK_Scalar:
  1217. if (LV.isSimple()) {
  1218. CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
  1219. } else {
  1220. CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
  1221. }
  1222. return;
  1223. }
  1224. llvm_unreachable("bad evaluation kind");
  1225. }
  1226. void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
  1227. QualType type = lv.getType();
  1228. // If the destination slot is already zeroed out before the aggregate is
  1229. // copied into it, we don't have to emit any zeros here.
  1230. if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
  1231. return;
  1232. if (CGF.hasScalarEvaluationKind(type)) {
  1233. // For non-aggregates, we can store the appropriate null constant.
  1234. llvm::Value *null = CGF.CGM.EmitNullConstant(type);
  1235. // Note that the following is not equivalent to
  1236. // EmitStoreThroughBitfieldLValue for ARC types.
  1237. if (lv.isBitField()) {
  1238. CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
  1239. } else {
  1240. assert(lv.isSimple());
  1241. CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
  1242. }
  1243. } else {
  1244. // There's a potential optimization opportunity in combining
  1245. // memsets; that would be easy for arrays, but relatively
  1246. // difficult for structures with the current code.
  1247. CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
  1248. }
  1249. }
  1250. void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
  1251. #if 0
  1252. // FIXME: Assess perf here? Figure out what cases are worth optimizing here
  1253. // (Length of globals? Chunks of zeroed-out space?).
  1254. //
  1255. // If we can, prefer a copy from a global; this is a lot less code for long
  1256. // globals, and it's easier for the current optimizers to analyze.
  1257. if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
  1258. llvm::GlobalVariable* GV =
  1259. new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
  1260. llvm::GlobalValue::InternalLinkage, C, "");
  1261. EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
  1262. return;
  1263. }
  1264. #endif
  1265. if (E->hadArrayRangeDesignator())
  1266. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  1267. if (E->isTransparent())
  1268. return Visit(E->getInit(0));
  1269. AggValueSlot Dest = EnsureSlot(E->getType());
  1270. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  1271. // Handle initialization of an array.
  1272. if (E->getType()->isArrayType()) {
  1273. auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
  1274. EmitArrayInit(Dest.getAddress(), AType, E->getType(), E);
  1275. return;
  1276. }
  1277. assert(E->getType()->isRecordType() && "Only support structs/unions here!");
  1278. // Do struct initialization; this code just sets each individual member
  1279. // to the approprate value. This makes bitfield support automatic;
  1280. // the disadvantage is that the generated code is more difficult for
  1281. // the optimizer, especially with bitfields.
  1282. unsigned NumInitElements = E->getNumInits();
  1283. RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
  1284. // We'll need to enter cleanup scopes in case any of the element
  1285. // initializers throws an exception.
  1286. SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
  1287. llvm::Instruction *cleanupDominator = nullptr;
  1288. auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) {
  1289. cleanups.push_back(cleanup);
  1290. if (!cleanupDominator) // create placeholder once needed
  1291. cleanupDominator = CGF.Builder.CreateAlignedLoad(
  1292. CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy),
  1293. CharUnits::One());
  1294. };
  1295. unsigned curInitIndex = 0;
  1296. // Emit initialization of base classes.
  1297. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
  1298. assert(E->getNumInits() >= CXXRD->getNumBases() &&
  1299. "missing initializer for base class");
  1300. for (auto &Base : CXXRD->bases()) {
  1301. assert(!Base.isVirtual() && "should not see vbases here");
  1302. auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
  1303. Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
  1304. Dest.getAddress(), CXXRD, BaseRD,
  1305. /*isBaseVirtual*/ false);
  1306. AggValueSlot AggSlot = AggValueSlot::forAddr(
  1307. V, Qualifiers(),
  1308. AggValueSlot::IsDestructed,
  1309. AggValueSlot::DoesNotNeedGCBarriers,
  1310. AggValueSlot::IsNotAliased,
  1311. CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
  1312. CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
  1313. if (QualType::DestructionKind dtorKind =
  1314. Base.getType().isDestructedType()) {
  1315. CGF.pushDestroy(dtorKind, V, Base.getType());
  1316. addCleanup(CGF.EHStack.stable_begin());
  1317. }
  1318. }
  1319. }
  1320. // Prepare a 'this' for CXXDefaultInitExprs.
  1321. CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
  1322. if (record->isUnion()) {
  1323. // Only initialize one field of a union. The field itself is
  1324. // specified by the initializer list.
  1325. if (!E->getInitializedFieldInUnion()) {
  1326. // Empty union; we have nothing to do.
  1327. #ifndef NDEBUG
  1328. // Make sure that it's really an empty and not a failure of
  1329. // semantic analysis.
  1330. for (const auto *Field : record->fields())
  1331. assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
  1332. #endif
  1333. return;
  1334. }
  1335. // FIXME: volatility
  1336. FieldDecl *Field = E->getInitializedFieldInUnion();
  1337. LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
  1338. if (NumInitElements) {
  1339. // Store the initializer into the field
  1340. EmitInitializationToLValue(E->getInit(0), FieldLoc);
  1341. } else {
  1342. // Default-initialize to null.
  1343. EmitNullInitializationToLValue(FieldLoc);
  1344. }
  1345. return;
  1346. }
  1347. // Here we iterate over the fields; this makes it simpler to both
  1348. // default-initialize fields and skip over unnamed fields.
  1349. for (const auto *field : record->fields()) {
  1350. // We're done once we hit the flexible array member.
  1351. if (field->getType()->isIncompleteArrayType())
  1352. break;
  1353. // Always skip anonymous bitfields.
  1354. if (field->isUnnamedBitfield())
  1355. continue;
  1356. // We're done if we reach the end of the explicit initializers, we
  1357. // have a zeroed object, and the rest of the fields are
  1358. // zero-initializable.
  1359. if (curInitIndex == NumInitElements && Dest.isZeroed() &&
  1360. CGF.getTypes().isZeroInitializable(E->getType()))
  1361. break;
  1362. LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
  1363. // We never generate write-barries for initialized fields.
  1364. LV.setNonGC(true);
  1365. if (curInitIndex < NumInitElements) {
  1366. // Store the initializer into the field.
  1367. EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
  1368. } else {
  1369. // We're out of initializers; default-initialize to null
  1370. EmitNullInitializationToLValue(LV);
  1371. }
  1372. // Push a destructor if necessary.
  1373. // FIXME: if we have an array of structures, all explicitly
  1374. // initialized, we can end up pushing a linear number of cleanups.
  1375. bool pushedCleanup = false;
  1376. if (QualType::DestructionKind dtorKind
  1377. = field->getType().isDestructedType()) {
  1378. assert(LV.isSimple());
  1379. if (CGF.needsEHCleanup(dtorKind)) {
  1380. CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
  1381. CGF.getDestroyer(dtorKind), false);
  1382. addCleanup(CGF.EHStack.stable_begin());
  1383. pushedCleanup = true;
  1384. }
  1385. }
  1386. // If the GEP didn't get used because of a dead zero init or something
  1387. // else, clean it up for -O0 builds and general tidiness.
  1388. if (!pushedCleanup && LV.isSimple())
  1389. if (llvm::GetElementPtrInst *GEP =
  1390. dyn_cast<llvm::GetElementPtrInst>(LV.getPointer()))
  1391. if (GEP->use_empty())
  1392. GEP->eraseFromParent();
  1393. }
  1394. // Deactivate all the partial cleanups in reverse order, which
  1395. // generally means popping them.
  1396. assert((cleanupDominator || cleanups.empty()) &&
  1397. "Missing cleanupDominator before deactivating cleanup blocks");
  1398. for (unsigned i = cleanups.size(); i != 0; --i)
  1399. CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
  1400. // Destroy the placeholder if we made one.
  1401. if (cleanupDominator)
  1402. cleanupDominator->eraseFromParent();
  1403. }
  1404. void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
  1405. llvm::Value *outerBegin) {
  1406. // Emit the common subexpression.
  1407. CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
  1408. Address destPtr = EnsureSlot(E->getType()).getAddress();
  1409. uint64_t numElements = E->getArraySize().getZExtValue();
  1410. if (!numElements)
  1411. return;
  1412. // destPtr is an array*. Construct an elementType* by drilling down a level.
  1413. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1414. llvm::Value *indices[] = {zero, zero};
  1415. llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
  1416. "arrayinit.begin");
  1417. // Prepare to special-case multidimensional array initialization: we avoid
  1418. // emitting multiple destructor loops in that case.
  1419. if (!outerBegin)
  1420. outerBegin = begin;
  1421. ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
  1422. QualType elementType =
  1423. CGF.getContext().getAsArrayType(E->getType())->getElementType();
  1424. CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
  1425. CharUnits elementAlign =
  1426. destPtr.getAlignment().alignmentOfArrayElement(elementSize);
  1427. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1428. llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
  1429. // Jump into the body.
  1430. CGF.EmitBlock(bodyBB);
  1431. llvm::PHINode *index =
  1432. Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
  1433. index->addIncoming(zero, entryBB);
  1434. llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
  1435. // Prepare for a cleanup.
  1436. QualType::DestructionKind dtorKind = elementType.isDestructedType();
  1437. EHScopeStack::stable_iterator cleanup;
  1438. if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
  1439. if (outerBegin->getType() != element->getType())
  1440. outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
  1441. CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
  1442. elementAlign,
  1443. CGF.getDestroyer(dtorKind));
  1444. cleanup = CGF.EHStack.stable_begin();
  1445. } else {
  1446. dtorKind = QualType::DK_none;
  1447. }
  1448. // Emit the actual filler expression.
  1449. {
  1450. // Temporaries created in an array initialization loop are destroyed
  1451. // at the end of each iteration.
  1452. CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
  1453. CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
  1454. LValue elementLV =
  1455. CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
  1456. if (InnerLoop) {
  1457. // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
  1458. auto elementSlot = AggValueSlot::forLValue(
  1459. elementLV, AggValueSlot::IsDestructed,
  1460. AggValueSlot::DoesNotNeedGCBarriers,
  1461. AggValueSlot::IsNotAliased,
  1462. AggValueSlot::DoesNotOverlap);
  1463. AggExprEmitter(CGF, elementSlot, false)
  1464. .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
  1465. } else
  1466. EmitInitializationToLValue(E->getSubExpr(), elementLV);
  1467. }
  1468. // Move on to the next element.
  1469. llvm::Value *nextIndex = Builder.CreateNUWAdd(
  1470. index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
  1471. index->addIncoming(nextIndex, Builder.GetInsertBlock());
  1472. // Leave the loop if we're done.
  1473. llvm::Value *done = Builder.CreateICmpEQ(
  1474. nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
  1475. "arrayinit.done");
  1476. llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
  1477. Builder.CreateCondBr(done, endBB, bodyBB);
  1478. CGF.EmitBlock(endBB);
  1479. // Leave the partial-array cleanup if we entered one.
  1480. if (dtorKind)
  1481. CGF.DeactivateCleanupBlock(cleanup, index);
  1482. }
  1483. void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
  1484. AggValueSlot Dest = EnsureSlot(E->getType());
  1485. LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
  1486. EmitInitializationToLValue(E->getBase(), DestLV);
  1487. VisitInitListExpr(E->getUpdater());
  1488. }
  1489. //===----------------------------------------------------------------------===//
  1490. // Entry Points into this File
  1491. //===----------------------------------------------------------------------===//
  1492. /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
  1493. /// non-zero bytes that will be stored when outputting the initializer for the
  1494. /// specified initializer expression.
  1495. static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
  1496. E = E->IgnoreParens();
  1497. // 0 and 0.0 won't require any non-zero stores!
  1498. if (isSimpleZero(E, CGF)) return CharUnits::Zero();
  1499. // If this is an initlist expr, sum up the size of sizes of the (present)
  1500. // elements. If this is something weird, assume the whole thing is non-zero.
  1501. const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  1502. while (ILE && ILE->isTransparent())
  1503. ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
  1504. if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
  1505. return CGF.getContext().getTypeSizeInChars(E->getType());
  1506. // InitListExprs for structs have to be handled carefully. If there are
  1507. // reference members, we need to consider the size of the reference, not the
  1508. // referencee. InitListExprs for unions and arrays can't have references.
  1509. if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
  1510. if (!RT->isUnionType()) {
  1511. RecordDecl *SD = RT->getDecl();
  1512. CharUnits NumNonZeroBytes = CharUnits::Zero();
  1513. unsigned ILEElement = 0;
  1514. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
  1515. while (ILEElement != CXXRD->getNumBases())
  1516. NumNonZeroBytes +=
  1517. GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
  1518. for (const auto *Field : SD->fields()) {
  1519. // We're done once we hit the flexible array member or run out of
  1520. // InitListExpr elements.
  1521. if (Field->getType()->isIncompleteArrayType() ||
  1522. ILEElement == ILE->getNumInits())
  1523. break;
  1524. if (Field->isUnnamedBitfield())
  1525. continue;
  1526. const Expr *E = ILE->getInit(ILEElement++);
  1527. // Reference values are always non-null and have the width of a pointer.
  1528. if (Field->getType()->isReferenceType())
  1529. NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
  1530. CGF.getTarget().getPointerWidth(0));
  1531. else
  1532. NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
  1533. }
  1534. return NumNonZeroBytes;
  1535. }
  1536. }
  1537. CharUnits NumNonZeroBytes = CharUnits::Zero();
  1538. for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
  1539. NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
  1540. return NumNonZeroBytes;
  1541. }
  1542. /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
  1543. /// zeros in it, emit a memset and avoid storing the individual zeros.
  1544. ///
  1545. static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
  1546. CodeGenFunction &CGF) {
  1547. // If the slot is already known to be zeroed, nothing to do. Don't mess with
  1548. // volatile stores.
  1549. if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
  1550. return;
  1551. // C++ objects with a user-declared constructor don't need zero'ing.
  1552. if (CGF.getLangOpts().CPlusPlus)
  1553. if (const RecordType *RT = CGF.getContext()
  1554. .getBaseElementType(E->getType())->getAs<RecordType>()) {
  1555. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  1556. if (RD->hasUserDeclaredConstructor())
  1557. return;
  1558. }
  1559. // If the type is 16-bytes or smaller, prefer individual stores over memset.
  1560. CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
  1561. if (Size <= CharUnits::fromQuantity(16))
  1562. return;
  1563. // Check to see if over 3/4 of the initializer are known to be zero. If so,
  1564. // we prefer to emit memset + individual stores for the rest.
  1565. CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
  1566. if (NumNonZeroBytes*4 > Size)
  1567. return;
  1568. // Okay, it seems like a good idea to use an initial memset, emit the call.
  1569. llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
  1570. Address Loc = Slot.getAddress();
  1571. Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
  1572. CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
  1573. // Tell the AggExprEmitter that the slot is known zero.
  1574. Slot.setZeroed();
  1575. }
  1576. /// EmitAggExpr - Emit the computation of the specified expression of aggregate
  1577. /// type. The result is computed into DestPtr. Note that if DestPtr is null,
  1578. /// the value of the aggregate expression is not needed. If VolatileDest is
  1579. /// true, DestPtr cannot be 0.
  1580. void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
  1581. assert(E && hasAggregateEvaluationKind(E->getType()) &&
  1582. "Invalid aggregate expression to emit");
  1583. assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
  1584. "slot has bits but no address");
  1585. // Optimize the slot if possible.
  1586. CheckAggExprForMemSetUse(Slot, E, *this);
  1587. AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
  1588. }
  1589. LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
  1590. assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
  1591. Address Temp = CreateMemTemp(E->getType());
  1592. LValue LV = MakeAddrLValue(Temp, E->getType());
  1593. EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
  1594. AggValueSlot::DoesNotNeedGCBarriers,
  1595. AggValueSlot::IsNotAliased,
  1596. AggValueSlot::DoesNotOverlap));
  1597. return LV;
  1598. }
  1599. AggValueSlot::Overlap_t
  1600. CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {
  1601. if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
  1602. return AggValueSlot::DoesNotOverlap;
  1603. // If the field lies entirely within the enclosing class's nvsize, its tail
  1604. // padding cannot overlap any already-initialized object. (The only subobjects
  1605. // with greater addresses that might already be initialized are vbases.)
  1606. const RecordDecl *ClassRD = FD->getParent();
  1607. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
  1608. if (Layout.getFieldOffset(FD->getFieldIndex()) +
  1609. getContext().getTypeSize(FD->getType()) <=
  1610. (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
  1611. return AggValueSlot::DoesNotOverlap;
  1612. // The tail padding may contain values we need to preserve.
  1613. return AggValueSlot::MayOverlap;
  1614. }
  1615. AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(
  1616. const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
  1617. // If the most-derived object is a field declared with [[no_unique_address]],
  1618. // the tail padding of any virtual base could be reused for other subobjects
  1619. // of that field's class.
  1620. if (IsVirtual)
  1621. return AggValueSlot::MayOverlap;
  1622. // If the base class is laid out entirely within the nvsize of the derived
  1623. // class, its tail padding cannot yet be initialized, so we can issue
  1624. // stores at the full width of the base class.
  1625. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  1626. if (Layout.getBaseClassOffset(BaseRD) +
  1627. getContext().getASTRecordLayout(BaseRD).getSize() <=
  1628. Layout.getNonVirtualSize())
  1629. return AggValueSlot::DoesNotOverlap;
  1630. // The tail padding may contain values we need to preserve.
  1631. return AggValueSlot::MayOverlap;
  1632. }
  1633. void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
  1634. AggValueSlot::Overlap_t MayOverlap,
  1635. bool isVolatile) {
  1636. assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
  1637. Address DestPtr = Dest.getAddress();
  1638. Address SrcPtr = Src.getAddress();
  1639. if (getLangOpts().CPlusPlus) {
  1640. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1641. CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
  1642. assert((Record->hasTrivialCopyConstructor() ||
  1643. Record->hasTrivialCopyAssignment() ||
  1644. Record->hasTrivialMoveConstructor() ||
  1645. Record->hasTrivialMoveAssignment() ||
  1646. Record->isUnion()) &&
  1647. "Trying to aggregate-copy a type without a trivial copy/move "
  1648. "constructor or assignment operator");
  1649. // Ignore empty classes in C++.
  1650. if (Record->isEmpty())
  1651. return;
  1652. }
  1653. }
  1654. // Aggregate assignment turns into llvm.memcpy. This is almost valid per
  1655. // C99 6.5.16.1p3, which states "If the value being stored in an object is
  1656. // read from another object that overlaps in anyway the storage of the first
  1657. // object, then the overlap shall be exact and the two objects shall have
  1658. // qualified or unqualified versions of a compatible type."
  1659. //
  1660. // memcpy is not defined if the source and destination pointers are exactly
  1661. // equal, but other compilers do this optimization, and almost every memcpy
  1662. // implementation handles this case safely. If there is a libc that does not
  1663. // safely handle this, we can add a target hook.
  1664. // Get data size info for this aggregate. Don't copy the tail padding if this
  1665. // might be a potentially-overlapping subobject, since the tail padding might
  1666. // be occupied by a different object. Otherwise, copying it is fine.
  1667. std::pair<CharUnits, CharUnits> TypeInfo;
  1668. if (MayOverlap)
  1669. TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
  1670. else
  1671. TypeInfo = getContext().getTypeInfoInChars(Ty);
  1672. llvm::Value *SizeVal = nullptr;
  1673. if (TypeInfo.first.isZero()) {
  1674. // But note that getTypeInfo returns 0 for a VLA.
  1675. if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
  1676. getContext().getAsArrayType(Ty))) {
  1677. QualType BaseEltTy;
  1678. SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
  1679. TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
  1680. assert(!TypeInfo.first.isZero());
  1681. SizeVal = Builder.CreateNUWMul(
  1682. SizeVal,
  1683. llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
  1684. }
  1685. }
  1686. if (!SizeVal) {
  1687. SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
  1688. }
  1689. // FIXME: If we have a volatile struct, the optimizer can remove what might
  1690. // appear to be `extra' memory ops:
  1691. //
  1692. // volatile struct { int i; } a, b;
  1693. //
  1694. // int main() {
  1695. // a = b;
  1696. // a = b;
  1697. // }
  1698. //
  1699. // we need to use a different call here. We use isVolatile to indicate when
  1700. // either the source or the destination is volatile.
  1701. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1702. SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
  1703. // Don't do any of the memmove_collectable tests if GC isn't set.
  1704. if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
  1705. // fall through
  1706. } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1707. RecordDecl *Record = RecordTy->getDecl();
  1708. if (Record->hasObjectMember()) {
  1709. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1710. SizeVal);
  1711. return;
  1712. }
  1713. } else if (Ty->isArrayType()) {
  1714. QualType BaseType = getContext().getBaseElementType(Ty);
  1715. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  1716. if (RecordTy->getDecl()->hasObjectMember()) {
  1717. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1718. SizeVal);
  1719. return;
  1720. }
  1721. }
  1722. }
  1723. auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
  1724. // Determine the metadata to describe the position of any padding in this
  1725. // memcpy, as well as the TBAA tags for the members of the struct, in case
  1726. // the optimizer wishes to expand it in to scalar memory operations.
  1727. if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
  1728. Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
  1729. if (CGM.getCodeGenOpts().NewStructPathTBAA) {
  1730. TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
  1731. Dest.getTBAAInfo(), Src.getTBAAInfo());
  1732. CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
  1733. }
  1734. }