CGExprAgg.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  1. //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Aggregate Expr nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGObjCRuntime.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/StmtVisitor.h"
  20. #include "llvm/Constants.h"
  21. #include "llvm/Function.h"
  22. #include "llvm/GlobalVariable.h"
  23. #include "llvm/Intrinsics.h"
  24. using namespace clang;
  25. using namespace CodeGen;
  26. //===----------------------------------------------------------------------===//
  27. // Aggregate Expression Emitter
  28. //===----------------------------------------------------------------------===//
  29. namespace {
  30. class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
  31. CodeGenFunction &CGF;
  32. CGBuilderTy &Builder;
  33. AggValueSlot Dest;
  34. bool IgnoreResult;
  35. /// We want to use 'dest' as the return slot except under two
  36. /// conditions:
  37. /// - The destination slot requires garbage collection, so we
  38. /// need to use the GC API.
  39. /// - The destination slot is potentially aliased.
  40. bool shouldUseDestForReturnSlot() const {
  41. return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
  42. }
  43. ReturnValueSlot getReturnValueSlot() const {
  44. if (!shouldUseDestForReturnSlot())
  45. return ReturnValueSlot();
  46. return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
  47. }
  48. AggValueSlot EnsureSlot(QualType T) {
  49. if (!Dest.isIgnored()) return Dest;
  50. return CGF.CreateAggTemp(T, "agg.tmp.ensured");
  51. }
  52. public:
  53. AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
  54. bool ignore)
  55. : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
  56. IgnoreResult(ignore) {
  57. }
  58. //===--------------------------------------------------------------------===//
  59. // Utilities
  60. //===--------------------------------------------------------------------===//
  61. /// EmitAggLoadOfLValue - Given an expression with aggregate type that
  62. /// represents a value lvalue, this method emits the address of the lvalue,
  63. /// then loads the result into DestPtr.
  64. void EmitAggLoadOfLValue(const Expr *E);
  65. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  66. void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
  67. void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false,
  68. unsigned Alignment = 0);
  69. void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
  70. void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
  71. void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
  72. QualType elementType, InitListExpr *E);
  73. AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
  74. if (CGF.getLangOptions().getGC() && TypeRequiresGCollection(T))
  75. return AggValueSlot::NeedsGCBarriers;
  76. return AggValueSlot::DoesNotNeedGCBarriers;
  77. }
  78. bool TypeRequiresGCollection(QualType T);
  79. //===--------------------------------------------------------------------===//
  80. // Visitor Methods
  81. //===--------------------------------------------------------------------===//
  82. void VisitStmt(Stmt *S) {
  83. CGF.ErrorUnsupported(S, "aggregate expression");
  84. }
  85. void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
  86. void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  87. Visit(GE->getResultExpr());
  88. }
  89. void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
  90. void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
  91. return Visit(E->getReplacement());
  92. }
  93. // l-values.
  94. void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
  95. void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
  96. void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
  97. void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
  98. void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
  99. void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
  100. EmitAggLoadOfLValue(E);
  101. }
  102. void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
  103. EmitAggLoadOfLValue(E);
  104. }
  105. void VisitPredefinedExpr(const PredefinedExpr *E) {
  106. EmitAggLoadOfLValue(E);
  107. }
  108. // Operators.
  109. void VisitCastExpr(CastExpr *E);
  110. void VisitCallExpr(const CallExpr *E);
  111. void VisitStmtExpr(const StmtExpr *E);
  112. void VisitBinaryOperator(const BinaryOperator *BO);
  113. void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
  114. void VisitBinAssign(const BinaryOperator *E);
  115. void VisitBinComma(const BinaryOperator *E);
  116. void VisitObjCMessageExpr(ObjCMessageExpr *E);
  117. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  118. EmitAggLoadOfLValue(E);
  119. }
  120. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
  121. void VisitChooseExpr(const ChooseExpr *CE);
  122. void VisitInitListExpr(InitListExpr *E);
  123. void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
  124. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  125. Visit(DAE->getExpr());
  126. }
  127. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
  128. void VisitCXXConstructExpr(const CXXConstructExpr *E);
  129. void VisitLambdaExpr(LambdaExpr *E);
  130. void VisitExprWithCleanups(ExprWithCleanups *E);
  131. void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
  132. void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
  133. void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
  134. void VisitOpaqueValueExpr(OpaqueValueExpr *E);
  135. void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
  136. if (E->isGLValue()) {
  137. LValue LV = CGF.EmitPseudoObjectLValue(E);
  138. return EmitFinalDestCopy(E, LV);
  139. }
  140. CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
  141. }
  142. void VisitVAArgExpr(VAArgExpr *E);
  143. void EmitInitializationToLValue(Expr *E, LValue Address);
  144. void EmitNullInitializationToLValue(LValue Address);
  145. // case Expr::ChooseExprClass:
  146. void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
  147. void VisitAtomicExpr(AtomicExpr *E) {
  148. CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
  149. }
  150. };
  151. } // end anonymous namespace.
  152. //===----------------------------------------------------------------------===//
  153. // Utilities
  154. //===----------------------------------------------------------------------===//
  155. /// EmitAggLoadOfLValue - Given an expression with aggregate type that
  156. /// represents a value lvalue, this method emits the address of the lvalue,
  157. /// then loads the result into DestPtr.
  158. void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
  159. LValue LV = CGF.EmitLValue(E);
  160. EmitFinalDestCopy(E, LV);
  161. }
  162. /// \brief True if the given aggregate type requires special GC API calls.
  163. bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
  164. // Only record types have members that might require garbage collection.
  165. const RecordType *RecordTy = T->getAs<RecordType>();
  166. if (!RecordTy) return false;
  167. // Don't mess with non-trivial C++ types.
  168. RecordDecl *Record = RecordTy->getDecl();
  169. if (isa<CXXRecordDecl>(Record) &&
  170. (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
  171. !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
  172. return false;
  173. // Check whether the type has an object member.
  174. return Record->hasObjectMember();
  175. }
  176. /// \brief Perform the final move to DestPtr if for some reason
  177. /// getReturnValueSlot() didn't use it directly.
  178. ///
  179. /// The idea is that you do something like this:
  180. /// RValue Result = EmitSomething(..., getReturnValueSlot());
  181. /// EmitMoveFromReturnSlot(E, Result);
  182. ///
  183. /// If nothing interferes, this will cause the result to be emitted
  184. /// directly into the return value slot. Otherwise, a final move
  185. /// will be performed.
  186. void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) {
  187. if (shouldUseDestForReturnSlot()) {
  188. // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
  189. // The possibility of undef rvalues complicates that a lot,
  190. // though, so we can't really assert.
  191. return;
  192. }
  193. // Otherwise, do a final copy,
  194. assert(Dest.getAddr() != Src.getAggregateAddr());
  195. EmitFinalDestCopy(E, Src, /*Ignore*/ true);
  196. }
  197. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  198. void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore,
  199. unsigned Alignment) {
  200. assert(Src.isAggregate() && "value must be aggregate value!");
  201. // If Dest is ignored, then we're evaluating an aggregate expression
  202. // in a context (like an expression statement) that doesn't care
  203. // about the result. C says that an lvalue-to-rvalue conversion is
  204. // performed in these cases; C++ says that it is not. In either
  205. // case, we don't actually need to do anything unless the value is
  206. // volatile.
  207. if (Dest.isIgnored()) {
  208. if (!Src.isVolatileQualified() ||
  209. CGF.CGM.getLangOptions().CPlusPlus ||
  210. (IgnoreResult && Ignore))
  211. return;
  212. // If the source is volatile, we must read from it; to do that, we need
  213. // some place to put it.
  214. Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
  215. }
  216. if (Dest.requiresGCollection()) {
  217. CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
  218. llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
  219. llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
  220. CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
  221. Dest.getAddr(),
  222. Src.getAggregateAddr(),
  223. SizeVal);
  224. return;
  225. }
  226. // If the result of the assignment is used, copy the LHS there also.
  227. // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
  228. // from the source as well, as we can't eliminate it if either operand
  229. // is volatile, unless copy has volatile for both source and destination..
  230. CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
  231. Dest.isVolatile()|Src.isVolatileQualified(),
  232. Alignment);
  233. }
  234. /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
  235. void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
  236. assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
  237. CharUnits Alignment = std::min(Src.getAlignment(), Dest.getAlignment());
  238. EmitFinalDestCopy(E, Src.asAggregateRValue(), Ignore, Alignment.getQuantity());
  239. }
  240. static QualType GetStdInitializerListElementType(QualType T) {
  241. // Just assume that this is really std::initializer_list.
  242. ClassTemplateSpecializationDecl *specialization =
  243. cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
  244. return specialization->getTemplateArgs()[0].getAsType();
  245. }
  246. /// \brief Prepare cleanup for the temporary array.
  247. static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
  248. QualType arrayType,
  249. llvm::Value *addr,
  250. const InitListExpr *initList) {
  251. QualType::DestructionKind dtorKind = arrayType.isDestructedType();
  252. if (!dtorKind)
  253. return; // Type doesn't need destroying.
  254. if (dtorKind != QualType::DK_cxx_destructor) {
  255. CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
  256. return;
  257. }
  258. CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
  259. CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
  260. /*EHCleanup=*/true);
  261. }
  262. /// \brief Emit the initializer for a std::initializer_list initialized with a
  263. /// real initializer list.
  264. void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
  265. InitListExpr *initList) {
  266. // We emit an array containing the elements, then have the init list point
  267. // at the array.
  268. ASTContext &ctx = CGF.getContext();
  269. unsigned numInits = initList->getNumInits();
  270. QualType element = GetStdInitializerListElementType(initList->getType());
  271. llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
  272. QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
  273. llvm::Type *LTy = CGF.ConvertTypeForMem(array);
  274. llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
  275. alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
  276. alloc->setName(".initlist.");
  277. EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
  278. // FIXME: The diagnostics are somewhat out of place here.
  279. RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
  280. RecordDecl::field_iterator field = record->field_begin();
  281. if (field == record->field_end()) {
  282. CGF.ErrorUnsupported(initList, "weird std::initializer_list");
  283. }
  284. QualType elementPtr = ctx.getPointerType(element.withConst());
  285. // Start pointer.
  286. if (!ctx.hasSameType(field->getType(), elementPtr)) {
  287. CGF.ErrorUnsupported(initList, "weird std::initializer_list");
  288. }
  289. LValue start = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
  290. llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
  291. CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
  292. ++field;
  293. if (field == record->field_end()) {
  294. CGF.ErrorUnsupported(initList, "weird std::initializer_list");
  295. }
  296. LValue endOrLength = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
  297. if (ctx.hasSameType(field->getType(), elementPtr)) {
  298. // End pointer.
  299. llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
  300. CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
  301. } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
  302. // Length.
  303. CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
  304. } else {
  305. CGF.ErrorUnsupported(initList, "weird std::initializer_list");
  306. }
  307. if (!Dest.isExternallyDestructed())
  308. EmitStdInitializerListCleanup(CGF, array, alloc, initList);
  309. }
  310. /// \brief Emit initialization of an array from an initializer list.
  311. void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
  312. QualType elementType, InitListExpr *E) {
  313. uint64_t NumInitElements = E->getNumInits();
  314. uint64_t NumArrayElements = AType->getNumElements();
  315. assert(NumInitElements <= NumArrayElements);
  316. // DestPtr is an array*. Construct an elementType* by drilling
  317. // down a level.
  318. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  319. llvm::Value *indices[] = { zero, zero };
  320. llvm::Value *begin =
  321. Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
  322. // Exception safety requires us to destroy all the
  323. // already-constructed members if an initializer throws.
  324. // For that, we'll need an EH cleanup.
  325. QualType::DestructionKind dtorKind = elementType.isDestructedType();
  326. llvm::AllocaInst *endOfInit = 0;
  327. EHScopeStack::stable_iterator cleanup;
  328. llvm::Instruction *cleanupDominator = 0;
  329. if (CGF.needsEHCleanup(dtorKind)) {
  330. // In principle we could tell the cleanup where we are more
  331. // directly, but the control flow can get so varied here that it
  332. // would actually be quite complex. Therefore we go through an
  333. // alloca.
  334. endOfInit = CGF.CreateTempAlloca(begin->getType(),
  335. "arrayinit.endOfInit");
  336. cleanupDominator = Builder.CreateStore(begin, endOfInit);
  337. CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
  338. CGF.getDestroyer(dtorKind));
  339. cleanup = CGF.EHStack.stable_begin();
  340. // Otherwise, remember that we didn't need a cleanup.
  341. } else {
  342. dtorKind = QualType::DK_none;
  343. }
  344. llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
  345. // The 'current element to initialize'. The invariants on this
  346. // variable are complicated. Essentially, after each iteration of
  347. // the loop, it points to the last initialized element, except
  348. // that it points to the beginning of the array before any
  349. // elements have been initialized.
  350. llvm::Value *element = begin;
  351. // Emit the explicit initializers.
  352. for (uint64_t i = 0; i != NumInitElements; ++i) {
  353. // Advance to the next element.
  354. if (i > 0) {
  355. element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
  356. // Tell the cleanup that it needs to destroy up to this
  357. // element. TODO: some of these stores can be trivially
  358. // observed to be unnecessary.
  359. if (endOfInit) Builder.CreateStore(element, endOfInit);
  360. }
  361. // If these are nested std::initializer_list inits, do them directly,
  362. // because they are conceptually the same "location".
  363. InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
  364. if (initList && initList->initializesStdInitializerList()) {
  365. EmitStdInitializerList(element, initList);
  366. } else {
  367. LValue elementLV = CGF.MakeAddrLValue(element, elementType);
  368. EmitInitializationToLValue(E->getInit(i), elementLV);
  369. }
  370. }
  371. // Check whether there's a non-trivial array-fill expression.
  372. // Note that this will be a CXXConstructExpr even if the element
  373. // type is an array (or array of array, etc.) of class type.
  374. Expr *filler = E->getArrayFiller();
  375. bool hasTrivialFiller = true;
  376. if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
  377. assert(cons->getConstructor()->isDefaultConstructor());
  378. hasTrivialFiller = cons->getConstructor()->isTrivial();
  379. }
  380. // Any remaining elements need to be zero-initialized, possibly
  381. // using the filler expression. We can skip this if the we're
  382. // emitting to zeroed memory.
  383. if (NumInitElements != NumArrayElements &&
  384. !(Dest.isZeroed() && hasTrivialFiller &&
  385. CGF.getTypes().isZeroInitializable(elementType))) {
  386. // Use an actual loop. This is basically
  387. // do { *array++ = filler; } while (array != end);
  388. // Advance to the start of the rest of the array.
  389. if (NumInitElements) {
  390. element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
  391. if (endOfInit) Builder.CreateStore(element, endOfInit);
  392. }
  393. // Compute the end of the array.
  394. llvm::Value *end = Builder.CreateInBoundsGEP(begin,
  395. llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
  396. "arrayinit.end");
  397. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  398. llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
  399. // Jump into the body.
  400. CGF.EmitBlock(bodyBB);
  401. llvm::PHINode *currentElement =
  402. Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
  403. currentElement->addIncoming(element, entryBB);
  404. // Emit the actual filler expression.
  405. LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
  406. if (filler)
  407. EmitInitializationToLValue(filler, elementLV);
  408. else
  409. EmitNullInitializationToLValue(elementLV);
  410. // Move on to the next element.
  411. llvm::Value *nextElement =
  412. Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
  413. // Tell the EH cleanup that we finished with the last element.
  414. if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
  415. // Leave the loop if we're done.
  416. llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
  417. "arrayinit.done");
  418. llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
  419. Builder.CreateCondBr(done, endBB, bodyBB);
  420. currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
  421. CGF.EmitBlock(endBB);
  422. }
  423. // Leave the partial-array cleanup if we entered one.
  424. if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
  425. }
  426. //===----------------------------------------------------------------------===//
  427. // Visitor Methods
  428. //===----------------------------------------------------------------------===//
  429. void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
  430. Visit(E->GetTemporaryExpr());
  431. }
  432. void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
  433. EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
  434. }
  435. void
  436. AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  437. if (E->getType().isPODType(CGF.getContext())) {
  438. // For a POD type, just emit a load of the lvalue + a copy, because our
  439. // compound literal might alias the destination.
  440. // FIXME: This is a band-aid; the real problem appears to be in our handling
  441. // of assignments, where we store directly into the LHS without checking
  442. // whether anything in the RHS aliases.
  443. EmitAggLoadOfLValue(E);
  444. return;
  445. }
  446. AggValueSlot Slot = EnsureSlot(E->getType());
  447. CGF.EmitAggExpr(E->getInitializer(), Slot);
  448. }
  449. void AggExprEmitter::VisitCastExpr(CastExpr *E) {
  450. switch (E->getCastKind()) {
  451. case CK_Dynamic: {
  452. assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
  453. LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
  454. // FIXME: Do we also need to handle property references here?
  455. if (LV.isSimple())
  456. CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
  457. else
  458. CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
  459. if (!Dest.isIgnored())
  460. CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
  461. break;
  462. }
  463. case CK_ToUnion: {
  464. if (Dest.isIgnored()) break;
  465. // GCC union extension
  466. QualType Ty = E->getSubExpr()->getType();
  467. QualType PtrTy = CGF.getContext().getPointerType(Ty);
  468. llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
  469. CGF.ConvertType(PtrTy));
  470. EmitInitializationToLValue(E->getSubExpr(),
  471. CGF.MakeAddrLValue(CastPtr, Ty));
  472. break;
  473. }
  474. case CK_DerivedToBase:
  475. case CK_BaseToDerived:
  476. case CK_UncheckedDerivedToBase: {
  477. llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
  478. "should have been unpacked before we got here");
  479. }
  480. case CK_LValueToRValue: // hope for downstream optimization
  481. case CK_NoOp:
  482. case CK_AtomicToNonAtomic:
  483. case CK_NonAtomicToAtomic:
  484. case CK_UserDefinedConversion:
  485. case CK_ConstructorConversion:
  486. assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
  487. E->getType()) &&
  488. "Implicit cast types must be compatible");
  489. Visit(E->getSubExpr());
  490. break;
  491. case CK_LValueBitCast:
  492. llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
  493. case CK_Dependent:
  494. case CK_BitCast:
  495. case CK_ArrayToPointerDecay:
  496. case CK_FunctionToPointerDecay:
  497. case CK_NullToPointer:
  498. case CK_NullToMemberPointer:
  499. case CK_BaseToDerivedMemberPointer:
  500. case CK_DerivedToBaseMemberPointer:
  501. case CK_MemberPointerToBoolean:
  502. case CK_ReinterpretMemberPointer:
  503. case CK_IntegralToPointer:
  504. case CK_PointerToIntegral:
  505. case CK_PointerToBoolean:
  506. case CK_ToVoid:
  507. case CK_VectorSplat:
  508. case CK_IntegralCast:
  509. case CK_IntegralToBoolean:
  510. case CK_IntegralToFloating:
  511. case CK_FloatingToIntegral:
  512. case CK_FloatingToBoolean:
  513. case CK_FloatingCast:
  514. case CK_CPointerToObjCPointerCast:
  515. case CK_BlockPointerToObjCPointerCast:
  516. case CK_AnyPointerToBlockPointerCast:
  517. case CK_ObjCObjectLValueCast:
  518. case CK_FloatingRealToComplex:
  519. case CK_FloatingComplexToReal:
  520. case CK_FloatingComplexToBoolean:
  521. case CK_FloatingComplexCast:
  522. case CK_FloatingComplexToIntegralComplex:
  523. case CK_IntegralRealToComplex:
  524. case CK_IntegralComplexToReal:
  525. case CK_IntegralComplexToBoolean:
  526. case CK_IntegralComplexCast:
  527. case CK_IntegralComplexToFloatingComplex:
  528. case CK_ARCProduceObject:
  529. case CK_ARCConsumeObject:
  530. case CK_ARCReclaimReturnedObject:
  531. case CK_ARCExtendBlockObject:
  532. llvm_unreachable("cast kind invalid for aggregate types");
  533. }
  534. }
  535. void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
  536. if (E->getCallReturnType()->isReferenceType()) {
  537. EmitAggLoadOfLValue(E);
  538. return;
  539. }
  540. RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
  541. EmitMoveFromReturnSlot(E, RV);
  542. }
  543. void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  544. RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
  545. EmitMoveFromReturnSlot(E, RV);
  546. }
  547. void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
  548. CGF.EmitIgnoredExpr(E->getLHS());
  549. Visit(E->getRHS());
  550. }
  551. void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
  552. CodeGenFunction::StmtExprEvaluation eval(CGF);
  553. CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
  554. }
  555. void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
  556. if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
  557. VisitPointerToDataMemberBinaryOperator(E);
  558. else
  559. CGF.ErrorUnsupported(E, "aggregate binary expression");
  560. }
  561. void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
  562. const BinaryOperator *E) {
  563. LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
  564. EmitFinalDestCopy(E, LV);
  565. }
  566. void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
  567. // For an assignment to work, the value on the right has
  568. // to be compatible with the value on the left.
  569. assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
  570. E->getRHS()->getType())
  571. && "Invalid assignment");
  572. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
  573. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  574. if (VD->hasAttr<BlocksAttr>() &&
  575. E->getRHS()->HasSideEffects(CGF.getContext())) {
  576. // When __block variable on LHS, the RHS must be evaluated first
  577. // as it may change the 'forwarding' field via call to Block_copy.
  578. LValue RHS = CGF.EmitLValue(E->getRHS());
  579. LValue LHS = CGF.EmitLValue(E->getLHS());
  580. Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
  581. needsGC(E->getLHS()->getType()),
  582. AggValueSlot::IsAliased);
  583. EmitFinalDestCopy(E, RHS, true);
  584. return;
  585. }
  586. LValue LHS = CGF.EmitLValue(E->getLHS());
  587. // Codegen the RHS so that it stores directly into the LHS.
  588. AggValueSlot LHSSlot =
  589. AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
  590. needsGC(E->getLHS()->getType()),
  591. AggValueSlot::IsAliased);
  592. CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
  593. EmitFinalDestCopy(E, LHS, true);
  594. }
  595. void AggExprEmitter::
  596. VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  597. llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
  598. llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
  599. llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
  600. // Bind the common expression if necessary.
  601. CodeGenFunction::OpaqueValueMapping binding(CGF, E);
  602. CodeGenFunction::ConditionalEvaluation eval(CGF);
  603. CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
  604. // Save whether the destination's lifetime is externally managed.
  605. bool isExternallyDestructed = Dest.isExternallyDestructed();
  606. eval.begin(CGF);
  607. CGF.EmitBlock(LHSBlock);
  608. Visit(E->getTrueExpr());
  609. eval.end(CGF);
  610. assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
  611. CGF.Builder.CreateBr(ContBlock);
  612. // If the result of an agg expression is unused, then the emission
  613. // of the LHS might need to create a destination slot. That's fine
  614. // with us, and we can safely emit the RHS into the same slot, but
  615. // we shouldn't claim that it's already being destructed.
  616. Dest.setExternallyDestructed(isExternallyDestructed);
  617. eval.begin(CGF);
  618. CGF.EmitBlock(RHSBlock);
  619. Visit(E->getFalseExpr());
  620. eval.end(CGF);
  621. CGF.EmitBlock(ContBlock);
  622. }
  623. void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
  624. Visit(CE->getChosenSubExpr(CGF.getContext()));
  625. }
  626. void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
  627. llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
  628. llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
  629. if (!ArgPtr) {
  630. CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
  631. return;
  632. }
  633. EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
  634. }
  635. void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  636. // Ensure that we have a slot, but if we already do, remember
  637. // whether it was externally destructed.
  638. bool wasExternallyDestructed = Dest.isExternallyDestructed();
  639. Dest = EnsureSlot(E->getType());
  640. // We're going to push a destructor if there isn't already one.
  641. Dest.setExternallyDestructed();
  642. Visit(E->getSubExpr());
  643. // Push that destructor we promised.
  644. if (!wasExternallyDestructed)
  645. CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
  646. }
  647. void
  648. AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
  649. AggValueSlot Slot = EnsureSlot(E->getType());
  650. CGF.EmitCXXConstructExpr(E, Slot);
  651. }
  652. void
  653. AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
  654. AggValueSlot Slot = EnsureSlot(E->getType());
  655. CGF.EmitLambdaExpr(E, Slot);
  656. }
  657. void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
  658. CGF.enterFullExpression(E);
  659. CodeGenFunction::RunCleanupsScope cleanups(CGF);
  660. Visit(E->getSubExpr());
  661. }
  662. void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
  663. QualType T = E->getType();
  664. AggValueSlot Slot = EnsureSlot(T);
  665. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
  666. }
  667. void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
  668. QualType T = E->getType();
  669. AggValueSlot Slot = EnsureSlot(T);
  670. EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
  671. }
  672. /// isSimpleZero - If emitting this value will obviously just cause a store of
  673. /// zero to memory, return true. This can return false if uncertain, so it just
  674. /// handles simple cases.
  675. static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
  676. E = E->IgnoreParens();
  677. // 0
  678. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
  679. return IL->getValue() == 0;
  680. // +0.0
  681. if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
  682. return FL->getValue().isPosZero();
  683. // int()
  684. if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
  685. CGF.getTypes().isZeroInitializable(E->getType()))
  686. return true;
  687. // (int*)0 - Null pointer expressions.
  688. if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
  689. return ICE->getCastKind() == CK_NullToPointer;
  690. // '\0'
  691. if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
  692. return CL->getValue() == 0;
  693. // Otherwise, hard case: conservatively return false.
  694. return false;
  695. }
  696. void
  697. AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
  698. QualType type = LV.getType();
  699. // FIXME: Ignore result?
  700. // FIXME: Are initializers affected by volatile?
  701. if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
  702. // Storing "i32 0" to a zero'd memory location is a noop.
  703. } else if (isa<ImplicitValueInitExpr>(E)) {
  704. EmitNullInitializationToLValue(LV);
  705. } else if (type->isReferenceType()) {
  706. RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
  707. CGF.EmitStoreThroughLValue(RV, LV);
  708. } else if (type->isAnyComplexType()) {
  709. CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
  710. } else if (CGF.hasAggregateLLVMType(type)) {
  711. CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
  712. AggValueSlot::IsDestructed,
  713. AggValueSlot::DoesNotNeedGCBarriers,
  714. AggValueSlot::IsNotAliased,
  715. Dest.isZeroed()));
  716. } else if (LV.isSimple()) {
  717. CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
  718. } else {
  719. CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
  720. }
  721. }
  722. void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
  723. QualType type = lv.getType();
  724. // If the destination slot is already zeroed out before the aggregate is
  725. // copied into it, we don't have to emit any zeros here.
  726. if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
  727. return;
  728. if (!CGF.hasAggregateLLVMType(type)) {
  729. // For non-aggregates, we can store zero
  730. llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
  731. CGF.EmitStoreThroughLValue(RValue::get(null), lv);
  732. } else {
  733. // There's a potential optimization opportunity in combining
  734. // memsets; that would be easy for arrays, but relatively
  735. // difficult for structures with the current code.
  736. CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
  737. }
  738. }
  739. void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
  740. #if 0
  741. // FIXME: Assess perf here? Figure out what cases are worth optimizing here
  742. // (Length of globals? Chunks of zeroed-out space?).
  743. //
  744. // If we can, prefer a copy from a global; this is a lot less code for long
  745. // globals, and it's easier for the current optimizers to analyze.
  746. if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
  747. llvm::GlobalVariable* GV =
  748. new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
  749. llvm::GlobalValue::InternalLinkage, C, "");
  750. EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
  751. return;
  752. }
  753. #endif
  754. if (E->hadArrayRangeDesignator())
  755. CGF.ErrorUnsupported(E, "GNU array range designator extension");
  756. if (E->initializesStdInitializerList()) {
  757. EmitStdInitializerList(Dest.getAddr(), E);
  758. return;
  759. }
  760. llvm::Value *DestPtr = Dest.getAddr();
  761. // Handle initialization of an array.
  762. if (E->getType()->isArrayType()) {
  763. if (E->getNumInits() > 0) {
  764. QualType T1 = E->getType();
  765. QualType T2 = E->getInit(0)->getType();
  766. if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
  767. EmitAggLoadOfLValue(E->getInit(0));
  768. return;
  769. }
  770. }
  771. QualType elementType = E->getType().getCanonicalType();
  772. elementType = CGF.getContext().getQualifiedType(
  773. cast<ArrayType>(elementType)->getElementType(),
  774. elementType.getQualifiers() + Dest.getQualifiers());
  775. llvm::PointerType *APType =
  776. cast<llvm::PointerType>(DestPtr->getType());
  777. llvm::ArrayType *AType =
  778. cast<llvm::ArrayType>(APType->getElementType());
  779. EmitArrayInit(DestPtr, AType, elementType, E);
  780. return;
  781. }
  782. assert(E->getType()->isRecordType() && "Only support structs/unions here!");
  783. // Do struct initialization; this code just sets each individual member
  784. // to the approprate value. This makes bitfield support automatic;
  785. // the disadvantage is that the generated code is more difficult for
  786. // the optimizer, especially with bitfields.
  787. unsigned NumInitElements = E->getNumInits();
  788. RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
  789. if (record->isUnion()) {
  790. // Only initialize one field of a union. The field itself is
  791. // specified by the initializer list.
  792. if (!E->getInitializedFieldInUnion()) {
  793. // Empty union; we have nothing to do.
  794. #ifndef NDEBUG
  795. // Make sure that it's really an empty and not a failure of
  796. // semantic analysis.
  797. for (RecordDecl::field_iterator Field = record->field_begin(),
  798. FieldEnd = record->field_end();
  799. Field != FieldEnd; ++Field)
  800. assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
  801. #endif
  802. return;
  803. }
  804. // FIXME: volatility
  805. FieldDecl *Field = E->getInitializedFieldInUnion();
  806. LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
  807. if (NumInitElements) {
  808. // Store the initializer into the field
  809. EmitInitializationToLValue(E->getInit(0), FieldLoc);
  810. } else {
  811. // Default-initialize to null.
  812. EmitNullInitializationToLValue(FieldLoc);
  813. }
  814. return;
  815. }
  816. // We'll need to enter cleanup scopes in case any of the member
  817. // initializers throw an exception.
  818. SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
  819. llvm::Instruction *cleanupDominator = 0;
  820. // Here we iterate over the fields; this makes it simpler to both
  821. // default-initialize fields and skip over unnamed fields.
  822. unsigned curInitIndex = 0;
  823. for (RecordDecl::field_iterator field = record->field_begin(),
  824. fieldEnd = record->field_end();
  825. field != fieldEnd; ++field) {
  826. // We're done once we hit the flexible array member.
  827. if (field->getType()->isIncompleteArrayType())
  828. break;
  829. // Always skip anonymous bitfields.
  830. if (field->isUnnamedBitfield())
  831. continue;
  832. // We're done if we reach the end of the explicit initializers, we
  833. // have a zeroed object, and the rest of the fields are
  834. // zero-initializable.
  835. if (curInitIndex == NumInitElements && Dest.isZeroed() &&
  836. CGF.getTypes().isZeroInitializable(E->getType()))
  837. break;
  838. // FIXME: volatility
  839. LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0);
  840. // We never generate write-barries for initialized fields.
  841. LV.setNonGC(true);
  842. if (curInitIndex < NumInitElements) {
  843. // Store the initializer into the field.
  844. EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
  845. } else {
  846. // We're out of initalizers; default-initialize to null
  847. EmitNullInitializationToLValue(LV);
  848. }
  849. // Push a destructor if necessary.
  850. // FIXME: if we have an array of structures, all explicitly
  851. // initialized, we can end up pushing a linear number of cleanups.
  852. bool pushedCleanup = false;
  853. if (QualType::DestructionKind dtorKind
  854. = field->getType().isDestructedType()) {
  855. assert(LV.isSimple());
  856. if (CGF.needsEHCleanup(dtorKind)) {
  857. if (!cleanupDominator)
  858. cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
  859. CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
  860. CGF.getDestroyer(dtorKind), false);
  861. cleanups.push_back(CGF.EHStack.stable_begin());
  862. pushedCleanup = true;
  863. }
  864. }
  865. // If the GEP didn't get used because of a dead zero init or something
  866. // else, clean it up for -O0 builds and general tidiness.
  867. if (!pushedCleanup && LV.isSimple())
  868. if (llvm::GetElementPtrInst *GEP =
  869. dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
  870. if (GEP->use_empty())
  871. GEP->eraseFromParent();
  872. }
  873. // Deactivate all the partial cleanups in reverse order, which
  874. // generally means popping them.
  875. for (unsigned i = cleanups.size(); i != 0; --i)
  876. CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
  877. // Destroy the placeholder if we made one.
  878. if (cleanupDominator)
  879. cleanupDominator->eraseFromParent();
  880. }
  881. //===----------------------------------------------------------------------===//
  882. // Entry Points into this File
  883. //===----------------------------------------------------------------------===//
  884. /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
  885. /// non-zero bytes that will be stored when outputting the initializer for the
  886. /// specified initializer expression.
  887. static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
  888. E = E->IgnoreParens();
  889. // 0 and 0.0 won't require any non-zero stores!
  890. if (isSimpleZero(E, CGF)) return CharUnits::Zero();
  891. // If this is an initlist expr, sum up the size of sizes of the (present)
  892. // elements. If this is something weird, assume the whole thing is non-zero.
  893. const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
  894. if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
  895. return CGF.getContext().getTypeSizeInChars(E->getType());
  896. // InitListExprs for structs have to be handled carefully. If there are
  897. // reference members, we need to consider the size of the reference, not the
  898. // referencee. InitListExprs for unions and arrays can't have references.
  899. if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
  900. if (!RT->isUnionType()) {
  901. RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
  902. CharUnits NumNonZeroBytes = CharUnits::Zero();
  903. unsigned ILEElement = 0;
  904. for (RecordDecl::field_iterator Field = SD->field_begin(),
  905. FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
  906. // We're done once we hit the flexible array member or run out of
  907. // InitListExpr elements.
  908. if (Field->getType()->isIncompleteArrayType() ||
  909. ILEElement == ILE->getNumInits())
  910. break;
  911. if (Field->isUnnamedBitfield())
  912. continue;
  913. const Expr *E = ILE->getInit(ILEElement++);
  914. // Reference values are always non-null and have the width of a pointer.
  915. if (Field->getType()->isReferenceType())
  916. NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
  917. CGF.getContext().getTargetInfo().getPointerWidth(0));
  918. else
  919. NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
  920. }
  921. return NumNonZeroBytes;
  922. }
  923. }
  924. CharUnits NumNonZeroBytes = CharUnits::Zero();
  925. for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
  926. NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
  927. return NumNonZeroBytes;
  928. }
  929. /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
  930. /// zeros in it, emit a memset and avoid storing the individual zeros.
  931. ///
  932. static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
  933. CodeGenFunction &CGF) {
  934. // If the slot is already known to be zeroed, nothing to do. Don't mess with
  935. // volatile stores.
  936. if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
  937. // C++ objects with a user-declared constructor don't need zero'ing.
  938. if (CGF.getContext().getLangOptions().CPlusPlus)
  939. if (const RecordType *RT = CGF.getContext()
  940. .getBaseElementType(E->getType())->getAs<RecordType>()) {
  941. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  942. if (RD->hasUserDeclaredConstructor())
  943. return;
  944. }
  945. // If the type is 16-bytes or smaller, prefer individual stores over memset.
  946. std::pair<CharUnits, CharUnits> TypeInfo =
  947. CGF.getContext().getTypeInfoInChars(E->getType());
  948. if (TypeInfo.first <= CharUnits::fromQuantity(16))
  949. return;
  950. // Check to see if over 3/4 of the initializer are known to be zero. If so,
  951. // we prefer to emit memset + individual stores for the rest.
  952. CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
  953. if (NumNonZeroBytes*4 > TypeInfo.first)
  954. return;
  955. // Okay, it seems like a good idea to use an initial memset, emit the call.
  956. llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
  957. CharUnits Align = TypeInfo.second;
  958. llvm::Value *Loc = Slot.getAddr();
  959. Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
  960. CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
  961. Align.getQuantity(), false);
  962. // Tell the AggExprEmitter that the slot is known zero.
  963. Slot.setZeroed();
  964. }
  965. /// EmitAggExpr - Emit the computation of the specified expression of aggregate
  966. /// type. The result is computed into DestPtr. Note that if DestPtr is null,
  967. /// the value of the aggregate expression is not needed. If VolatileDest is
  968. /// true, DestPtr cannot be 0.
  969. ///
  970. /// \param IsInitializer - true if this evaluation is initializing an
  971. /// object whose lifetime is already being managed.
  972. void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
  973. bool IgnoreResult) {
  974. assert(E && hasAggregateLLVMType(E->getType()) &&
  975. "Invalid aggregate expression to emit");
  976. assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
  977. "slot has bits but no address");
  978. // Optimize the slot if possible.
  979. CheckAggExprForMemSetUse(Slot, E, *this);
  980. AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
  981. }
  982. LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
  983. assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
  984. llvm::Value *Temp = CreateMemTemp(E->getType());
  985. LValue LV = MakeAddrLValue(Temp, E->getType());
  986. EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
  987. AggValueSlot::DoesNotNeedGCBarriers,
  988. AggValueSlot::IsNotAliased));
  989. return LV;
  990. }
  991. void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
  992. llvm::Value *SrcPtr, QualType Ty,
  993. bool isVolatile, unsigned Alignment) {
  994. assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
  995. if (getContext().getLangOptions().CPlusPlus) {
  996. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  997. CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
  998. assert((Record->hasTrivialCopyConstructor() ||
  999. Record->hasTrivialCopyAssignment() ||
  1000. Record->hasTrivialMoveConstructor() ||
  1001. Record->hasTrivialMoveAssignment()) &&
  1002. "Trying to aggregate-copy a type without a trivial copy "
  1003. "constructor or assignment operator");
  1004. // Ignore empty classes in C++.
  1005. if (Record->isEmpty())
  1006. return;
  1007. }
  1008. }
  1009. // Aggregate assignment turns into llvm.memcpy. This is almost valid per
  1010. // C99 6.5.16.1p3, which states "If the value being stored in an object is
  1011. // read from another object that overlaps in anyway the storage of the first
  1012. // object, then the overlap shall be exact and the two objects shall have
  1013. // qualified or unqualified versions of a compatible type."
  1014. //
  1015. // memcpy is not defined if the source and destination pointers are exactly
  1016. // equal, but other compilers do this optimization, and almost every memcpy
  1017. // implementation handles this case safely. If there is a libc that does not
  1018. // safely handle this, we can add a target hook.
  1019. // Get size and alignment info for this aggregate.
  1020. std::pair<CharUnits, CharUnits> TypeInfo =
  1021. getContext().getTypeInfoInChars(Ty);
  1022. if (!Alignment)
  1023. Alignment = TypeInfo.second.getQuantity();
  1024. // FIXME: Handle variable sized types.
  1025. // FIXME: If we have a volatile struct, the optimizer can remove what might
  1026. // appear to be `extra' memory ops:
  1027. //
  1028. // volatile struct { int i; } a, b;
  1029. //
  1030. // int main() {
  1031. // a = b;
  1032. // a = b;
  1033. // }
  1034. //
  1035. // we need to use a different call here. We use isVolatile to indicate when
  1036. // either the source or the destination is volatile.
  1037. llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
  1038. llvm::Type *DBP =
  1039. llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
  1040. DestPtr = Builder.CreateBitCast(DestPtr, DBP);
  1041. llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
  1042. llvm::Type *SBP =
  1043. llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
  1044. SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
  1045. // Don't do any of the memmove_collectable tests if GC isn't set.
  1046. if (CGM.getLangOptions().getGC() == LangOptions::NonGC) {
  1047. // fall through
  1048. } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1049. RecordDecl *Record = RecordTy->getDecl();
  1050. if (Record->hasObjectMember()) {
  1051. CharUnits size = TypeInfo.first;
  1052. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  1053. llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
  1054. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1055. SizeVal);
  1056. return;
  1057. }
  1058. } else if (Ty->isArrayType()) {
  1059. QualType BaseType = getContext().getBaseElementType(Ty);
  1060. if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
  1061. if (RecordTy->getDecl()->hasObjectMember()) {
  1062. CharUnits size = TypeInfo.first;
  1063. llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  1064. llvm::Value *SizeVal =
  1065. llvm::ConstantInt::get(SizeTy, size.getQuantity());
  1066. CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
  1067. SizeVal);
  1068. return;
  1069. }
  1070. }
  1071. }
  1072. Builder.CreateMemCpy(DestPtr, SrcPtr,
  1073. llvm::ConstantInt::get(IntPtrTy,
  1074. TypeInfo.first.getQuantity()),
  1075. Alignment, isVolatile);
  1076. }
  1077. void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
  1078. const Expr *init) {
  1079. const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
  1080. if (cleanups)
  1081. init = cleanups->getSubExpr();
  1082. if (isa<InitListExpr>(init) &&
  1083. cast<InitListExpr>(init)->initializesStdInitializerList()) {
  1084. // We initialized this std::initializer_list with an initializer list.
  1085. // A backing array was created. Push a cleanup for it.
  1086. EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
  1087. }
  1088. }
  1089. static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
  1090. llvm::Value *arrayStart,
  1091. const InitListExpr *init) {
  1092. // Check if there are any recursive cleanups to do, i.e. if we have
  1093. // std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
  1094. // then we need to destroy the inner array as well.
  1095. for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
  1096. const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
  1097. if (!subInit || !subInit->initializesStdInitializerList())
  1098. continue;
  1099. // This one needs to be destroyed. Get the address of the std::init_list.
  1100. llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
  1101. llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
  1102. "std.initlist");
  1103. CGF.EmitStdInitializerListCleanup(loc, subInit);
  1104. }
  1105. }
  1106. void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
  1107. const InitListExpr *init) {
  1108. ASTContext &ctx = getContext();
  1109. QualType element = GetStdInitializerListElementType(init->getType());
  1110. unsigned numInits = init->getNumInits();
  1111. llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
  1112. QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
  1113. QualType arrayPtr = ctx.getPointerType(array);
  1114. llvm::Type *arrayPtrType = ConvertType(arrayPtr);
  1115. // lvalue is the location of a std::initializer_list, which as its first
  1116. // element has a pointer to the array we want to destroy.
  1117. llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
  1118. llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
  1119. ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
  1120. llvm::Value *arrayAddress =
  1121. Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
  1122. ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
  1123. }