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