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 "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Support/Compiler.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 VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33   CodeGenFunction &CGF;
34   CGBuilderTy &Builder;
35   llvm::Value *DestPtr;
36   bool VolatileDest;
37 public:
38   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest)
39     : CGF(cgf), Builder(CGF.Builder),
40       DestPtr(destPtr), VolatileDest(volatileDest) {
41   }
42 
43   //===--------------------------------------------------------------------===//
44   //                               Utilities
45   //===--------------------------------------------------------------------===//
46 
47   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
48   /// represents a value lvalue, this method emits the address of the lvalue,
49   /// then loads the result into DestPtr.
50   void EmitAggLoadOfLValue(const Expr *E);
51 
52   //===--------------------------------------------------------------------===//
53   //                            Visitor Methods
54   //===--------------------------------------------------------------------===//
55 
56   void VisitStmt(Stmt *S) {
57     CGF.ErrorUnsupported(S, "aggregate expression");
58   }
59   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
60   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
61 
62   // l-values.
63   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
64   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
65   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
66   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
67   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
68     EmitAggLoadOfLValue(E);
69   }
70   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
71     EmitAggLoadOfLValue(E);
72   }
73   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
74     EmitAggLoadOfLValue(E);
75   }
76   void VisitPredefinedExpr(const PredefinedExpr *E) {
77     EmitAggLoadOfLValue(E);
78   }
79 
80   // Operators.
81   void VisitCStyleCastExpr(CStyleCastExpr *E);
82   void VisitImplicitCastExpr(ImplicitCastExpr *E);
83   void VisitCallExpr(const CallExpr *E);
84   void VisitStmtExpr(const StmtExpr *E);
85   void VisitBinaryOperator(const BinaryOperator *BO);
86   void VisitBinAssign(const BinaryOperator *E);
87   void VisitBinComma(const BinaryOperator *E);
88 
89   void VisitObjCMessageExpr(ObjCMessageExpr *E);
90   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
91     EmitAggLoadOfLValue(E);
92   }
93   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
94   void VisitObjCKVCRefExpr(ObjCKVCRefExpr *E);
95 
96   void VisitConditionalOperator(const ConditionalOperator *CO);
97   void VisitInitListExpr(InitListExpr *E);
98   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
99     Visit(DAE->getExpr());
100   }
101   void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
102   void VisitVAArgExpr(VAArgExpr *E);
103 
104   void EmitInitializationToLValue(Expr *E, LValue Address);
105   void EmitNullInitializationToLValue(LValue Address, QualType T);
106   //  case Expr::ChooseExprClass:
107 
108 };
109 }  // end anonymous namespace.
110 
111 //===----------------------------------------------------------------------===//
112 //                                Utilities
113 //===----------------------------------------------------------------------===//
114 
115 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
116 /// represents a value lvalue, this method emits the address of the lvalue,
117 /// then loads the result into DestPtr.
118 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
119   LValue LV = CGF.EmitLValue(E);
120   assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc");
121   llvm::Value *SrcPtr = LV.getAddress();
122 
123   // If the result is ignored, don't copy from the value.
124   if (DestPtr == 0)
125     // FIXME: If the source is volatile, we must read from it.
126     return;
127 
128   CGF.EmitAggregateCopy(DestPtr, SrcPtr, E->getType());
129 }
130 
131 //===----------------------------------------------------------------------===//
132 //                            Visitor Methods
133 //===----------------------------------------------------------------------===//
134 
135 void AggExprEmitter::VisitCStyleCastExpr(CStyleCastExpr *E) {
136   // GCC union extension
137   if (E->getType()->isUnionType()) {
138     RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
139     LValue FieldLoc = CGF.EmitLValueForField(DestPtr,
140                                              *SD->field_begin(CGF.getContext()),
141                                              true, 0);
142     EmitInitializationToLValue(E->getSubExpr(), FieldLoc);
143     return;
144   }
145 
146   Visit(E->getSubExpr());
147 }
148 
149 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
150   assert(CGF.getContext().typesAreCompatible(
151                           E->getSubExpr()->getType().getUnqualifiedType(),
152                           E->getType().getUnqualifiedType()) &&
153          "Implicit cast types must be compatible");
154   Visit(E->getSubExpr());
155 }
156 
157 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
158   RValue RV = CGF.EmitCallExpr(E);
159   assert(RV.isAggregate() && "Return value must be aggregate value!");
160 
161   // If the result is ignored, don't copy from the value.
162   if (DestPtr == 0)
163     // FIXME: If the source is volatile, we must read from it.
164     return;
165 
166   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
167 }
168 
169 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
170   RValue RV = CGF.EmitObjCMessageExpr(E);
171   assert(RV.isAggregate() && "Return value must be aggregate value!");
172 
173   // If the result is ignored, don't copy from the value.
174   if (DestPtr == 0)
175     // FIXME: If the source is volatile, we must read from it.
176     return;
177 
178   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
179 }
180 
181 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
182   RValue RV = CGF.EmitObjCPropertyGet(E);
183   assert(RV.isAggregate() && "Return value must be aggregate value!");
184 
185   // If the result is ignored, don't copy from the value.
186   if (DestPtr == 0)
187     // FIXME: If the source is volatile, we must read from it.
188     return;
189 
190   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
191 }
192 
193 void AggExprEmitter::VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
194   RValue RV = CGF.EmitObjCPropertyGet(E);
195   assert(RV.isAggregate() && "Return value must be aggregate value!");
196 
197   // If the result is ignored, don't copy from the value.
198   if (DestPtr == 0)
199     // FIXME: If the source is volatile, we must read from it.
200     return;
201 
202   CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType());
203 }
204 
205 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
206   CGF.EmitAnyExpr(E->getLHS());
207   CGF.EmitAggExpr(E->getRHS(), DestPtr, false);
208 }
209 
210 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
211   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
212 }
213 
214 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
215   CGF.ErrorUnsupported(E, "aggregate binary expression");
216 }
217 
218 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
219   // For an assignment to work, the value on the right has
220   // to be compatible with the value on the left.
221   assert(CGF.getContext().typesAreCompatible(
222              E->getLHS()->getType().getUnqualifiedType(),
223              E->getRHS()->getType().getUnqualifiedType())
224          && "Invalid assignment");
225   LValue LHS = CGF.EmitLValue(E->getLHS());
226 
227   // We have to special case property setters, otherwise we must have
228   // a simple lvalue (no aggregates inside vectors, bitfields).
229   if (LHS.isPropertyRef()) {
230     // FIXME: Volatility?
231     llvm::Value *AggLoc = DestPtr;
232     if (!AggLoc)
233       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
234     CGF.EmitAggExpr(E->getRHS(), AggLoc, false);
235     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
236                             RValue::getAggregate(AggLoc));
237   }
238   else if (LHS.isKVCRef()) {
239     // FIXME: Volatility?
240     llvm::Value *AggLoc = DestPtr;
241     if (!AggLoc)
242       AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType()));
243     CGF.EmitAggExpr(E->getRHS(), AggLoc, false);
244     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
245                             RValue::getAggregate(AggLoc));
246   } else {
247     // Codegen the RHS so that it stores directly into the LHS.
248     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/);
249 
250     if (DestPtr == 0)
251       return;
252 
253     // If the result of the assignment is used, copy the RHS there also.
254     CGF.EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType());
255   }
256 }
257 
258 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
259   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
260   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
261   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
262 
263   llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond());
264   Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
265 
266   CGF.EmitBlock(LHSBlock);
267 
268   // Handle the GNU extension for missing LHS.
269   assert(E->getLHS() && "Must have LHS for aggregate value");
270 
271   Visit(E->getLHS());
272   CGF.EmitBranch(ContBlock);
273 
274   CGF.EmitBlock(RHSBlock);
275 
276   Visit(E->getRHS());
277   CGF.EmitBranch(ContBlock);
278 
279   CGF.EmitBlock(ContBlock);
280 }
281 
282 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
283   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
284   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
285 
286   if (!ArgPtr) {
287     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
288     return;
289   }
290 
291   if (DestPtr)
292     // FIXME: volatility
293     CGF.EmitAggregateCopy(DestPtr, ArgPtr, VE->getType());
294 }
295 
296 void
297 AggExprEmitter::VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E) {
298   llvm::Value *This = 0;
299 
300   if (DestPtr)
301     This = DestPtr;
302   else
303     This = CGF.CreateTempAlloca(CGF.ConvertType(E->getType()), "tmp");
304 
305   CGF.EmitCXXTemporaryObjectExpr(This, E);
306 }
307 
308 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
309   // FIXME: Are initializers affected by volatile?
310   if (isa<ImplicitValueInitExpr>(E)) {
311     EmitNullInitializationToLValue(LV, E->getType());
312   } else if (E->getType()->isComplexType()) {
313     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
314   } else if (CGF.hasAggregateLLVMType(E->getType())) {
315     CGF.EmitAnyExpr(E, LV.getAddress(), false);
316   } else {
317     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType());
318   }
319 }
320 
321 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
322   if (!CGF.hasAggregateLLVMType(T)) {
323     // For non-aggregates, we can store zero
324     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
325     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
326   } else {
327     // Otherwise, just memset the whole thing to zero.  This is legal
328     // because in LLVM, all default initializers are guaranteed to have a
329     // bit pattern of all zeros.
330     // FIXME: That isn't true for member pointers!
331     // There's a potential optimization opportunity in combining
332     // memsets; that would be easy for arrays, but relatively
333     // difficult for structures with the current code.
334     CGF.EmitMemSetToZero(LV.getAddress(), T);
335   }
336 }
337 
338 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
339 #if 0
340   // FIXME: Disabled while we figure out what to do about
341   // test/CodeGen/bitfield.c
342   //
343   // If we can, prefer a copy from a global; this is a lot less
344   // code for long globals, and it's easier for the current optimizers
345   // to analyze.
346   // FIXME: Should we really be doing this? Should we try to avoid
347   // cases where we emit a global with a lot of zeros?  Should
348   // we try to avoid short globals?
349   if (E->isConstantInitializer(CGF.getContext(), 0)) {
350     llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF);
351     llvm::GlobalVariable* GV =
352     new llvm::GlobalVariable(C->getType(), true,
353                              llvm::GlobalValue::InternalLinkage,
354                              C, "", &CGF.CGM.getModule(), 0);
355     CGF.EmitAggregateCopy(DestPtr, GV, E->getType());
356     return;
357   }
358 #endif
359   if (E->hadArrayRangeDesignator()) {
360     CGF.ErrorUnsupported(E, "GNU array range designator extension");
361   }
362 
363   // Handle initialization of an array.
364   if (E->getType()->isArrayType()) {
365     const llvm::PointerType *APType =
366       cast<llvm::PointerType>(DestPtr->getType());
367     const llvm::ArrayType *AType =
368       cast<llvm::ArrayType>(APType->getElementType());
369 
370     uint64_t NumInitElements = E->getNumInits();
371 
372     if (E->getNumInits() > 0) {
373       QualType T1 = E->getType();
374       QualType T2 = E->getInit(0)->getType();
375       if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() ==
376           CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) {
377         EmitAggLoadOfLValue(E->getInit(0));
378         return;
379       }
380     }
381 
382     uint64_t NumArrayElements = AType->getNumElements();
383     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
384     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
385 
386     unsigned CVRqualifier = ElementType.getCVRQualifiers();
387 
388     for (uint64_t i = 0; i != NumArrayElements; ++i) {
389       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
390       if (i < NumInitElements)
391         EmitInitializationToLValue(E->getInit(i),
392                                    LValue::MakeAddr(NextVal, CVRqualifier));
393       else
394         EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier),
395                                        ElementType);
396     }
397     return;
398   }
399 
400   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
401 
402   // Do struct initialization; this code just sets each individual member
403   // to the approprate value.  This makes bitfield support automatic;
404   // the disadvantage is that the generated code is more difficult for
405   // the optimizer, especially with bitfields.
406   unsigned NumInitElements = E->getNumInits();
407   RecordDecl *SD = E->getType()->getAsRecordType()->getDecl();
408   unsigned CurInitVal = 0;
409 
410   if (E->getType()->isUnionType()) {
411     // Only initialize one field of a union. The field itself is
412     // specified by the initializer list.
413     if (!E->getInitializedFieldInUnion()) {
414       // Empty union; we have nothing to do.
415 
416 #ifndef NDEBUG
417       // Make sure that it's really an empty and not a failure of
418       // semantic analysis.
419       for (RecordDecl::field_iterator Field = SD->field_begin(CGF.getContext()),
420                                    FieldEnd = SD->field_end(CGF.getContext());
421            Field != FieldEnd; ++Field)
422         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
423 #endif
424       return;
425     }
426 
427     // FIXME: volatility
428     FieldDecl *Field = E->getInitializedFieldInUnion();
429     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0);
430 
431     if (NumInitElements) {
432       // Store the initializer into the field
433       EmitInitializationToLValue(E->getInit(0), FieldLoc);
434     } else {
435       // Default-initialize to null
436       EmitNullInitializationToLValue(FieldLoc, Field->getType());
437     }
438 
439     return;
440   }
441 
442   // Here we iterate over the fields; this makes it simpler to both
443   // default-initialize fields and skip over unnamed fields.
444   for (RecordDecl::field_iterator Field = SD->field_begin(CGF.getContext()),
445                                FieldEnd = SD->field_end(CGF.getContext());
446        Field != FieldEnd; ++Field) {
447     // We're done once we hit the flexible array member
448     if (Field->getType()->isIncompleteArrayType())
449       break;
450 
451     if (Field->isUnnamedBitfield())
452       continue;
453 
454     // FIXME: volatility
455     LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0);
456     if (CurInitVal < NumInitElements) {
457       // Store the initializer into the field
458       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc);
459     } else {
460       // We're out of initalizers; default-initialize to null
461       EmitNullInitializationToLValue(FieldLoc, Field->getType());
462     }
463   }
464 }
465 
466 //===----------------------------------------------------------------------===//
467 //                        Entry Points into this File
468 //===----------------------------------------------------------------------===//
469 
470 /// EmitAggExpr - Emit the computation of the specified expression of
471 /// aggregate type.  The result is computed into DestPtr.  Note that if
472 /// DestPtr is null, the value of the aggregate expression is not needed.
473 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
474                                   bool VolatileDest) {
475   assert(E && hasAggregateLLVMType(E->getType()) &&
476          "Invalid aggregate expression to emit");
477 
478   AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E));
479 }
480 
481 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) {
482   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
483 
484   EmitMemSetToZero(DestPtr, Ty);
485 }
486 
487 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
488                                         llvm::Value *SrcPtr, QualType Ty) {
489   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
490 
491   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
492   // C99 6.5.16.1p3, which states "If the value being stored in an object is
493   // read from another object that overlaps in anyway the storage of the first
494   // object, then the overlap shall be exact and the two objects shall have
495   // qualified or unqualified versions of a compatible type."
496   //
497   // memcpy is not defined if the source and destination pointers are exactly
498   // equal, but other compilers do this optimization, and almost every memcpy
499   // implementation handles this case safely.  If there is a libc that does not
500   // safely handle this, we can add a target hook.
501   const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
502   if (DestPtr->getType() != BP)
503     DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
504   if (SrcPtr->getType() != BP)
505     SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
506 
507   // Get size and alignment info for this aggregate.
508   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
509 
510   // FIXME: Handle variable sized types.
511   const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
512 
513   Builder.CreateCall4(CGM.getMemCpyFn(),
514                       DestPtr, SrcPtr,
515                       // TypeInfo.first describes size in bits.
516                       llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
517                       llvm::ConstantInt::get(llvm::Type::Int32Ty,
518                                              TypeInfo.second/8));
519 }
520