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