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