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