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