1 //===--- CGExpr.cpp - Emit LLVM Code from 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 Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGCall.h"
17 #include "CGCXXABI.h"
18 #include "CGDebugInfo.h"
19 #include "CGRecordLayout.h"
20 #include "CGObjCRuntime.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "llvm/Intrinsics.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/Target/TargetData.h"
26 using namespace clang;
27 using namespace CodeGen;
28 
29 //===--------------------------------------------------------------------===//
30 //                        Miscellaneous Helper Methods
31 //===--------------------------------------------------------------------===//
32 
33 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
34   unsigned addressSpace =
35     cast<llvm::PointerType>(value->getType())->getAddressSpace();
36 
37   const llvm::PointerType *destType = Int8PtrTy;
38   if (addressSpace)
39     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
40 
41   if (value->getType() == destType) return value;
42   return Builder.CreateBitCast(value, destType);
43 }
44 
45 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
46 /// block.
47 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
48                                                     const llvm::Twine &Name) {
49   if (!Builder.isNamePreserving())
50     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
51   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
52 }
53 
54 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
55                                      llvm::Value *Init) {
56   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
57   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
58   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
59 }
60 
61 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
62                                                 const llvm::Twine &Name) {
63   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
64   // FIXME: Should we prefer the preferred type alignment here?
65   CharUnits Align = getContext().getTypeAlignInChars(Ty);
66   Alloc->setAlignment(Align.getQuantity());
67   return Alloc;
68 }
69 
70 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
71                                                  const llvm::Twine &Name) {
72   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
73   // FIXME: Should we prefer the preferred type alignment here?
74   CharUnits Align = getContext().getTypeAlignInChars(Ty);
75   Alloc->setAlignment(Align.getQuantity());
76   return Alloc;
77 }
78 
79 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
80 /// expression and compare the result against zero, returning an Int1Ty value.
81 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
82   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
83     llvm::Value *MemPtr = EmitScalarExpr(E);
84     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
85   }
86 
87   QualType BoolTy = getContext().BoolTy;
88   if (!E->getType()->isAnyComplexType())
89     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
90 
91   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
92 }
93 
94 /// EmitIgnoredExpr - Emit code to compute the specified expression,
95 /// ignoring the result.
96 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
97   if (E->isRValue())
98     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
99 
100   // Just emit it as an l-value and drop the result.
101   EmitLValue(E);
102 }
103 
104 /// EmitAnyExpr - Emit code to compute the specified expression which
105 /// can have any type.  The result is returned as an RValue struct.
106 /// If this is an aggregate expression, AggSlot indicates where the
107 /// result should be returned.
108 RValue CodeGenFunction::EmitAnyExpr(const Expr *E, AggValueSlot AggSlot,
109                                     bool IgnoreResult) {
110   if (!hasAggregateLLVMType(E->getType()))
111     return RValue::get(EmitScalarExpr(E, IgnoreResult));
112   else if (E->getType()->isAnyComplexType())
113     return RValue::getComplex(EmitComplexExpr(E, IgnoreResult, IgnoreResult));
114 
115   EmitAggExpr(E, AggSlot, IgnoreResult);
116   return AggSlot.asRValue();
117 }
118 
119 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
120 /// always be accessible even if no aggregate location is provided.
121 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
122   AggValueSlot AggSlot = AggValueSlot::ignored();
123 
124   if (hasAggregateLLVMType(E->getType()) &&
125       !E->getType()->isAnyComplexType())
126     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
127   return EmitAnyExpr(E, AggSlot);
128 }
129 
130 /// EmitAnyExprToMem - Evaluate an expression into a given memory
131 /// location.
132 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
133                                        llvm::Value *Location,
134                                        bool IsLocationVolatile,
135                                        bool IsInit) {
136   if (E->getType()->isComplexType())
137     EmitComplexExprIntoAddr(E, Location, IsLocationVolatile);
138   else if (hasAggregateLLVMType(E->getType()))
139     EmitAggExpr(E, AggValueSlot::forAddr(Location, IsLocationVolatile, IsInit));
140   else {
141     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
142     LValue LV = MakeAddrLValue(Location, E->getType());
143     EmitStoreThroughLValue(RV, LV, E->getType());
144   }
145 }
146 
147 namespace {
148 /// \brief An adjustment to be made to the temporary created when emitting a
149 /// reference binding, which accesses a particular subobject of that temporary.
150   struct SubobjectAdjustment {
151     enum { DerivedToBaseAdjustment, FieldAdjustment } Kind;
152 
153     union {
154       struct {
155         const CastExpr *BasePath;
156         const CXXRecordDecl *DerivedClass;
157       } DerivedToBase;
158 
159       FieldDecl *Field;
160     };
161 
162     SubobjectAdjustment(const CastExpr *BasePath,
163                         const CXXRecordDecl *DerivedClass)
164       : Kind(DerivedToBaseAdjustment) {
165       DerivedToBase.BasePath = BasePath;
166       DerivedToBase.DerivedClass = DerivedClass;
167     }
168 
169     SubobjectAdjustment(FieldDecl *Field)
170       : Kind(FieldAdjustment) {
171       this->Field = Field;
172     }
173   };
174 }
175 
176 static llvm::Value *
177 CreateReferenceTemporary(CodeGenFunction& CGF, QualType Type,
178                          const NamedDecl *InitializedDecl) {
179   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
180     if (VD->hasGlobalStorage()) {
181       llvm::SmallString<256> Name;
182       llvm::raw_svector_ostream Out(Name);
183       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
184       Out.flush();
185 
186       const llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
187 
188       // Create the reference temporary.
189       llvm::GlobalValue *RefTemp =
190         new llvm::GlobalVariable(CGF.CGM.getModule(),
191                                  RefTempTy, /*isConstant=*/false,
192                                  llvm::GlobalValue::InternalLinkage,
193                                  llvm::Constant::getNullValue(RefTempTy),
194                                  Name.str());
195       return RefTemp;
196     }
197   }
198 
199   return CGF.CreateMemTemp(Type, "ref.tmp");
200 }
201 
202 static llvm::Value *
203 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
204                             llvm::Value *&ReferenceTemporary,
205                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
206                             const NamedDecl *InitializedDecl) {
207   if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
208     E = DAE->getExpr();
209 
210   if (const ExprWithCleanups *TE = dyn_cast<ExprWithCleanups>(E)) {
211     CodeGenFunction::RunCleanupsScope Scope(CGF);
212 
213     return EmitExprForReferenceBinding(CGF, TE->getSubExpr(),
214                                        ReferenceTemporary,
215                                        ReferenceTemporaryDtor,
216                                        InitializedDecl);
217   }
218 
219   if (const ObjCPropertyRefExpr *PRE =
220       dyn_cast<ObjCPropertyRefExpr>(E->IgnoreParenImpCasts()))
221     if (PRE->getGetterResultType()->isReferenceType())
222       E = PRE;
223 
224   RValue RV;
225   if (E->isGLValue()) {
226     // Emit the expression as an lvalue.
227     LValue LV = CGF.EmitLValue(E);
228     if (LV.isPropertyRef()) {
229       RV = CGF.EmitLoadOfPropertyRefLValue(LV);
230       return RV.getScalarVal();
231     }
232     if (LV.isSimple())
233       return LV.getAddress();
234 
235     // We have to load the lvalue.
236     RV = CGF.EmitLoadOfLValue(LV, E->getType());
237   } else {
238     QualType ResultTy = E->getType();
239 
240     llvm::SmallVector<SubobjectAdjustment, 2> Adjustments;
241     while (true) {
242       if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
243         E = PE->getSubExpr();
244         continue;
245       }
246 
247       if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
248         if ((CE->getCastKind() == CK_DerivedToBase ||
249              CE->getCastKind() == CK_UncheckedDerivedToBase) &&
250             E->getType()->isRecordType()) {
251           E = CE->getSubExpr();
252           CXXRecordDecl *Derived
253             = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
254           Adjustments.push_back(SubobjectAdjustment(CE, Derived));
255           continue;
256         }
257 
258         if (CE->getCastKind() == CK_NoOp) {
259           E = CE->getSubExpr();
260           continue;
261         }
262       } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
263         if (!ME->isArrow() && ME->getBase()->isRValue()) {
264           assert(ME->getBase()->getType()->isRecordType());
265           if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
266             E = ME->getBase();
267             Adjustments.push_back(SubobjectAdjustment(Field));
268             continue;
269           }
270         }
271       }
272 
273       if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
274         if (opaque->getType()->isRecordType())
275           return CGF.EmitOpaqueValueLValue(opaque).getAddress();
276 
277       // Nothing changed.
278       break;
279     }
280 
281     // Create a reference temporary if necessary.
282     AggValueSlot AggSlot = AggValueSlot::ignored();
283     if (CGF.hasAggregateLLVMType(E->getType()) &&
284         !E->getType()->isAnyComplexType()) {
285       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
286                                                     InitializedDecl);
287       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, false,
288                                       InitializedDecl != 0);
289     }
290 
291     RV = CGF.EmitAnyExpr(E, AggSlot);
292 
293     if (InitializedDecl) {
294       // Get the destructor for the reference temporary.
295       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
296         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
297         if (!ClassDecl->hasTrivialDestructor())
298           ReferenceTemporaryDtor = ClassDecl->getDestructor();
299       }
300     }
301 
302     // Check if need to perform derived-to-base casts and/or field accesses, to
303     // get from the temporary object we created (and, potentially, for which we
304     // extended the lifetime) to the subobject we're binding the reference to.
305     if (!Adjustments.empty()) {
306       llvm::Value *Object = RV.getAggregateAddr();
307       for (unsigned I = Adjustments.size(); I != 0; --I) {
308         SubobjectAdjustment &Adjustment = Adjustments[I-1];
309         switch (Adjustment.Kind) {
310         case SubobjectAdjustment::DerivedToBaseAdjustment:
311           Object =
312               CGF.GetAddressOfBaseClass(Object,
313                                         Adjustment.DerivedToBase.DerivedClass,
314                               Adjustment.DerivedToBase.BasePath->path_begin(),
315                               Adjustment.DerivedToBase.BasePath->path_end(),
316                                         /*NullCheckValue=*/false);
317           break;
318 
319         case SubobjectAdjustment::FieldAdjustment: {
320           LValue LV =
321             CGF.EmitLValueForField(Object, Adjustment.Field, 0);
322           if (LV.isSimple()) {
323             Object = LV.getAddress();
324             break;
325           }
326 
327           // For non-simple lvalues, we actually have to create a copy of
328           // the object we're binding to.
329           QualType T = Adjustment.Field->getType().getNonReferenceType()
330                                                   .getUnqualifiedType();
331           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
332           LValue TempLV = CGF.MakeAddrLValue(Object,
333                                              Adjustment.Field->getType());
334           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV, T), TempLV, T);
335           break;
336         }
337 
338         }
339       }
340 
341       return Object;
342     }
343   }
344 
345   if (RV.isAggregate())
346     return RV.getAggregateAddr();
347 
348   // Create a temporary variable that we can bind the reference to.
349   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
350                                                 InitializedDecl);
351 
352 
353   unsigned Alignment =
354     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
355   if (RV.isScalar())
356     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
357                           /*Volatile=*/false, Alignment, E->getType());
358   else
359     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
360                            /*Volatile=*/false);
361   return ReferenceTemporary;
362 }
363 
364 RValue
365 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
366                                             const NamedDecl *InitializedDecl) {
367   llvm::Value *ReferenceTemporary = 0;
368   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
369   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
370                                                    ReferenceTemporaryDtor,
371                                                    InitializedDecl);
372   if (!ReferenceTemporaryDtor)
373     return RValue::get(Value);
374 
375   // Make sure to call the destructor for the reference temporary.
376   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
377     if (VD->hasGlobalStorage()) {
378       llvm::Constant *DtorFn =
379         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
380       EmitCXXGlobalDtorRegistration(DtorFn,
381                                     cast<llvm::Constant>(ReferenceTemporary));
382 
383       return RValue::get(Value);
384     }
385   }
386 
387   PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
388 
389   return RValue::get(Value);
390 }
391 
392 
393 /// getAccessedFieldNo - Given an encoded value and a result number, return the
394 /// input field number being accessed.
395 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
396                                              const llvm::Constant *Elts) {
397   if (isa<llvm::ConstantAggregateZero>(Elts))
398     return 0;
399 
400   return cast<llvm::ConstantInt>(Elts->getOperand(Idx))->getZExtValue();
401 }
402 
403 void CodeGenFunction::EmitCheck(llvm::Value *Address, unsigned Size) {
404   if (!CatchUndefined)
405     return;
406 
407   // This needs to be to the standard address space.
408   Address = Builder.CreateBitCast(Address, Int8PtrTy);
409 
410   const llvm::Type *IntPtrT = IntPtrTy;
411   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, &IntPtrT, 1);
412 
413   // In time, people may want to control this and use a 1 here.
414   llvm::Value *Arg = Builder.getFalse();
415   llvm::Value *C = Builder.CreateCall2(F, Address, Arg);
416   llvm::BasicBlock *Cont = createBasicBlock();
417   llvm::BasicBlock *Check = createBasicBlock();
418   llvm::Value *NegativeOne = llvm::ConstantInt::get(IntPtrTy, -1ULL);
419   Builder.CreateCondBr(Builder.CreateICmpEQ(C, NegativeOne), Cont, Check);
420 
421   EmitBlock(Check);
422   Builder.CreateCondBr(Builder.CreateICmpUGE(C,
423                                         llvm::ConstantInt::get(IntPtrTy, Size)),
424                        Cont, getTrapBB());
425   EmitBlock(Cont);
426 }
427 
428 
429 CodeGenFunction::ComplexPairTy CodeGenFunction::
430 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
431                          bool isInc, bool isPre) {
432   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
433                                             LV.isVolatileQualified());
434 
435   llvm::Value *NextVal;
436   if (isa<llvm::IntegerType>(InVal.first->getType())) {
437     uint64_t AmountVal = isInc ? 1 : -1;
438     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
439 
440     // Add the inc/dec to the real part.
441     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
442   } else {
443     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
444     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
445     if (!isInc)
446       FVal.changeSign();
447     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
448 
449     // Add the inc/dec to the real part.
450     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
451   }
452 
453   ComplexPairTy IncVal(NextVal, InVal.second);
454 
455   // Store the updated result through the lvalue.
456   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
457 
458   // If this is a postinc, return the value read from memory, otherwise use the
459   // updated value.
460   return isPre ? IncVal : InVal;
461 }
462 
463 
464 //===----------------------------------------------------------------------===//
465 //                         LValue Expression Emission
466 //===----------------------------------------------------------------------===//
467 
468 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
469   if (Ty->isVoidType())
470     return RValue::get(0);
471 
472   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
473     const llvm::Type *EltTy = ConvertType(CTy->getElementType());
474     llvm::Value *U = llvm::UndefValue::get(EltTy);
475     return RValue::getComplex(std::make_pair(U, U));
476   }
477 
478   // If this is a use of an undefined aggregate type, the aggregate must have an
479   // identifiable address.  Just because the contents of the value are undefined
480   // doesn't mean that the address can't be taken and compared.
481   if (hasAggregateLLVMType(Ty)) {
482     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
483     return RValue::getAggregate(DestPtr);
484   }
485 
486   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
487 }
488 
489 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
490                                               const char *Name) {
491   ErrorUnsupported(E, Name);
492   return GetUndefRValue(E->getType());
493 }
494 
495 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
496                                               const char *Name) {
497   ErrorUnsupported(E, Name);
498   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
499   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
500 }
501 
502 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E) {
503   LValue LV = EmitLValue(E);
504   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
505     EmitCheck(LV.getAddress(),
506               getContext().getTypeSizeInChars(E->getType()).getQuantity());
507   return LV;
508 }
509 
510 /// EmitLValue - Emit code to compute a designator that specifies the location
511 /// of the expression.
512 ///
513 /// This can return one of two things: a simple address or a bitfield reference.
514 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
515 /// an LLVM pointer type.
516 ///
517 /// If this returns a bitfield reference, nothing about the pointee type of the
518 /// LLVM value is known: For example, it may not be a pointer to an integer.
519 ///
520 /// If this returns a normal address, and if the lvalue's C type is fixed size,
521 /// this method guarantees that the returned pointer type will point to an LLVM
522 /// type of the same size of the lvalue's type.  If the lvalue has a variable
523 /// length type, this is not possible.
524 ///
525 LValue CodeGenFunction::EmitLValue(const Expr *E) {
526   switch (E->getStmtClass()) {
527   default: return EmitUnsupportedLValue(E, "l-value expression");
528 
529   case Expr::ObjCSelectorExprClass:
530   return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
531   case Expr::ObjCIsaExprClass:
532     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
533   case Expr::BinaryOperatorClass:
534     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
535   case Expr::CompoundAssignOperatorClass:
536     if (!E->getType()->isAnyComplexType())
537       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
538     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
539   case Expr::CallExprClass:
540   case Expr::CXXMemberCallExprClass:
541   case Expr::CXXOperatorCallExprClass:
542     return EmitCallExprLValue(cast<CallExpr>(E));
543   case Expr::VAArgExprClass:
544     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
545   case Expr::DeclRefExprClass:
546     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
547   case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
548   case Expr::PredefinedExprClass:
549     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
550   case Expr::StringLiteralClass:
551     return EmitStringLiteralLValue(cast<StringLiteral>(E));
552   case Expr::ObjCEncodeExprClass:
553     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
554 
555   case Expr::BlockDeclRefExprClass:
556     return EmitBlockDeclRefLValue(cast<BlockDeclRefExpr>(E));
557 
558   case Expr::CXXTemporaryObjectExprClass:
559   case Expr::CXXConstructExprClass:
560     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
561   case Expr::CXXBindTemporaryExprClass:
562     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
563   case Expr::ExprWithCleanupsClass:
564     return EmitExprWithCleanupsLValue(cast<ExprWithCleanups>(E));
565   case Expr::CXXScalarValueInitExprClass:
566     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
567   case Expr::CXXDefaultArgExprClass:
568     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
569   case Expr::CXXTypeidExprClass:
570     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
571 
572   case Expr::ObjCMessageExprClass:
573     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
574   case Expr::ObjCIvarRefExprClass:
575     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
576   case Expr::ObjCPropertyRefExprClass:
577     return EmitObjCPropertyRefLValue(cast<ObjCPropertyRefExpr>(E));
578   case Expr::StmtExprClass:
579     return EmitStmtExprLValue(cast<StmtExpr>(E));
580   case Expr::UnaryOperatorClass:
581     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
582   case Expr::ArraySubscriptExprClass:
583     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
584   case Expr::ExtVectorElementExprClass:
585     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
586   case Expr::MemberExprClass:
587     return EmitMemberExpr(cast<MemberExpr>(E));
588   case Expr::CompoundLiteralExprClass:
589     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
590   case Expr::ConditionalOperatorClass:
591     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
592   case Expr::BinaryConditionalOperatorClass:
593     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
594   case Expr::ChooseExprClass:
595     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
596   case Expr::OpaqueValueExprClass:
597     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
598   case Expr::ImplicitCastExprClass:
599   case Expr::CStyleCastExprClass:
600   case Expr::CXXFunctionalCastExprClass:
601   case Expr::CXXStaticCastExprClass:
602   case Expr::CXXDynamicCastExprClass:
603   case Expr::CXXReinterpretCastExprClass:
604   case Expr::CXXConstCastExprClass:
605     return EmitCastLValue(cast<CastExpr>(E));
606   }
607 }
608 
609 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
610                                               unsigned Alignment, QualType Ty,
611                                               llvm::MDNode *TBAAInfo) {
612   llvm::LoadInst *Load = Builder.CreateLoad(Addr, "tmp");
613   if (Volatile)
614     Load->setVolatile(true);
615   if (Alignment)
616     Load->setAlignment(Alignment);
617   if (TBAAInfo)
618     CGM.DecorateInstruction(Load, TBAAInfo);
619 
620   return EmitFromMemory(Load, Ty);
621 }
622 
623 static bool isBooleanUnderlyingType(QualType Ty) {
624   if (const EnumType *ET = dyn_cast<EnumType>(Ty))
625     return ET->getDecl()->getIntegerType()->isBooleanType();
626   return false;
627 }
628 
629 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
630   // Bool has a different representation in memory than in registers.
631   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
632     // This should really always be an i1, but sometimes it's already
633     // an i8, and it's awkward to track those cases down.
634     if (Value->getType()->isIntegerTy(1))
635       return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
636     assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
637   }
638 
639   return Value;
640 }
641 
642 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
643   // Bool has a different representation in memory than in registers.
644   if (Ty->isBooleanType() || isBooleanUnderlyingType(Ty)) {
645     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
646     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
647   }
648 
649   return Value;
650 }
651 
652 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
653                                         bool Volatile, unsigned Alignment,
654                                         QualType Ty,
655                                         llvm::MDNode *TBAAInfo) {
656   Value = EmitToMemory(Value, Ty);
657   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
658   if (Alignment)
659     Store->setAlignment(Alignment);
660   if (TBAAInfo)
661     CGM.DecorateInstruction(Store, TBAAInfo);
662 }
663 
664 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
665 /// method emits the address of the lvalue, then loads the result as an rvalue,
666 /// returning the rvalue.
667 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
668   if (LV.isObjCWeak()) {
669     // load of a __weak object.
670     llvm::Value *AddrWeakObj = LV.getAddress();
671     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
672                                                              AddrWeakObj));
673   }
674 
675   if (LV.isSimple()) {
676     llvm::Value *Ptr = LV.getAddress();
677 
678     // Functions are l-values that don't require loading.
679     if (ExprType->isFunctionType())
680       return RValue::get(Ptr);
681 
682     // Everything needs a load.
683     return RValue::get(EmitLoadOfScalar(Ptr, LV.isVolatileQualified(),
684                                         LV.getAlignment(), ExprType,
685                                         LV.getTBAAInfo()));
686 
687   }
688 
689   if (LV.isVectorElt()) {
690     llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(),
691                                           LV.isVolatileQualified(), "tmp");
692     return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
693                                                     "vecext"));
694   }
695 
696   // If this is a reference to a subset of the elements of a vector, either
697   // shuffle the input or extract/insert them as appropriate.
698   if (LV.isExtVectorElt())
699     return EmitLoadOfExtVectorElementLValue(LV, ExprType);
700 
701   if (LV.isBitField())
702     return EmitLoadOfBitfieldLValue(LV, ExprType);
703 
704   assert(LV.isPropertyRef() && "Unknown LValue type!");
705   return EmitLoadOfPropertyRefLValue(LV);
706 }
707 
708 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
709                                                  QualType ExprType) {
710   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
711 
712   // Get the output type.
713   const llvm::Type *ResLTy = ConvertType(ExprType);
714   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
715 
716   // Compute the result as an OR of all of the individual component accesses.
717   llvm::Value *Res = 0;
718   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
719     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
720 
721     // Get the field pointer.
722     llvm::Value *Ptr = LV.getBitFieldBaseAddr();
723 
724     // Only offset by the field index if used, so that incoming values are not
725     // required to be structures.
726     if (AI.FieldIndex)
727       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
728 
729     // Offset by the byte offset, if used.
730     if (AI.FieldByteOffset) {
731       Ptr = EmitCastToVoidPtr(Ptr);
732       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
733     }
734 
735     // Cast to the access type.
736     const llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(),
737                                                      AI.AccessWidth,
738                               CGM.getContext().getTargetAddressSpace(ExprType));
739     Ptr = Builder.CreateBitCast(Ptr, PTy);
740 
741     // Perform the load.
742     llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
743     if (AI.AccessAlignment)
744       Load->setAlignment(AI.AccessAlignment);
745 
746     // Shift out unused low bits and mask out unused high bits.
747     llvm::Value *Val = Load;
748     if (AI.FieldBitStart)
749       Val = Builder.CreateLShr(Load, AI.FieldBitStart);
750     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
751                                                             AI.TargetBitWidth),
752                             "bf.clear");
753 
754     // Extend or truncate to the target size.
755     if (AI.AccessWidth < ResSizeInBits)
756       Val = Builder.CreateZExt(Val, ResLTy);
757     else if (AI.AccessWidth > ResSizeInBits)
758       Val = Builder.CreateTrunc(Val, ResLTy);
759 
760     // Shift into place, and OR into the result.
761     if (AI.TargetBitOffset)
762       Val = Builder.CreateShl(Val, AI.TargetBitOffset);
763     Res = Res ? Builder.CreateOr(Res, Val) : Val;
764   }
765 
766   // If the bit-field is signed, perform the sign-extension.
767   //
768   // FIXME: This can easily be folded into the load of the high bits, which
769   // could also eliminate the mask of high bits in some situations.
770   if (Info.isSigned()) {
771     unsigned ExtraBits = ResSizeInBits - Info.getSize();
772     if (ExtraBits)
773       Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
774                                ExtraBits, "bf.val.sext");
775   }
776 
777   return RValue::get(Res);
778 }
779 
780 // If this is a reference to a subset of the elements of a vector, create an
781 // appropriate shufflevector.
782 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV,
783                                                          QualType ExprType) {
784   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddr(),
785                                         LV.isVolatileQualified(), "tmp");
786 
787   const llvm::Constant *Elts = LV.getExtVectorElts();
788 
789   // If the result of the expression is a non-vector type, we must be extracting
790   // a single element.  Just codegen as an extractelement.
791   const VectorType *ExprVT = ExprType->getAs<VectorType>();
792   if (!ExprVT) {
793     unsigned InIdx = getAccessedFieldNo(0, Elts);
794     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
795     return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
796   }
797 
798   // Always use shuffle vector to try to retain the original program structure
799   unsigned NumResultElts = ExprVT->getNumElements();
800 
801   llvm::SmallVector<llvm::Constant*, 4> Mask;
802   for (unsigned i = 0; i != NumResultElts; ++i) {
803     unsigned InIdx = getAccessedFieldNo(i, Elts);
804     Mask.push_back(llvm::ConstantInt::get(Int32Ty, InIdx));
805   }
806 
807   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
808   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
809                                     MaskV, "tmp");
810   return RValue::get(Vec);
811 }
812 
813 
814 
815 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
816 /// lvalue, where both are guaranteed to the have the same type, and that type
817 /// is 'Ty'.
818 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
819                                              QualType Ty) {
820   if (!Dst.isSimple()) {
821     if (Dst.isVectorElt()) {
822       // Read/modify/write the vector, inserting the new element.
823       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(),
824                                             Dst.isVolatileQualified(), "tmp");
825       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
826                                         Dst.getVectorIdx(), "vecins");
827       Builder.CreateStore(Vec, Dst.getVectorAddr(),Dst.isVolatileQualified());
828       return;
829     }
830 
831     // If this is an update of extended vector elements, insert them as
832     // appropriate.
833     if (Dst.isExtVectorElt())
834       return EmitStoreThroughExtVectorComponentLValue(Src, Dst, Ty);
835 
836     if (Dst.isBitField())
837       return EmitStoreThroughBitfieldLValue(Src, Dst, Ty);
838 
839     assert(Dst.isPropertyRef() && "Unknown LValue type");
840     return EmitStoreThroughPropertyRefLValue(Src, Dst);
841   }
842 
843   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
844     // load of a __weak object.
845     llvm::Value *LvalueDst = Dst.getAddress();
846     llvm::Value *src = Src.getScalarVal();
847      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
848     return;
849   }
850 
851   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
852     // load of a __strong object.
853     llvm::Value *LvalueDst = Dst.getAddress();
854     llvm::Value *src = Src.getScalarVal();
855     if (Dst.isObjCIvar()) {
856       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
857       const llvm::Type *ResultType = ConvertType(getContext().LongTy);
858       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
859       llvm::Value *dst = RHS;
860       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
861       llvm::Value *LHS =
862         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
863       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
864       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
865                                               BytesBetween);
866     } else if (Dst.isGlobalObjCRef()) {
867       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
868                                                 Dst.isThreadLocalRef());
869     }
870     else
871       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
872     return;
873   }
874 
875   assert(Src.isScalar() && "Can't emit an agg store with this method");
876   EmitStoreOfScalar(Src.getScalarVal(), Dst.getAddress(),
877                     Dst.isVolatileQualified(), Dst.getAlignment(), Ty,
878                     Dst.getTBAAInfo());
879 }
880 
881 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
882                                                      QualType Ty,
883                                                      llvm::Value **Result) {
884   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
885 
886   // Get the output type.
887   const llvm::Type *ResLTy = ConvertTypeForMem(Ty);
888   unsigned ResSizeInBits = CGM.getTargetData().getTypeSizeInBits(ResLTy);
889 
890   // Get the source value, truncated to the width of the bit-field.
891   llvm::Value *SrcVal = Src.getScalarVal();
892 
893   if (Ty->isBooleanType())
894     SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
895 
896   SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
897                                                                 Info.getSize()),
898                              "bf.value");
899 
900   // Return the new value of the bit-field, if requested.
901   if (Result) {
902     // Cast back to the proper type for result.
903     const llvm::Type *SrcTy = Src.getScalarVal()->getType();
904     llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
905                                                    "bf.reload.val");
906 
907     // Sign extend if necessary.
908     if (Info.isSigned()) {
909       unsigned ExtraBits = ResSizeInBits - Info.getSize();
910       if (ExtraBits)
911         ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
912                                        ExtraBits, "bf.reload.sext");
913     }
914 
915     *Result = ReloadVal;
916   }
917 
918   // Iterate over the components, writing each piece to memory.
919   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
920     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
921 
922     // Get the field pointer.
923     llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
924     unsigned addressSpace =
925       cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
926 
927     // Only offset by the field index if used, so that incoming values are not
928     // required to be structures.
929     if (AI.FieldIndex)
930       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
931 
932     // Offset by the byte offset, if used.
933     if (AI.FieldByteOffset) {
934       Ptr = EmitCastToVoidPtr(Ptr);
935       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset,"bf.field.offs");
936     }
937 
938     // Cast to the access type.
939     const llvm::Type *AccessLTy =
940       llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
941 
942     const llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
943     Ptr = Builder.CreateBitCast(Ptr, PTy);
944 
945     // Extract the piece of the bit-field value to write in this access, limited
946     // to the values that are part of this access.
947     llvm::Value *Val = SrcVal;
948     if (AI.TargetBitOffset)
949       Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
950     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
951                                                             AI.TargetBitWidth));
952 
953     // Extend or truncate to the access size.
954     if (ResSizeInBits < AI.AccessWidth)
955       Val = Builder.CreateZExt(Val, AccessLTy);
956     else if (ResSizeInBits > AI.AccessWidth)
957       Val = Builder.CreateTrunc(Val, AccessLTy);
958 
959     // Shift into the position in memory.
960     if (AI.FieldBitStart)
961       Val = Builder.CreateShl(Val, AI.FieldBitStart);
962 
963     // If necessary, load and OR in bits that are outside of the bit-field.
964     if (AI.TargetBitWidth != AI.AccessWidth) {
965       llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
966       if (AI.AccessAlignment)
967         Load->setAlignment(AI.AccessAlignment);
968 
969       // Compute the mask for zeroing the bits that are part of the bit-field.
970       llvm::APInt InvMask =
971         ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
972                                  AI.FieldBitStart + AI.TargetBitWidth);
973 
974       // Apply the mask and OR in to the value to write.
975       Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
976     }
977 
978     // Write the value.
979     llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
980                                                  Dst.isVolatileQualified());
981     if (AI.AccessAlignment)
982       Store->setAlignment(AI.AccessAlignment);
983   }
984 }
985 
986 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
987                                                                LValue Dst,
988                                                                QualType Ty) {
989   // This access turns into a read/modify/write of the vector.  Load the input
990   // value now.
991   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddr(),
992                                         Dst.isVolatileQualified(), "tmp");
993   const llvm::Constant *Elts = Dst.getExtVectorElts();
994 
995   llvm::Value *SrcVal = Src.getScalarVal();
996 
997   if (const VectorType *VTy = Ty->getAs<VectorType>()) {
998     unsigned NumSrcElts = VTy->getNumElements();
999     unsigned NumDstElts =
1000        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1001     if (NumDstElts == NumSrcElts) {
1002       // Use shuffle vector is the src and destination are the same number of
1003       // elements and restore the vector mask since it is on the side it will be
1004       // stored.
1005       llvm::SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1006       for (unsigned i = 0; i != NumSrcElts; ++i) {
1007         unsigned InIdx = getAccessedFieldNo(i, Elts);
1008         Mask[InIdx] = llvm::ConstantInt::get(Int32Ty, i);
1009       }
1010 
1011       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1012       Vec = Builder.CreateShuffleVector(SrcVal,
1013                                         llvm::UndefValue::get(Vec->getType()),
1014                                         MaskV, "tmp");
1015     } else if (NumDstElts > NumSrcElts) {
1016       // Extended the source vector to the same length and then shuffle it
1017       // into the destination.
1018       // FIXME: since we're shuffling with undef, can we just use the indices
1019       //        into that?  This could be simpler.
1020       llvm::SmallVector<llvm::Constant*, 4> ExtMask;
1021       unsigned i;
1022       for (i = 0; i != NumSrcElts; ++i)
1023         ExtMask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1024       for (; i != NumDstElts; ++i)
1025         ExtMask.push_back(llvm::UndefValue::get(Int32Ty));
1026       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1027       llvm::Value *ExtSrcVal =
1028         Builder.CreateShuffleVector(SrcVal,
1029                                     llvm::UndefValue::get(SrcVal->getType()),
1030                                     ExtMaskV, "tmp");
1031       // build identity
1032       llvm::SmallVector<llvm::Constant*, 4> Mask;
1033       for (unsigned i = 0; i != NumDstElts; ++i)
1034         Mask.push_back(llvm::ConstantInt::get(Int32Ty, i));
1035 
1036       // modify when what gets shuffled in
1037       for (unsigned i = 0; i != NumSrcElts; ++i) {
1038         unsigned Idx = getAccessedFieldNo(i, Elts);
1039         Mask[Idx] = llvm::ConstantInt::get(Int32Ty, i+NumDstElts);
1040       }
1041       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1042       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV, "tmp");
1043     } else {
1044       // We should never shorten the vector
1045       assert(0 && "unexpected shorten vector length");
1046     }
1047   } else {
1048     // If the Src is a scalar (not a vector) it must be updating one element.
1049     unsigned InIdx = getAccessedFieldNo(0, Elts);
1050     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1051     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
1052   }
1053 
1054   Builder.CreateStore(Vec, Dst.getExtVectorAddr(), Dst.isVolatileQualified());
1055 }
1056 
1057 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1058 // generating write-barries API. It is currently a global, ivar,
1059 // or neither.
1060 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1061                                  LValue &LV) {
1062   if (Ctx.getLangOptions().getGCMode() == LangOptions::NonGC)
1063     return;
1064 
1065   if (isa<ObjCIvarRefExpr>(E)) {
1066     LV.setObjCIvar(true);
1067     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1068     LV.setBaseIvarExp(Exp->getBase());
1069     LV.setObjCArray(E->getType()->isArrayType());
1070     return;
1071   }
1072 
1073   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1074     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1075       if (VD->hasGlobalStorage()) {
1076         LV.setGlobalObjCRef(true);
1077         LV.setThreadLocalRef(VD->isThreadSpecified());
1078       }
1079     }
1080     LV.setObjCArray(E->getType()->isArrayType());
1081     return;
1082   }
1083 
1084   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1085     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1086     return;
1087   }
1088 
1089   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1090     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1091     if (LV.isObjCIvar()) {
1092       // If cast is to a structure pointer, follow gcc's behavior and make it
1093       // a non-ivar write-barrier.
1094       QualType ExpTy = E->getType();
1095       if (ExpTy->isPointerType())
1096         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1097       if (ExpTy->isRecordType())
1098         LV.setObjCIvar(false);
1099     }
1100     return;
1101   }
1102   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1103     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1104     return;
1105   }
1106 
1107   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1108     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV);
1109     return;
1110   }
1111 
1112   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1113     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1114     if (LV.isObjCIvar() && !LV.isObjCArray())
1115       // Using array syntax to assigning to what an ivar points to is not
1116       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1117       LV.setObjCIvar(false);
1118     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1119       // Using array syntax to assigning to what global points to is not
1120       // same as assigning to the global itself. {id *G;} G[i] = 0;
1121       LV.setGlobalObjCRef(false);
1122     return;
1123   }
1124 
1125   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1126     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1127     // We don't know if member is an 'ivar', but this flag is looked at
1128     // only in the context of LV.isObjCIvar().
1129     LV.setObjCArray(E->getType()->isArrayType());
1130     return;
1131   }
1132 }
1133 
1134 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1135                                       const Expr *E, const VarDecl *VD) {
1136   assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1137          "Var decl must have external storage or be a file var decl!");
1138 
1139   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1140   if (VD->getType()->isReferenceType())
1141     V = CGF.Builder.CreateLoad(V, "tmp");
1142   unsigned Alignment = CGF.getContext().getDeclAlign(VD).getQuantity();
1143   LValue LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1144   setObjCGCLValueClass(CGF.getContext(), E, LV);
1145   return LV;
1146 }
1147 
1148 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1149                                       const Expr *E, const FunctionDecl *FD) {
1150   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1151   if (!FD->hasPrototype()) {
1152     if (const FunctionProtoType *Proto =
1153             FD->getType()->getAs<FunctionProtoType>()) {
1154       // Ugly case: for a K&R-style definition, the type of the definition
1155       // isn't the same as the type of a use.  Correct for this with a
1156       // bitcast.
1157       QualType NoProtoType =
1158           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1159       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1160       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType), "tmp");
1161     }
1162   }
1163   unsigned Alignment = CGF.getContext().getDeclAlign(FD).getQuantity();
1164   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1165 }
1166 
1167 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1168   const NamedDecl *ND = E->getDecl();
1169   unsigned Alignment = getContext().getDeclAlign(ND).getQuantity();
1170 
1171   if (ND->hasAttr<WeakRefAttr>()) {
1172     const ValueDecl *VD = cast<ValueDecl>(ND);
1173     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1174     return MakeAddrLValue(Aliasee, E->getType(), Alignment);
1175   }
1176 
1177   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1178 
1179     // Check if this is a global variable.
1180     if (VD->hasExternalStorage() || VD->isFileVarDecl())
1181       return EmitGlobalVarDeclLValue(*this, E, VD);
1182 
1183     bool NonGCable = VD->hasLocalStorage() &&
1184                      !VD->getType()->isReferenceType() &&
1185                      !VD->hasAttr<BlocksAttr>();
1186 
1187     llvm::Value *V = LocalDeclMap[VD];
1188     if (!V && VD->isStaticLocal())
1189       V = CGM.getStaticLocalDeclAddress(VD);
1190     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1191 
1192     if (VD->hasAttr<BlocksAttr>())
1193       V = BuildBlockByrefAddress(V, VD);
1194 
1195     if (VD->getType()->isReferenceType())
1196       V = Builder.CreateLoad(V, "tmp");
1197 
1198     LValue LV = MakeAddrLValue(V, E->getType(), Alignment);
1199     if (NonGCable) {
1200       LV.getQuals().removeObjCGCAttr();
1201       LV.setNonGC(true);
1202     }
1203     setObjCGCLValueClass(getContext(), E, LV);
1204     return LV;
1205   }
1206 
1207   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1208     return EmitFunctionDeclLValue(*this, E, fn);
1209 
1210   assert(false && "Unhandled DeclRefExpr");
1211 
1212   // an invalid LValue, but the assert will
1213   // ensure that this point is never reached.
1214   return LValue();
1215 }
1216 
1217 LValue CodeGenFunction::EmitBlockDeclRefLValue(const BlockDeclRefExpr *E) {
1218   unsigned Alignment =
1219     getContext().getDeclAlign(E->getDecl()).getQuantity();
1220   return MakeAddrLValue(GetAddrOfBlockDecl(E), E->getType(), Alignment);
1221 }
1222 
1223 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1224   // __extension__ doesn't affect lvalue-ness.
1225   if (E->getOpcode() == UO_Extension)
1226     return EmitLValue(E->getSubExpr());
1227 
1228   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1229   switch (E->getOpcode()) {
1230   default: assert(0 && "Unknown unary operator lvalue!");
1231   case UO_Deref: {
1232     QualType T = E->getSubExpr()->getType()->getPointeeType();
1233     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1234 
1235     LValue LV = MakeAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1236     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1237 
1238     // We should not generate __weak write barrier on indirect reference
1239     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1240     // But, we continue to generate __strong write barrier on indirect write
1241     // into a pointer to object.
1242     if (getContext().getLangOptions().ObjC1 &&
1243         getContext().getLangOptions().getGCMode() != LangOptions::NonGC &&
1244         LV.isObjCWeak())
1245       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1246     return LV;
1247   }
1248   case UO_Real:
1249   case UO_Imag: {
1250     LValue LV = EmitLValue(E->getSubExpr());
1251     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1252     llvm::Value *Addr = LV.getAddress();
1253 
1254     // real and imag are valid on scalars.  This is a faster way of
1255     // testing that.
1256     if (!cast<llvm::PointerType>(Addr->getType())
1257            ->getElementType()->isStructTy()) {
1258       assert(E->getSubExpr()->getType()->isArithmeticType());
1259       return LV;
1260     }
1261 
1262     assert(E->getSubExpr()->getType()->isAnyComplexType());
1263 
1264     unsigned Idx = E->getOpcode() == UO_Imag;
1265     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1266                                                   Idx, "idx"),
1267                           ExprTy);
1268   }
1269   case UO_PreInc:
1270   case UO_PreDec: {
1271     LValue LV = EmitLValue(E->getSubExpr());
1272     bool isInc = E->getOpcode() == UO_PreInc;
1273 
1274     if (E->getType()->isAnyComplexType())
1275       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1276     else
1277       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1278     return LV;
1279   }
1280   }
1281 }
1282 
1283 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1284   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1285                         E->getType());
1286 }
1287 
1288 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1289   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1290                         E->getType());
1291 }
1292 
1293 
1294 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1295   switch (E->getIdentType()) {
1296   default:
1297     return EmitUnsupportedLValue(E, "predefined expression");
1298 
1299   case PredefinedExpr::Func:
1300   case PredefinedExpr::Function:
1301   case PredefinedExpr::PrettyFunction: {
1302     unsigned Type = E->getIdentType();
1303     std::string GlobalVarName;
1304 
1305     switch (Type) {
1306     default: assert(0 && "Invalid type");
1307     case PredefinedExpr::Func:
1308       GlobalVarName = "__func__.";
1309       break;
1310     case PredefinedExpr::Function:
1311       GlobalVarName = "__FUNCTION__.";
1312       break;
1313     case PredefinedExpr::PrettyFunction:
1314       GlobalVarName = "__PRETTY_FUNCTION__.";
1315       break;
1316     }
1317 
1318     llvm::StringRef FnName = CurFn->getName();
1319     if (FnName.startswith("\01"))
1320       FnName = FnName.substr(1);
1321     GlobalVarName += FnName;
1322 
1323     const Decl *CurDecl = CurCodeDecl;
1324     if (CurDecl == 0)
1325       CurDecl = getContext().getTranslationUnitDecl();
1326 
1327     std::string FunctionName =
1328         (isa<BlockDecl>(CurDecl)
1329          ? FnName.str()
1330          : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)Type, CurDecl));
1331 
1332     llvm::Constant *C =
1333       CGM.GetAddrOfConstantCString(FunctionName, GlobalVarName.c_str());
1334     return MakeAddrLValue(C, E->getType());
1335   }
1336   }
1337 }
1338 
1339 llvm::BasicBlock *CodeGenFunction::getTrapBB() {
1340   const CodeGenOptions &GCO = CGM.getCodeGenOpts();
1341 
1342   // If we are not optimzing, don't collapse all calls to trap in the function
1343   // to the same call, that way, in the debugger they can see which operation
1344   // did in fact fail.  If we are optimizing, we collapse all calls to trap down
1345   // to just one per function to save on codesize.
1346   if (GCO.OptimizationLevel && TrapBB)
1347     return TrapBB;
1348 
1349   llvm::BasicBlock *Cont = 0;
1350   if (HaveInsertPoint()) {
1351     Cont = createBasicBlock("cont");
1352     EmitBranch(Cont);
1353   }
1354   TrapBB = createBasicBlock("trap");
1355   EmitBlock(TrapBB);
1356 
1357   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap, 0, 0);
1358   llvm::CallInst *TrapCall = Builder.CreateCall(F);
1359   TrapCall->setDoesNotReturn();
1360   TrapCall->setDoesNotThrow();
1361   Builder.CreateUnreachable();
1362 
1363   if (Cont)
1364     EmitBlock(Cont);
1365   return TrapBB;
1366 }
1367 
1368 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
1369 /// array to pointer, return the array subexpression.
1370 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
1371   // If this isn't just an array->pointer decay, bail out.
1372   const CastExpr *CE = dyn_cast<CastExpr>(E);
1373   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
1374     return 0;
1375 
1376   // If this is a decay from variable width array, bail out.
1377   const Expr *SubExpr = CE->getSubExpr();
1378   if (SubExpr->getType()->isVariableArrayType())
1379     return 0;
1380 
1381   return SubExpr;
1382 }
1383 
1384 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1385   // The index must always be an integer, which is not an aggregate.  Emit it.
1386   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
1387   QualType IdxTy  = E->getIdx()->getType();
1388   bool IdxSigned = IdxTy->isSignedIntegerType();
1389 
1390   // If the base is a vector type, then we are forming a vector element lvalue
1391   // with this subscript.
1392   if (E->getBase()->getType()->isVectorType()) {
1393     // Emit the vector as an lvalue to get its address.
1394     LValue LHS = EmitLValue(E->getBase());
1395     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
1396     Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
1397     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
1398                                  E->getBase()->getType().getCVRQualifiers());
1399   }
1400 
1401   // Extend or truncate the index type to 32 or 64-bits.
1402   if (Idx->getType() != IntPtrTy)
1403     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
1404 
1405   // FIXME: As llvm implements the object size checking, this can come out.
1406   if (CatchUndefined) {
1407     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E->getBase())){
1408       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1409         if (ICE->getCastKind() == CK_ArrayToPointerDecay) {
1410           if (const ConstantArrayType *CAT
1411               = getContext().getAsConstantArrayType(DRE->getType())) {
1412             llvm::APInt Size = CAT->getSize();
1413             llvm::BasicBlock *Cont = createBasicBlock("cont");
1414             Builder.CreateCondBr(Builder.CreateICmpULE(Idx,
1415                                   llvm::ConstantInt::get(Idx->getType(), Size)),
1416                                  Cont, getTrapBB());
1417             EmitBlock(Cont);
1418           }
1419         }
1420       }
1421     }
1422   }
1423 
1424   // We know that the pointer points to a type of the correct size, unless the
1425   // size is a VLA or Objective-C interface.
1426   llvm::Value *Address = 0;
1427   unsigned ArrayAlignment = 0;
1428   if (const VariableArrayType *VAT =
1429         getContext().getAsVariableArrayType(E->getType())) {
1430     llvm::Value *VLASize = GetVLASize(VAT);
1431 
1432     Idx = Builder.CreateMul(Idx, VLASize);
1433 
1434     // The base must be a pointer, which is not an aggregate.  Emit it.
1435     llvm::Value *Base = EmitScalarExpr(E->getBase());
1436 
1437     Address = EmitCastToVoidPtr(Base);
1438     if (getContext().getLangOptions().isSignedOverflowDefined())
1439       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1440     else
1441       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
1442     Address = Builder.CreateBitCast(Address, Base->getType());
1443   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
1444     // Indexing over an interface, as in "NSString *P; P[4];"
1445     llvm::Value *InterfaceSize =
1446       llvm::ConstantInt::get(Idx->getType(),
1447           getContext().getTypeSizeInChars(OIT).getQuantity());
1448 
1449     Idx = Builder.CreateMul(Idx, InterfaceSize);
1450 
1451     // The base must be a pointer, which is not an aggregate.  Emit it.
1452     llvm::Value *Base = EmitScalarExpr(E->getBase());
1453     Address = EmitCastToVoidPtr(Base);
1454     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
1455     Address = Builder.CreateBitCast(Address, Base->getType());
1456   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
1457     // If this is A[i] where A is an array, the frontend will have decayed the
1458     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
1459     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
1460     // "gep x, i" here.  Emit one "gep A, 0, i".
1461     assert(Array->getType()->isArrayType() &&
1462            "Array to pointer decay must have array source type!");
1463     LValue ArrayLV = EmitLValue(Array);
1464     llvm::Value *ArrayPtr = ArrayLV.getAddress();
1465     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
1466     llvm::Value *Args[] = { Zero, Idx };
1467 
1468     // Propagate the alignment from the array itself to the result.
1469     ArrayAlignment = ArrayLV.getAlignment();
1470 
1471     if (getContext().getLangOptions().isSignedOverflowDefined())
1472       Address = Builder.CreateGEP(ArrayPtr, Args, Args+2, "arrayidx");
1473     else
1474       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, Args+2, "arrayidx");
1475   } else {
1476     // The base must be a pointer, which is not an aggregate.  Emit it.
1477     llvm::Value *Base = EmitScalarExpr(E->getBase());
1478     if (getContext().getLangOptions().isSignedOverflowDefined())
1479       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
1480     else
1481       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
1482   }
1483 
1484   QualType T = E->getBase()->getType()->getPointeeType();
1485   assert(!T.isNull() &&
1486          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
1487 
1488   // Limit the alignment to that of the result type.
1489   if (ArrayAlignment) {
1490     unsigned Align = getContext().getTypeAlignInChars(T).getQuantity();
1491     ArrayAlignment = std::min(Align, ArrayAlignment);
1492   }
1493 
1494   LValue LV = MakeAddrLValue(Address, T, ArrayAlignment);
1495   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
1496 
1497   if (getContext().getLangOptions().ObjC1 &&
1498       getContext().getLangOptions().getGCMode() != LangOptions::NonGC) {
1499     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1500     setObjCGCLValueClass(getContext(), E, LV);
1501   }
1502   return LV;
1503 }
1504 
1505 static
1506 llvm::Constant *GenerateConstantVector(llvm::LLVMContext &VMContext,
1507                                        llvm::SmallVector<unsigned, 4> &Elts) {
1508   llvm::SmallVector<llvm::Constant*, 4> CElts;
1509 
1510   const llvm::Type *Int32Ty = llvm::Type::getInt32Ty(VMContext);
1511   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
1512     CElts.push_back(llvm::ConstantInt::get(Int32Ty, Elts[i]));
1513 
1514   return llvm::ConstantVector::get(CElts);
1515 }
1516 
1517 LValue CodeGenFunction::
1518 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
1519   // Emit the base vector as an l-value.
1520   LValue Base;
1521 
1522   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1523   if (E->isArrow()) {
1524     // If it is a pointer to a vector, emit the address and form an lvalue with
1525     // it.
1526     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
1527     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
1528     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
1529     Base.getQuals().removeObjCGCAttr();
1530   } else if (E->getBase()->isGLValue()) {
1531     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1532     // emit the base as an lvalue.
1533     assert(E->getBase()->getType()->isVectorType());
1534     Base = EmitLValue(E->getBase());
1535   } else {
1536     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1537     assert(E->getBase()->getType()->getAs<VectorType>() &&
1538            "Result must be a vector");
1539     llvm::Value *Vec = EmitScalarExpr(E->getBase());
1540 
1541     // Store the vector to memory (because LValue wants an address).
1542     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
1543     Builder.CreateStore(Vec, VecMem);
1544     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
1545   }
1546 
1547   // Encode the element access list into a vector of unsigned indices.
1548   llvm::SmallVector<unsigned, 4> Indices;
1549   E->getEncodedElementAccess(Indices);
1550 
1551   if (Base.isSimple()) {
1552     llvm::Constant *CV = GenerateConstantVector(getLLVMContext(), Indices);
1553     return LValue::MakeExtVectorElt(Base.getAddress(), CV,
1554                                     Base.getVRQualifiers());
1555   }
1556   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1557 
1558   llvm::Constant *BaseElts = Base.getExtVectorElts();
1559   llvm::SmallVector<llvm::Constant *, 4> CElts;
1560 
1561   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1562     if (isa<llvm::ConstantAggregateZero>(BaseElts))
1563       CElts.push_back(llvm::ConstantInt::get(Int32Ty, 0));
1564     else
1565       CElts.push_back(cast<llvm::Constant>(BaseElts->getOperand(Indices[i])));
1566   }
1567   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
1568   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV,
1569                                   Base.getVRQualifiers());
1570 }
1571 
1572 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
1573   bool isNonGC = false;
1574   Expr *BaseExpr = E->getBase();
1575   llvm::Value *BaseValue = NULL;
1576   Qualifiers BaseQuals;
1577 
1578   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
1579   if (E->isArrow()) {
1580     BaseValue = EmitScalarExpr(BaseExpr);
1581     const PointerType *PTy =
1582       BaseExpr->getType()->getAs<PointerType>();
1583     BaseQuals = PTy->getPointeeType().getQualifiers();
1584   } else {
1585     LValue BaseLV = EmitLValue(BaseExpr);
1586     if (BaseLV.isNonGC())
1587       isNonGC = true;
1588     // FIXME: this isn't right for bitfields.
1589     BaseValue = BaseLV.getAddress();
1590     QualType BaseTy = BaseExpr->getType();
1591     BaseQuals = BaseTy.getQualifiers();
1592   }
1593 
1594   NamedDecl *ND = E->getMemberDecl();
1595   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
1596     LValue LV = EmitLValueForField(BaseValue, Field,
1597                                    BaseQuals.getCVRQualifiers());
1598     LV.setNonGC(isNonGC);
1599     setObjCGCLValueClass(getContext(), E, LV);
1600     return LV;
1601   }
1602 
1603   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
1604     return EmitGlobalVarDeclLValue(*this, E, VD);
1605 
1606   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
1607     return EmitFunctionDeclLValue(*this, E, FD);
1608 
1609   assert(false && "Unhandled member declaration!");
1610   return LValue();
1611 }
1612 
1613 LValue CodeGenFunction::EmitLValueForBitfield(llvm::Value *BaseValue,
1614                                               const FieldDecl *Field,
1615                                               unsigned CVRQualifiers) {
1616   const CGRecordLayout &RL =
1617     CGM.getTypes().getCGRecordLayout(Field->getParent());
1618   const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
1619   return LValue::MakeBitfield(BaseValue, Info,
1620                              Field->getType().getCVRQualifiers()|CVRQualifiers);
1621 }
1622 
1623 /// EmitLValueForAnonRecordField - Given that the field is a member of
1624 /// an anonymous struct or union buried inside a record, and given
1625 /// that the base value is a pointer to the enclosing record, derive
1626 /// an lvalue for the ultimate field.
1627 LValue CodeGenFunction::EmitLValueForAnonRecordField(llvm::Value *BaseValue,
1628                                              const IndirectFieldDecl *Field,
1629                                                      unsigned CVRQualifiers) {
1630   IndirectFieldDecl::chain_iterator I = Field->chain_begin(),
1631     IEnd = Field->chain_end();
1632   while (true) {
1633     LValue LV = EmitLValueForField(BaseValue, cast<FieldDecl>(*I), CVRQualifiers);
1634     if (++I == IEnd) return LV;
1635 
1636     assert(LV.isSimple());
1637     BaseValue = LV.getAddress();
1638     CVRQualifiers |= LV.getVRQualifiers();
1639   }
1640 }
1641 
1642 LValue CodeGenFunction::EmitLValueForField(llvm::Value *baseAddr,
1643                                            const FieldDecl *field,
1644                                            unsigned cvr) {
1645   if (field->isBitField())
1646     return EmitLValueForBitfield(baseAddr, field, cvr);
1647 
1648   const RecordDecl *rec = field->getParent();
1649   QualType type = field->getType();
1650 
1651   bool mayAlias = rec->hasAttr<MayAliasAttr>();
1652 
1653   llvm::Value *addr;
1654   if (rec->isUnion()) {
1655     // For unions, we just cast to the appropriate type.
1656     assert(!type->isReferenceType() && "union has reference member");
1657 
1658     const llvm::Type *llvmType = CGM.getTypes().ConvertTypeForMem(type);
1659     unsigned AS =
1660       cast<llvm::PointerType>(baseAddr->getType())->getAddressSpace();
1661     addr = Builder.CreateBitCast(baseAddr, llvmType->getPointerTo(AS),
1662                                  field->getName());
1663   } else {
1664     // For structs, we GEP to the field that the record layout suggests.
1665     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
1666     addr = Builder.CreateStructGEP(baseAddr, idx, field->getName());
1667 
1668     // If this is a reference field, load the reference right now.
1669     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
1670       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
1671       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
1672 
1673       if (CGM.shouldUseTBAA()) {
1674         llvm::MDNode *tbaa;
1675         if (mayAlias)
1676           tbaa = CGM.getTBAAInfo(getContext().CharTy);
1677         else
1678           tbaa = CGM.getTBAAInfo(type);
1679         CGM.DecorateInstruction(load, tbaa);
1680       }
1681 
1682       addr = load;
1683       mayAlias = false;
1684       type = refType->getPointeeType();
1685       cvr = 0; // qualifiers don't recursively apply to referencee
1686     }
1687   }
1688 
1689   unsigned alignment = getContext().getDeclAlign(field).getQuantity();
1690   LValue LV = MakeAddrLValue(addr, type, alignment);
1691   LV.getQuals().addCVRQualifiers(cvr);
1692 
1693   // __weak attribute on a field is ignored.
1694   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
1695     LV.getQuals().removeObjCGCAttr();
1696 
1697   // Fields of may_alias structs act like 'char' for TBAA purposes.
1698   // FIXME: this should get propagated down through anonymous structs
1699   // and unions.
1700   if (mayAlias && LV.getTBAAInfo())
1701     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
1702 
1703   return LV;
1704 }
1705 
1706 LValue
1707 CodeGenFunction::EmitLValueForFieldInitialization(llvm::Value *BaseValue,
1708                                                   const FieldDecl *Field,
1709                                                   unsigned CVRQualifiers) {
1710   QualType FieldType = Field->getType();
1711 
1712   if (!FieldType->isReferenceType())
1713     return EmitLValueForField(BaseValue, Field, CVRQualifiers);
1714 
1715   const CGRecordLayout &RL =
1716     CGM.getTypes().getCGRecordLayout(Field->getParent());
1717   unsigned idx = RL.getLLVMFieldNo(Field);
1718   llvm::Value *V = Builder.CreateStructGEP(BaseValue, idx, "tmp");
1719 
1720   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
1721 
1722   unsigned Alignment = getContext().getDeclAlign(Field).getQuantity();
1723   return MakeAddrLValue(V, FieldType, Alignment);
1724 }
1725 
1726 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
1727   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
1728   const Expr *InitExpr = E->getInitializer();
1729   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
1730 
1731   EmitAnyExprToMem(InitExpr, DeclPtr, /*Volatile*/ false, /*Init*/ true);
1732 
1733   return Result;
1734 }
1735 
1736 LValue CodeGenFunction::
1737 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
1738   if (!expr->isGLValue()) {
1739     // ?: here should be an aggregate.
1740     assert((hasAggregateLLVMType(expr->getType()) &&
1741             !expr->getType()->isAnyComplexType()) &&
1742            "Unexpected conditional operator!");
1743     return EmitAggExprToLValue(expr);
1744   }
1745 
1746   const Expr *condExpr = expr->getCond();
1747   bool CondExprBool;
1748   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
1749     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
1750     if (!CondExprBool) std::swap(live, dead);
1751 
1752     if (!ContainsLabel(dead))
1753       return EmitLValue(live);
1754   }
1755 
1756   OpaqueValueMapping binding(*this, expr);
1757 
1758   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
1759   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
1760   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
1761 
1762   ConditionalEvaluation eval(*this);
1763   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
1764 
1765   // Any temporaries created here are conditional.
1766   EmitBlock(lhsBlock);
1767   eval.begin(*this);
1768   LValue lhs = EmitLValue(expr->getTrueExpr());
1769   eval.end(*this);
1770 
1771   if (!lhs.isSimple())
1772     return EmitUnsupportedLValue(expr, "conditional operator");
1773 
1774   lhsBlock = Builder.GetInsertBlock();
1775   Builder.CreateBr(contBlock);
1776 
1777   // Any temporaries created here are conditional.
1778   EmitBlock(rhsBlock);
1779   eval.begin(*this);
1780   LValue rhs = EmitLValue(expr->getFalseExpr());
1781   eval.end(*this);
1782   if (!rhs.isSimple())
1783     return EmitUnsupportedLValue(expr, "conditional operator");
1784   rhsBlock = Builder.GetInsertBlock();
1785 
1786   EmitBlock(contBlock);
1787 
1788   llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
1789                                          "cond-lvalue");
1790   phi->addIncoming(lhs.getAddress(), lhsBlock);
1791   phi->addIncoming(rhs.getAddress(), rhsBlock);
1792   return MakeAddrLValue(phi, expr->getType());
1793 }
1794 
1795 /// EmitCastLValue - Casts are never lvalues unless that cast is a dynamic_cast.
1796 /// If the cast is a dynamic_cast, we can have the usual lvalue result,
1797 /// otherwise if a cast is needed by the code generator in an lvalue context,
1798 /// then it must mean that we need the address of an aggregate in order to
1799 /// access one of its fields.  This can happen for all the reasons that casts
1800 /// are permitted with aggregate result, including noop aggregate casts, and
1801 /// cast from scalar to union.
1802 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
1803   switch (E->getCastKind()) {
1804   case CK_ToVoid:
1805     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
1806 
1807   case CK_Dependent:
1808     llvm_unreachable("dependent cast kind in IR gen!");
1809 
1810   case CK_GetObjCProperty: {
1811     LValue LV = EmitLValue(E->getSubExpr());
1812     assert(LV.isPropertyRef());
1813     RValue RV = EmitLoadOfPropertyRefLValue(LV);
1814 
1815     // Property is an aggregate r-value.
1816     if (RV.isAggregate()) {
1817       return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
1818     }
1819 
1820     // Implicit property returns an l-value.
1821     assert(RV.isScalar());
1822     return MakeAddrLValue(RV.getScalarVal(), E->getSubExpr()->getType());
1823   }
1824 
1825   case CK_NoOp:
1826   case CK_LValueToRValue:
1827     if (!E->getSubExpr()->Classify(getContext()).isPRValue()
1828         || E->getType()->isRecordType())
1829       return EmitLValue(E->getSubExpr());
1830     // Fall through to synthesize a temporary.
1831 
1832   case CK_BitCast:
1833   case CK_ArrayToPointerDecay:
1834   case CK_FunctionToPointerDecay:
1835   case CK_NullToMemberPointer:
1836   case CK_NullToPointer:
1837   case CK_IntegralToPointer:
1838   case CK_PointerToIntegral:
1839   case CK_PointerToBoolean:
1840   case CK_VectorSplat:
1841   case CK_IntegralCast:
1842   case CK_IntegralToBoolean:
1843   case CK_IntegralToFloating:
1844   case CK_FloatingToIntegral:
1845   case CK_FloatingToBoolean:
1846   case CK_FloatingCast:
1847   case CK_FloatingRealToComplex:
1848   case CK_FloatingComplexToReal:
1849   case CK_FloatingComplexToBoolean:
1850   case CK_FloatingComplexCast:
1851   case CK_FloatingComplexToIntegralComplex:
1852   case CK_IntegralRealToComplex:
1853   case CK_IntegralComplexToReal:
1854   case CK_IntegralComplexToBoolean:
1855   case CK_IntegralComplexCast:
1856   case CK_IntegralComplexToFloatingComplex:
1857   case CK_DerivedToBaseMemberPointer:
1858   case CK_BaseToDerivedMemberPointer:
1859   case CK_MemberPointerToBoolean:
1860   case CK_AnyPointerToBlockPointerCast: {
1861     // These casts only produce lvalues when we're binding a reference to a
1862     // temporary realized from a (converted) pure rvalue. Emit the expression
1863     // as a value, copy it into a temporary, and return an lvalue referring to
1864     // that temporary.
1865     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
1866     EmitAnyExprToMem(E, V, false, false);
1867     return MakeAddrLValue(V, E->getType());
1868   }
1869 
1870   case CK_Dynamic: {
1871     LValue LV = EmitLValue(E->getSubExpr());
1872     llvm::Value *V = LV.getAddress();
1873     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
1874     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
1875   }
1876 
1877   case CK_ConstructorConversion:
1878   case CK_UserDefinedConversion:
1879   case CK_AnyPointerToObjCPointerCast:
1880     return EmitLValue(E->getSubExpr());
1881 
1882   case CK_UncheckedDerivedToBase:
1883   case CK_DerivedToBase: {
1884     const RecordType *DerivedClassTy =
1885       E->getSubExpr()->getType()->getAs<RecordType>();
1886     CXXRecordDecl *DerivedClassDecl =
1887       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1888 
1889     LValue LV = EmitLValue(E->getSubExpr());
1890     llvm::Value *This = LV.getAddress();
1891 
1892     // Perform the derived-to-base conversion
1893     llvm::Value *Base =
1894       GetAddressOfBaseClass(This, DerivedClassDecl,
1895                             E->path_begin(), E->path_end(),
1896                             /*NullCheckValue=*/false);
1897 
1898     return MakeAddrLValue(Base, E->getType());
1899   }
1900   case CK_ToUnion:
1901     return EmitAggExprToLValue(E);
1902   case CK_BaseToDerived: {
1903     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
1904     CXXRecordDecl *DerivedClassDecl =
1905       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1906 
1907     LValue LV = EmitLValue(E->getSubExpr());
1908 
1909     // Perform the base-to-derived conversion
1910     llvm::Value *Derived =
1911       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
1912                                E->path_begin(), E->path_end(),
1913                                /*NullCheckValue=*/false);
1914 
1915     return MakeAddrLValue(Derived, E->getType());
1916   }
1917   case CK_LValueBitCast: {
1918     // This must be a reinterpret_cast (or c-style equivalent).
1919     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
1920 
1921     LValue LV = EmitLValue(E->getSubExpr());
1922     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1923                                            ConvertType(CE->getTypeAsWritten()));
1924     return MakeAddrLValue(V, E->getType());
1925   }
1926   case CK_ObjCObjectLValueCast: {
1927     LValue LV = EmitLValue(E->getSubExpr());
1928     QualType ToType = getContext().getLValueReferenceType(E->getType());
1929     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
1930                                            ConvertType(ToType));
1931     return MakeAddrLValue(V, E->getType());
1932   }
1933   }
1934 
1935   llvm_unreachable("Unhandled lvalue cast kind?");
1936 }
1937 
1938 LValue CodeGenFunction::EmitNullInitializationLValue(
1939                                               const CXXScalarValueInitExpr *E) {
1940   QualType Ty = E->getType();
1941   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
1942   EmitNullInitialization(LV.getAddress(), Ty);
1943   return LV;
1944 }
1945 
1946 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
1947   assert(e->isGLValue() || e->getType()->isRecordType());
1948   return getOpaqueLValueMapping(e);
1949 }
1950 
1951 //===--------------------------------------------------------------------===//
1952 //                             Expression Emission
1953 //===--------------------------------------------------------------------===//
1954 
1955 
1956 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
1957                                      ReturnValueSlot ReturnValue) {
1958   if (CGDebugInfo *DI = getDebugInfo()) {
1959     DI->setLocation(E->getLocStart());
1960     DI->UpdateLineDirectiveRegion(Builder);
1961     DI->EmitStopPoint(Builder);
1962   }
1963 
1964   // Builtins never have block type.
1965   if (E->getCallee()->getType()->isBlockPointerType())
1966     return EmitBlockCallExpr(E, ReturnValue);
1967 
1968   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
1969     return EmitCXXMemberCallExpr(CE, ReturnValue);
1970 
1971   const Decl *TargetDecl = 0;
1972   if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E->getCallee())) {
1973     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1974       TargetDecl = DRE->getDecl();
1975       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(TargetDecl))
1976         if (unsigned builtinID = FD->getBuiltinID())
1977           return EmitBuiltinExpr(FD, builtinID, E);
1978     }
1979   }
1980 
1981   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
1982     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
1983       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
1984 
1985   if (isa<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
1986     // C++ [expr.pseudo]p1:
1987     //   The result shall only be used as the operand for the function call
1988     //   operator (), and the result of such a call has type void. The only
1989     //   effect is the evaluation of the postfix-expression before the dot or
1990     //   arrow.
1991     EmitScalarExpr(E->getCallee());
1992     return RValue::get(0);
1993   }
1994 
1995   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
1996   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
1997                   E->arg_begin(), E->arg_end(), TargetDecl);
1998 }
1999 
2000 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2001   // Comma expressions just emit their LHS then their RHS as an l-value.
2002   if (E->getOpcode() == BO_Comma) {
2003     EmitIgnoredExpr(E->getLHS());
2004     EnsureInsertPoint();
2005     return EmitLValue(E->getRHS());
2006   }
2007 
2008   if (E->getOpcode() == BO_PtrMemD ||
2009       E->getOpcode() == BO_PtrMemI)
2010     return EmitPointerToDataMemberBinaryExpr(E);
2011 
2012   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2013 
2014   if (!hasAggregateLLVMType(E->getType())) {
2015     // __block variables need the RHS evaluated first.
2016     RValue RV = EmitAnyExpr(E->getRHS());
2017     LValue LV = EmitLValue(E->getLHS());
2018     EmitStoreThroughLValue(RV, LV, E->getType());
2019     return LV;
2020   }
2021 
2022   if (E->getType()->isAnyComplexType())
2023     return EmitComplexAssignmentLValue(E);
2024 
2025   return EmitAggExprToLValue(E);
2026 }
2027 
2028 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2029   RValue RV = EmitCallExpr(E);
2030 
2031   if (!RV.isScalar())
2032     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2033 
2034   assert(E->getCallReturnType()->isReferenceType() &&
2035          "Can't have a scalar return unless the return type is a "
2036          "reference type!");
2037 
2038   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2039 }
2040 
2041 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2042   // FIXME: This shouldn't require another copy.
2043   return EmitAggExprToLValue(E);
2044 }
2045 
2046 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2047   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2048          && "binding l-value to type which needs a temporary");
2049   AggValueSlot Slot = CreateAggTemp(E->getType(), "tmp");
2050   EmitCXXConstructExpr(E, Slot);
2051   return MakeAddrLValue(Slot.getAddr(), E->getType());
2052 }
2053 
2054 LValue
2055 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2056   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2057 }
2058 
2059 LValue
2060 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2061   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2062   Slot.setLifetimeExternallyManaged();
2063   EmitAggExpr(E->getSubExpr(), Slot);
2064   EmitCXXTemporary(E->getTemporary(), Slot.getAddr());
2065   return MakeAddrLValue(Slot.getAddr(), E->getType());
2066 }
2067 
2068 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2069   RValue RV = EmitObjCMessageExpr(E);
2070 
2071   if (!RV.isScalar())
2072     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2073 
2074   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2075          "Can't have a scalar return unless the return type is a "
2076          "reference type!");
2077 
2078   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2079 }
2080 
2081 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2082   llvm::Value *V =
2083     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
2084   return MakeAddrLValue(V, E->getType());
2085 }
2086 
2087 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2088                                              const ObjCIvarDecl *Ivar) {
2089   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
2090 }
2091 
2092 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2093                                           llvm::Value *BaseValue,
2094                                           const ObjCIvarDecl *Ivar,
2095                                           unsigned CVRQualifiers) {
2096   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
2097                                                    Ivar, CVRQualifiers);
2098 }
2099 
2100 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
2101   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2102   llvm::Value *BaseValue = 0;
2103   const Expr *BaseExpr = E->getBase();
2104   Qualifiers BaseQuals;
2105   QualType ObjectTy;
2106   if (E->isArrow()) {
2107     BaseValue = EmitScalarExpr(BaseExpr);
2108     ObjectTy = BaseExpr->getType()->getPointeeType();
2109     BaseQuals = ObjectTy.getQualifiers();
2110   } else {
2111     LValue BaseLV = EmitLValue(BaseExpr);
2112     // FIXME: this isn't right for bitfields.
2113     BaseValue = BaseLV.getAddress();
2114     ObjectTy = BaseExpr->getType();
2115     BaseQuals = ObjectTy.getQualifiers();
2116   }
2117 
2118   LValue LV =
2119     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2120                       BaseQuals.getCVRQualifiers());
2121   setObjCGCLValueClass(getContext(), E, LV);
2122   return LV;
2123 }
2124 
2125 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
2126   // Can only get l-value for message expression returning aggregate type
2127   RValue RV = EmitAnyExprToTemp(E);
2128   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2129 }
2130 
2131 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
2132                                  ReturnValueSlot ReturnValue,
2133                                  CallExpr::const_arg_iterator ArgBeg,
2134                                  CallExpr::const_arg_iterator ArgEnd,
2135                                  const Decl *TargetDecl) {
2136   // Get the actual function type. The callee type will always be a pointer to
2137   // function type or a block pointer type.
2138   assert(CalleeType->isFunctionPointerType() &&
2139          "Call must have function pointer type!");
2140 
2141   CalleeType = getContext().getCanonicalType(CalleeType);
2142 
2143   const FunctionType *FnType
2144     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
2145 
2146   CallArgList Args;
2147   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
2148 
2149   return EmitCall(CGM.getTypes().getFunctionInfo(Args, FnType),
2150                   Callee, ReturnValue, Args, TargetDecl);
2151 }
2152 
2153 LValue CodeGenFunction::
2154 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
2155   llvm::Value *BaseV;
2156   if (E->getOpcode() == BO_PtrMemI)
2157     BaseV = EmitScalarExpr(E->getLHS());
2158   else
2159     BaseV = EmitLValue(E->getLHS()).getAddress();
2160 
2161   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2162 
2163   const MemberPointerType *MPT
2164     = E->getRHS()->getType()->getAs<MemberPointerType>();
2165 
2166   llvm::Value *AddV =
2167     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2168 
2169   return MakeAddrLValue(AddV, MPT->getPointeeType());
2170 }
2171