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 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.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 //===----------------------------------------------------------------------===//
28 //                        Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
30 
31 namespace  {
32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33   CodeGenFunction &CGF;
34   CGBuilderTy &Builder;
35   AggValueSlot Dest;
36   bool IgnoreResult;
37 
38   ReturnValueSlot getReturnValueSlot() const {
39     // If the destination slot requires garbage collection, we can't
40     // use the real return value slot, because we have to use the GC
41     // API.
42     if (Dest.requiresGCollection()) return ReturnValueSlot();
43 
44     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
45   }
46 
47   AggValueSlot EnsureSlot(QualType T) {
48     if (!Dest.isIgnored()) return Dest;
49     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
50   }
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   //===--------------------------------------------------------------------===//
60   //                               Utilities
61   //===--------------------------------------------------------------------===//
62 
63   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
64   /// represents a value lvalue, this method emits the address of the lvalue,
65   /// then loads the result into DestPtr.
66   void EmitAggLoadOfLValue(const Expr *E);
67 
68   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
69   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
70   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
71 
72   void EmitGCMove(const Expr *E, RValue Src);
73 
74   bool TypeRequiresGCollection(QualType T);
75 
76   //===--------------------------------------------------------------------===//
77   //                            Visitor Methods
78   //===--------------------------------------------------------------------===//
79 
80   void VisitStmt(Stmt *S) {
81     CGF.ErrorUnsupported(S, "aggregate expression");
82   }
83   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
84   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
85     Visit(GE->getResultExpr());
86   }
87   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
88 
89   // l-values.
90   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
91   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
92   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
93   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
94   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
95   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
96     EmitAggLoadOfLValue(E);
97   }
98   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
99     EmitAggLoadOfLValue(E);
100   }
101   void VisitPredefinedExpr(const PredefinedExpr *E) {
102     EmitAggLoadOfLValue(E);
103   }
104 
105   // Operators.
106   void VisitCastExpr(CastExpr *E);
107   void VisitCallExpr(const CallExpr *E);
108   void VisitStmtExpr(const StmtExpr *E);
109   void VisitBinaryOperator(const BinaryOperator *BO);
110   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
111   void VisitBinAssign(const BinaryOperator *E);
112   void VisitBinComma(const BinaryOperator *E);
113 
114   void VisitObjCMessageExpr(ObjCMessageExpr *E);
115   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
116     EmitAggLoadOfLValue(E);
117   }
118   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *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 VisitExprWithCleanups(ExprWithCleanups *E);
130   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
131   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
132 
133   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
134 
135   void VisitVAArgExpr(VAArgExpr *E);
136 
137   void EmitInitializationToLValue(Expr *E, LValue Address);
138   void EmitNullInitializationToLValue(LValue Address);
139   //  case Expr::ChooseExprClass:
140   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
141 };
142 }  // end anonymous namespace.
143 
144 //===----------------------------------------------------------------------===//
145 //                                Utilities
146 //===----------------------------------------------------------------------===//
147 
148 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
149 /// represents a value lvalue, this method emits the address of the lvalue,
150 /// then loads the result into DestPtr.
151 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
152   LValue LV = CGF.EmitLValue(E);
153   EmitFinalDestCopy(E, LV);
154 }
155 
156 /// \brief True if the given aggregate type requires special GC API calls.
157 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
158   // Only record types have members that might require garbage collection.
159   const RecordType *RecordTy = T->getAs<RecordType>();
160   if (!RecordTy) return false;
161 
162   // Don't mess with non-trivial C++ types.
163   RecordDecl *Record = RecordTy->getDecl();
164   if (isa<CXXRecordDecl>(Record) &&
165       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
166        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
167     return false;
168 
169   // Check whether the type has an object member.
170   return Record->hasObjectMember();
171 }
172 
173 /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
174 ///
175 /// The idea is that you do something like this:
176 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
177 ///   EmitGCMove(E, Result);
178 /// If GC doesn't interfere, this will cause the result to be emitted
179 /// directly into the return value slot.  If GC does interfere, a final
180 /// move will be performed.
181 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
182   if (Dest.requiresGCollection()) {
183     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
184     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
185     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
186     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
187                                                     Src.getAggregateAddr(),
188                                                     SizeVal);
189   }
190 }
191 
192 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
193 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
194   assert(Src.isAggregate() && "value must be aggregate value!");
195 
196   // If Dest is ignored, then we're evaluating an aggregate expression
197   // in a context (like an expression statement) that doesn't care
198   // about the result.  C says that an lvalue-to-rvalue conversion is
199   // performed in these cases; C++ says that it is not.  In either
200   // case, we don't actually need to do anything unless the value is
201   // volatile.
202   if (Dest.isIgnored()) {
203     if (!Src.isVolatileQualified() ||
204         CGF.CGM.getLangOptions().CPlusPlus ||
205         (IgnoreResult && Ignore))
206       return;
207 
208     // If the source is volatile, we must read from it; to do that, we need
209     // some place to put it.
210     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
211   }
212 
213   if (Dest.requiresGCollection()) {
214     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
215     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
216     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
217     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
218                                                       Dest.getAddr(),
219                                                       Src.getAggregateAddr(),
220                                                       SizeVal);
221     return;
222   }
223   // If the result of the assignment is used, copy the LHS there also.
224   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
225   // from the source as well, as we can't eliminate it if either operand
226   // is volatile, unless copy has volatile for both source and destination..
227   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
228                         Dest.isVolatile()|Src.isVolatileQualified());
229 }
230 
231 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
232 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
233   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
234 
235   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
236                                             Src.isVolatileQualified()),
237                     Ignore);
238 }
239 
240 //===----------------------------------------------------------------------===//
241 //                            Visitor Methods
242 //===----------------------------------------------------------------------===//
243 
244 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
245   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
246 }
247 
248 void
249 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
250   AggValueSlot Slot = EnsureSlot(E->getType());
251   CGF.EmitAggExpr(E->getInitializer(), Slot);
252 }
253 
254 
255 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
256   switch (E->getCastKind()) {
257   case CK_Dynamic: {
258     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
259     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
260     // FIXME: Do we also need to handle property references here?
261     if (LV.isSimple())
262       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
263     else
264       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
265 
266     if (!Dest.isIgnored())
267       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
268     break;
269   }
270 
271   case CK_ToUnion: {
272     if (Dest.isIgnored()) break;
273 
274     // GCC union extension
275     QualType Ty = E->getSubExpr()->getType();
276     QualType PtrTy = CGF.getContext().getPointerType(Ty);
277     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
278                                                  CGF.ConvertType(PtrTy));
279     EmitInitializationToLValue(E->getSubExpr(),
280                                CGF.MakeAddrLValue(CastPtr, Ty));
281     break;
282   }
283 
284   case CK_DerivedToBase:
285   case CK_BaseToDerived:
286   case CK_UncheckedDerivedToBase: {
287     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
288                 "should have been unpacked before we got here");
289     break;
290   }
291 
292   case CK_GetObjCProperty: {
293     LValue LV = CGF.EmitLValue(E->getSubExpr());
294     assert(LV.isPropertyRef());
295     RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot());
296     EmitGCMove(E, RV);
297     break;
298   }
299 
300   case CK_LValueToRValue: // hope for downstream optimization
301   case CK_NoOp:
302   case CK_UserDefinedConversion:
303   case CK_ConstructorConversion:
304     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
305                                                    E->getType()) &&
306            "Implicit cast types must be compatible");
307     Visit(E->getSubExpr());
308     break;
309 
310   case CK_LValueBitCast:
311     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
312     break;
313 
314   case CK_Dependent:
315   case CK_BitCast:
316   case CK_ArrayToPointerDecay:
317   case CK_FunctionToPointerDecay:
318   case CK_NullToPointer:
319   case CK_NullToMemberPointer:
320   case CK_BaseToDerivedMemberPointer:
321   case CK_DerivedToBaseMemberPointer:
322   case CK_MemberPointerToBoolean:
323   case CK_IntegralToPointer:
324   case CK_PointerToIntegral:
325   case CK_PointerToBoolean:
326   case CK_ToVoid:
327   case CK_VectorSplat:
328   case CK_IntegralCast:
329   case CK_IntegralToBoolean:
330   case CK_IntegralToFloating:
331   case CK_FloatingToIntegral:
332   case CK_FloatingToBoolean:
333   case CK_FloatingCast:
334   case CK_AnyPointerToObjCPointerCast:
335   case CK_AnyPointerToBlockPointerCast:
336   case CK_ObjCObjectLValueCast:
337   case CK_FloatingRealToComplex:
338   case CK_FloatingComplexToReal:
339   case CK_FloatingComplexToBoolean:
340   case CK_FloatingComplexCast:
341   case CK_FloatingComplexToIntegralComplex:
342   case CK_IntegralRealToComplex:
343   case CK_IntegralComplexToReal:
344   case CK_IntegralComplexToBoolean:
345   case CK_IntegralComplexCast:
346   case CK_IntegralComplexToFloatingComplex:
347   case CK_ObjCProduceObject:
348   case CK_ObjCConsumeObject:
349     llvm_unreachable("cast kind invalid for aggregate types");
350   }
351 }
352 
353 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
354   if (E->getCallReturnType()->isReferenceType()) {
355     EmitAggLoadOfLValue(E);
356     return;
357   }
358 
359   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
360   EmitGCMove(E, RV);
361 }
362 
363 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
364   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
365   EmitGCMove(E, RV);
366 }
367 
368 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
369   llvm_unreachable("direct property access not surrounded by "
370                    "lvalue-to-rvalue cast");
371 }
372 
373 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
374   CGF.EmitIgnoredExpr(E->getLHS());
375   Visit(E->getRHS());
376 }
377 
378 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
379   CodeGenFunction::StmtExprEvaluation eval(CGF);
380   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
381 }
382 
383 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
384   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
385     VisitPointerToDataMemberBinaryOperator(E);
386   else
387     CGF.ErrorUnsupported(E, "aggregate binary expression");
388 }
389 
390 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
391                                                     const BinaryOperator *E) {
392   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
393   EmitFinalDestCopy(E, LV);
394 }
395 
396 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
397   // For an assignment to work, the value on the right has
398   // to be compatible with the value on the left.
399   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
400                                                  E->getRHS()->getType())
401          && "Invalid assignment");
402 
403   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
404     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
405       if (VD->hasAttr<BlocksAttr>() &&
406           E->getRHS()->HasSideEffects(CGF.getContext())) {
407         // When __block variable on LHS, the RHS must be evaluated first
408         // as it may change the 'forwarding' field via call to Block_copy.
409         LValue RHS = CGF.EmitLValue(E->getRHS());
410         LValue LHS = CGF.EmitLValue(E->getLHS());
411         bool GCollection = false;
412         if (CGF.getContext().getLangOptions().getGCMode())
413           GCollection = TypeRequiresGCollection(E->getLHS()->getType());
414         Dest = AggValueSlot::forLValue(LHS, true, GCollection);
415         EmitFinalDestCopy(E, RHS, true);
416         return;
417       }
418 
419   LValue LHS = CGF.EmitLValue(E->getLHS());
420 
421   // We have to special case property setters, otherwise we must have
422   // a simple lvalue (no aggregates inside vectors, bitfields).
423   if (LHS.isPropertyRef()) {
424     const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr();
425     QualType ArgType = RE->getSetterArgType();
426     RValue Src;
427     if (ArgType->isReferenceType())
428       Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
429     else {
430       AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
431       CGF.EmitAggExpr(E->getRHS(), Slot);
432       Src = Slot.asRValue();
433     }
434     CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
435   } else {
436     bool GCollection = false;
437     if (CGF.getContext().getLangOptions().getGCMode())
438       GCollection = TypeRequiresGCollection(E->getLHS()->getType());
439 
440     // Codegen the RHS so that it stores directly into the LHS.
441     AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
442                                                    GCollection);
443     CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
444     EmitFinalDestCopy(E, LHS, true);
445   }
446 }
447 
448 void AggExprEmitter::
449 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
450   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
451   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
452   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
453 
454   // Bind the common expression if necessary.
455   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
456 
457   CodeGenFunction::ConditionalEvaluation eval(CGF);
458   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
459 
460   // Save whether the destination's lifetime is externally managed.
461   bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged();
462 
463   eval.begin(CGF);
464   CGF.EmitBlock(LHSBlock);
465   Visit(E->getTrueExpr());
466   eval.end(CGF);
467 
468   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
469   CGF.Builder.CreateBr(ContBlock);
470 
471   // If the result of an agg expression is unused, then the emission
472   // of the LHS might need to create a destination slot.  That's fine
473   // with us, and we can safely emit the RHS into the same slot, but
474   // we shouldn't claim that its lifetime is externally managed.
475   Dest.setLifetimeExternallyManaged(DestLifetimeManaged);
476 
477   eval.begin(CGF);
478   CGF.EmitBlock(RHSBlock);
479   Visit(E->getFalseExpr());
480   eval.end(CGF);
481 
482   CGF.EmitBlock(ContBlock);
483 }
484 
485 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
486   Visit(CE->getChosenSubExpr(CGF.getContext()));
487 }
488 
489 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
490   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
491   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
492 
493   if (!ArgPtr) {
494     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
495     return;
496   }
497 
498   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
499 }
500 
501 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
502   // Ensure that we have a slot, but if we already do, remember
503   // whether its lifetime was externally managed.
504   bool WasManaged = Dest.isLifetimeExternallyManaged();
505   Dest = EnsureSlot(E->getType());
506   Dest.setLifetimeExternallyManaged();
507 
508   Visit(E->getSubExpr());
509 
510   // Set up the temporary's destructor if its lifetime wasn't already
511   // being managed.
512   if (!WasManaged)
513     CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
514 }
515 
516 void
517 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
518   AggValueSlot Slot = EnsureSlot(E->getType());
519   CGF.EmitCXXConstructExpr(E, Slot);
520 }
521 
522 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
523   CGF.EmitExprWithCleanups(E, Dest);
524 }
525 
526 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
527   QualType T = E->getType();
528   AggValueSlot Slot = EnsureSlot(T);
529   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
530 }
531 
532 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
533   QualType T = E->getType();
534   AggValueSlot Slot = EnsureSlot(T);
535   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
536 }
537 
538 /// isSimpleZero - If emitting this value will obviously just cause a store of
539 /// zero to memory, return true.  This can return false if uncertain, so it just
540 /// handles simple cases.
541 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
542   E = E->IgnoreParens();
543 
544   // 0
545   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
546     return IL->getValue() == 0;
547   // +0.0
548   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
549     return FL->getValue().isPosZero();
550   // int()
551   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
552       CGF.getTypes().isZeroInitializable(E->getType()))
553     return true;
554   // (int*)0 - Null pointer expressions.
555   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
556     return ICE->getCastKind() == CK_NullToPointer;
557   // '\0'
558   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
559     return CL->getValue() == 0;
560 
561   // Otherwise, hard case: conservatively return false.
562   return false;
563 }
564 
565 
566 void
567 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
568   QualType type = LV.getType();
569   // FIXME: Ignore result?
570   // FIXME: Are initializers affected by volatile?
571   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
572     // Storing "i32 0" to a zero'd memory location is a noop.
573   } else if (isa<ImplicitValueInitExpr>(E)) {
574     EmitNullInitializationToLValue(LV);
575   } else if (type->isReferenceType()) {
576     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
577     CGF.EmitStoreThroughLValue(RV, LV, type);
578   } else if (type->isAnyComplexType()) {
579     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
580   } else if (CGF.hasAggregateLLVMType(type)) {
581     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV, true, false,
582                                                Dest.isZeroed()));
583   } else if (LV.isSimple()) {
584     CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
585   } else {
586     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV, type);
587   }
588 }
589 
590 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
591   QualType type = lv.getType();
592 
593   // If the destination slot is already zeroed out before the aggregate is
594   // copied into it, we don't have to emit any zeros here.
595   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
596     return;
597 
598   if (!CGF.hasAggregateLLVMType(type)) {
599     // For non-aggregates, we can store zero
600     llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
601     CGF.EmitStoreThroughLValue(RValue::get(null), lv, type);
602   } else {
603     // There's a potential optimization opportunity in combining
604     // memsets; that would be easy for arrays, but relatively
605     // difficult for structures with the current code.
606     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
607   }
608 }
609 
610 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
611 #if 0
612   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
613   // (Length of globals? Chunks of zeroed-out space?).
614   //
615   // If we can, prefer a copy from a global; this is a lot less code for long
616   // globals, and it's easier for the current optimizers to analyze.
617   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
618     llvm::GlobalVariable* GV =
619     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
620                              llvm::GlobalValue::InternalLinkage, C, "");
621     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
622     return;
623   }
624 #endif
625   if (E->hadArrayRangeDesignator())
626     CGF.ErrorUnsupported(E, "GNU array range designator extension");
627 
628   llvm::Value *DestPtr = Dest.getAddr();
629 
630   // Handle initialization of an array.
631   if (E->getType()->isArrayType()) {
632     const llvm::PointerType *APType =
633       cast<llvm::PointerType>(DestPtr->getType());
634     const llvm::ArrayType *AType =
635       cast<llvm::ArrayType>(APType->getElementType());
636 
637     uint64_t NumInitElements = E->getNumInits();
638 
639     if (E->getNumInits() > 0) {
640       QualType T1 = E->getType();
641       QualType T2 = E->getInit(0)->getType();
642       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
643         EmitAggLoadOfLValue(E->getInit(0));
644         return;
645       }
646     }
647 
648     uint64_t NumArrayElements = AType->getNumElements();
649     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
650     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
651     ElementType = CGF.getContext().getQualifiedType(ElementType,
652                                                     Dest.getQualifiers());
653 
654     bool hasNonTrivialCXXConstructor = false;
655     if (CGF.getContext().getLangOptions().CPlusPlus)
656       if (const RecordType *RT = CGF.getContext()
657                         .getBaseElementType(ElementType)->getAs<RecordType>()) {
658         const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
659         hasNonTrivialCXXConstructor = !RD->hasTrivialDefaultConstructor();
660       }
661 
662     for (uint64_t i = 0; i != NumArrayElements; ++i) {
663       // If we're done emitting initializers and the destination is known-zeroed
664       // then we're done.
665       if (i == NumInitElements &&
666           Dest.isZeroed() &&
667           CGF.getTypes().isZeroInitializable(ElementType) &&
668           !hasNonTrivialCXXConstructor)
669         break;
670 
671       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
672       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
673 
674       if (i < NumInitElements)
675         EmitInitializationToLValue(E->getInit(i), LV);
676       else if (Expr *filler = E->getArrayFiller())
677         EmitInitializationToLValue(filler, LV);
678       else
679         EmitNullInitializationToLValue(LV);
680 
681       // If the GEP didn't get used because of a dead zero init or something
682       // else, clean it up for -O0 builds and general tidiness.
683       if (llvm::GetElementPtrInst *GEP =
684             dyn_cast<llvm::GetElementPtrInst>(NextVal))
685         if (GEP->use_empty())
686           GEP->eraseFromParent();
687     }
688     return;
689   }
690 
691   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
692 
693   // Do struct initialization; this code just sets each individual member
694   // to the approprate value.  This makes bitfield support automatic;
695   // the disadvantage is that the generated code is more difficult for
696   // the optimizer, especially with bitfields.
697   unsigned NumInitElements = E->getNumInits();
698   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
699 
700   if (E->getType()->isUnionType()) {
701     // Only initialize one field of a union. The field itself is
702     // specified by the initializer list.
703     if (!E->getInitializedFieldInUnion()) {
704       // Empty union; we have nothing to do.
705 
706 #ifndef NDEBUG
707       // Make sure that it's really an empty and not a failure of
708       // semantic analysis.
709       for (RecordDecl::field_iterator Field = SD->field_begin(),
710                                    FieldEnd = SD->field_end();
711            Field != FieldEnd; ++Field)
712         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
713 #endif
714       return;
715     }
716 
717     // FIXME: volatility
718     FieldDecl *Field = E->getInitializedFieldInUnion();
719 
720     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
721     if (NumInitElements) {
722       // Store the initializer into the field
723       EmitInitializationToLValue(E->getInit(0), FieldLoc);
724     } else {
725       // Default-initialize to null.
726       EmitNullInitializationToLValue(FieldLoc);
727     }
728 
729     return;
730   }
731 
732   // Here we iterate over the fields; this makes it simpler to both
733   // default-initialize fields and skip over unnamed fields.
734   unsigned CurInitVal = 0;
735   for (RecordDecl::field_iterator Field = SD->field_begin(),
736                                FieldEnd = SD->field_end();
737        Field != FieldEnd; ++Field) {
738     // We're done once we hit the flexible array member
739     if (Field->getType()->isIncompleteArrayType())
740       break;
741 
742     if (Field->isUnnamedBitfield())
743       continue;
744 
745     // Don't emit GEP before a noop store of zero.
746     if (CurInitVal == NumInitElements && Dest.isZeroed() &&
747         CGF.getTypes().isZeroInitializable(E->getType()))
748       break;
749 
750     // FIXME: volatility
751     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
752     // We never generate write-barries for initialized fields.
753     FieldLoc.setNonGC(true);
754 
755     if (CurInitVal < NumInitElements) {
756       // Store the initializer into the field.
757       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
758     } else {
759       // We're out of initalizers; default-initialize to null
760       EmitNullInitializationToLValue(FieldLoc);
761     }
762 
763     // If the GEP didn't get used because of a dead zero init or something
764     // else, clean it up for -O0 builds and general tidiness.
765     if (FieldLoc.isSimple())
766       if (llvm::GetElementPtrInst *GEP =
767             dyn_cast<llvm::GetElementPtrInst>(FieldLoc.getAddress()))
768         if (GEP->use_empty())
769           GEP->eraseFromParent();
770   }
771 }
772 
773 //===----------------------------------------------------------------------===//
774 //                        Entry Points into this File
775 //===----------------------------------------------------------------------===//
776 
777 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
778 /// non-zero bytes that will be stored when outputting the initializer for the
779 /// specified initializer expression.
780 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
781   E = E->IgnoreParens();
782 
783   // 0 and 0.0 won't require any non-zero stores!
784   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
785 
786   // If this is an initlist expr, sum up the size of sizes of the (present)
787   // elements.  If this is something weird, assume the whole thing is non-zero.
788   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
789   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
790     return CGF.getContext().getTypeSizeInChars(E->getType());
791 
792   // InitListExprs for structs have to be handled carefully.  If there are
793   // reference members, we need to consider the size of the reference, not the
794   // referencee.  InitListExprs for unions and arrays can't have references.
795   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
796     if (!RT->isUnionType()) {
797       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
798       CharUnits NumNonZeroBytes = CharUnits::Zero();
799 
800       unsigned ILEElement = 0;
801       for (RecordDecl::field_iterator Field = SD->field_begin(),
802            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
803         // We're done once we hit the flexible array member or run out of
804         // InitListExpr elements.
805         if (Field->getType()->isIncompleteArrayType() ||
806             ILEElement == ILE->getNumInits())
807           break;
808         if (Field->isUnnamedBitfield())
809           continue;
810 
811         const Expr *E = ILE->getInit(ILEElement++);
812 
813         // Reference values are always non-null and have the width of a pointer.
814         if (Field->getType()->isReferenceType())
815           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
816               CGF.getContext().Target.getPointerWidth(0));
817         else
818           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
819       }
820 
821       return NumNonZeroBytes;
822     }
823   }
824 
825 
826   CharUnits NumNonZeroBytes = CharUnits::Zero();
827   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
828     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
829   return NumNonZeroBytes;
830 }
831 
832 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
833 /// zeros in it, emit a memset and avoid storing the individual zeros.
834 ///
835 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
836                                      CodeGenFunction &CGF) {
837   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
838   // volatile stores.
839   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
840 
841   // C++ objects with a user-declared constructor don't need zero'ing.
842   if (CGF.getContext().getLangOptions().CPlusPlus)
843     if (const RecordType *RT = CGF.getContext()
844                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
845       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
846       if (RD->hasUserDeclaredConstructor())
847         return;
848     }
849 
850   // If the type is 16-bytes or smaller, prefer individual stores over memset.
851   std::pair<CharUnits, CharUnits> TypeInfo =
852     CGF.getContext().getTypeInfoInChars(E->getType());
853   if (TypeInfo.first <= CharUnits::fromQuantity(16))
854     return;
855 
856   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
857   // we prefer to emit memset + individual stores for the rest.
858   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
859   if (NumNonZeroBytes*4 > TypeInfo.first)
860     return;
861 
862   // Okay, it seems like a good idea to use an initial memset, emit the call.
863   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
864   CharUnits Align = TypeInfo.second;
865 
866   llvm::Value *Loc = Slot.getAddr();
867   const llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
868 
869   Loc = CGF.Builder.CreateBitCast(Loc, BP);
870   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
871                            Align.getQuantity(), false);
872 
873   // Tell the AggExprEmitter that the slot is known zero.
874   Slot.setZeroed();
875 }
876 
877 
878 
879 
880 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
881 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
882 /// the value of the aggregate expression is not needed.  If VolatileDest is
883 /// true, DestPtr cannot be 0.
884 ///
885 /// \param IsInitializer - true if this evaluation is initializing an
886 /// object whose lifetime is already being managed.
887 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
888                                   bool IgnoreResult) {
889   assert(E && hasAggregateLLVMType(E->getType()) &&
890          "Invalid aggregate expression to emit");
891   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
892          "slot has bits but no address");
893 
894   // Optimize the slot if possible.
895   CheckAggExprForMemSetUse(Slot, E, *this);
896 
897   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
898 }
899 
900 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
901   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
902   llvm::Value *Temp = CreateMemTemp(E->getType());
903   LValue LV = MakeAddrLValue(Temp, E->getType());
904   EmitAggExpr(E, AggValueSlot::forLValue(LV, false));
905   return LV;
906 }
907 
908 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
909                                         llvm::Value *SrcPtr, QualType Ty,
910                                         bool isVolatile) {
911   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
912 
913   if (getContext().getLangOptions().CPlusPlus) {
914     if (const RecordType *RT = Ty->getAs<RecordType>()) {
915       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
916       assert((Record->hasTrivialCopyConstructor() ||
917               Record->hasTrivialCopyAssignment()) &&
918              "Trying to aggregate-copy a type without a trivial copy "
919              "constructor or assignment operator");
920       // Ignore empty classes in C++.
921       if (Record->isEmpty())
922         return;
923     }
924   }
925 
926   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
927   // C99 6.5.16.1p3, which states "If the value being stored in an object is
928   // read from another object that overlaps in anyway the storage of the first
929   // object, then the overlap shall be exact and the two objects shall have
930   // qualified or unqualified versions of a compatible type."
931   //
932   // memcpy is not defined if the source and destination pointers are exactly
933   // equal, but other compilers do this optimization, and almost every memcpy
934   // implementation handles this case safely.  If there is a libc that does not
935   // safely handle this, we can add a target hook.
936 
937   // Get size and alignment info for this aggregate.
938   std::pair<CharUnits, CharUnits> TypeInfo =
939     getContext().getTypeInfoInChars(Ty);
940 
941   // FIXME: Handle variable sized types.
942 
943   // FIXME: If we have a volatile struct, the optimizer can remove what might
944   // appear to be `extra' memory ops:
945   //
946   // volatile struct { int i; } a, b;
947   //
948   // int main() {
949   //   a = b;
950   //   a = b;
951   // }
952   //
953   // we need to use a different call here.  We use isVolatile to indicate when
954   // either the source or the destination is volatile.
955 
956   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
957   const llvm::Type *DBP =
958     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
959   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
960 
961   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
962   const llvm::Type *SBP =
963     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
964   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
965 
966   // Don't do any of the memmove_collectable tests if GC isn't set.
967   if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) {
968     // fall through
969   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
970     RecordDecl *Record = RecordTy->getDecl();
971     if (Record->hasObjectMember()) {
972       CharUnits size = TypeInfo.first;
973       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
974       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
975       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
976                                                     SizeVal);
977       return;
978     }
979   } else if (Ty->isArrayType()) {
980     QualType BaseType = getContext().getBaseElementType(Ty);
981     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
982       if (RecordTy->getDecl()->hasObjectMember()) {
983         CharUnits size = TypeInfo.first;
984         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
985         llvm::Value *SizeVal =
986           llvm::ConstantInt::get(SizeTy, size.getQuantity());
987         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
988                                                       SizeVal);
989         return;
990       }
991     }
992   }
993 
994   Builder.CreateMemCpy(DestPtr, SrcPtr,
995                        llvm::ConstantInt::get(IntPtrTy,
996                                               TypeInfo.first.getQuantity()),
997                        TypeInfo.second.getQuantity(), isVolatile);
998 }
999