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 "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/Basic/ConvertUTF.h"
25 #include "clang/Frontend/CodeGenOptions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/MDBuilder.h"
29 #include "llvm/DataLayout.h"
30 #include "llvm/ADT/Hashing.h"
31 using namespace clang;
32 using namespace CodeGen;
33 
34 //===--------------------------------------------------------------------===//
35 //                        Miscellaneous Helper Methods
36 //===--------------------------------------------------------------------===//
37 
38 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
39   unsigned addressSpace =
40     cast<llvm::PointerType>(value->getType())->getAddressSpace();
41 
42   llvm::PointerType *destType = Int8PtrTy;
43   if (addressSpace)
44     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
45 
46   if (value->getType() == destType) return value;
47   return Builder.CreateBitCast(value, destType);
48 }
49 
50 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
51 /// block.
52 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
53                                                     const Twine &Name) {
54   if (!Builder.isNamePreserving())
55     return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
56   return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
57 }
58 
59 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
60                                      llvm::Value *Init) {
61   llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
62   llvm::BasicBlock *Block = AllocaInsertPt->getParent();
63   Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
64 }
65 
66 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
67                                                 const Twine &Name) {
68   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
69   // FIXME: Should we prefer the preferred type alignment here?
70   CharUnits Align = getContext().getTypeAlignInChars(Ty);
71   Alloc->setAlignment(Align.getQuantity());
72   return Alloc;
73 }
74 
75 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
76                                                  const Twine &Name) {
77   llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
78   // FIXME: Should we prefer the preferred type alignment here?
79   CharUnits Align = getContext().getTypeAlignInChars(Ty);
80   Alloc->setAlignment(Align.getQuantity());
81   return Alloc;
82 }
83 
84 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
85 /// expression and compare the result against zero, returning an Int1Ty value.
86 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
87   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
88     llvm::Value *MemPtr = EmitScalarExpr(E);
89     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
90   }
91 
92   QualType BoolTy = getContext().BoolTy;
93   if (!E->getType()->isAnyComplexType())
94     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
95 
96   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
97 }
98 
99 /// EmitIgnoredExpr - Emit code to compute the specified expression,
100 /// ignoring the result.
101 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
102   if (E->isRValue())
103     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
104 
105   // Just emit it as an l-value and drop the result.
106   EmitLValue(E);
107 }
108 
109 /// EmitAnyExpr - Emit code to compute the specified expression which
110 /// can have any type.  The result is returned as an RValue struct.
111 /// If this is an aggregate expression, AggSlot indicates where the
112 /// result should be returned.
113 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
114                                     AggValueSlot aggSlot,
115                                     bool ignoreResult) {
116   if (!hasAggregateLLVMType(E->getType()))
117     return RValue::get(EmitScalarExpr(E, ignoreResult));
118   else if (E->getType()->isAnyComplexType())
119     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
120 
121   if (!ignoreResult && aggSlot.isIgnored())
122     aggSlot = CreateAggTemp(E->getType(), "agg-temp");
123   EmitAggExpr(E, aggSlot);
124   return aggSlot.asRValue();
125 }
126 
127 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
128 /// always be accessible even if no aggregate location is provided.
129 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
130   AggValueSlot AggSlot = AggValueSlot::ignored();
131 
132   if (hasAggregateLLVMType(E->getType()) &&
133       !E->getType()->isAnyComplexType())
134     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
135   return EmitAnyExpr(E, AggSlot);
136 }
137 
138 /// EmitAnyExprToMem - Evaluate an expression into a given memory
139 /// location.
140 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
141                                        llvm::Value *Location,
142                                        Qualifiers Quals,
143                                        bool IsInit) {
144   // FIXME: This function should take an LValue as an argument.
145   if (E->getType()->isAnyComplexType()) {
146     EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
147   } else if (hasAggregateLLVMType(E->getType())) {
148     CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
149     EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
150                                          AggValueSlot::IsDestructed_t(IsInit),
151                                          AggValueSlot::DoesNotNeedGCBarriers,
152                                          AggValueSlot::IsAliased_t(!IsInit)));
153   } else {
154     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
155     LValue LV = MakeAddrLValue(Location, E->getType());
156     EmitStoreThroughLValue(RV, LV);
157   }
158 }
159 
160 namespace {
161 /// \brief An adjustment to be made to the temporary created when emitting a
162 /// reference binding, which accesses a particular subobject of that temporary.
163   struct SubobjectAdjustment {
164     enum {
165       DerivedToBaseAdjustment,
166       FieldAdjustment,
167       MemberPointerAdjustment
168     } Kind;
169 
170     union {
171       struct {
172         const CastExpr *BasePath;
173         const CXXRecordDecl *DerivedClass;
174       } DerivedToBase;
175 
176       FieldDecl *Field;
177 
178       struct {
179         const MemberPointerType *MPT;
180         Expr *RHS;
181       } Ptr;
182     };
183 
184     SubobjectAdjustment(const CastExpr *BasePath,
185                         const CXXRecordDecl *DerivedClass)
186       : Kind(DerivedToBaseAdjustment) {
187       DerivedToBase.BasePath = BasePath;
188       DerivedToBase.DerivedClass = DerivedClass;
189     }
190 
191     SubobjectAdjustment(FieldDecl *Field)
192       : Kind(FieldAdjustment) {
193       this->Field = Field;
194     }
195 
196     SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
197       : Kind(MemberPointerAdjustment) {
198       this->Ptr.MPT = MPT;
199       this->Ptr.RHS = RHS;
200     }
201   };
202 }
203 
204 static llvm::Value *
205 CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
206                          const NamedDecl *InitializedDecl) {
207   if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
208     if (VD->hasGlobalStorage()) {
209       SmallString<256> Name;
210       llvm::raw_svector_ostream Out(Name);
211       CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
212       Out.flush();
213 
214       llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
215 
216       // Create the reference temporary.
217       llvm::GlobalValue *RefTemp =
218         new llvm::GlobalVariable(CGF.CGM.getModule(),
219                                  RefTempTy, /*isConstant=*/false,
220                                  llvm::GlobalValue::InternalLinkage,
221                                  llvm::Constant::getNullValue(RefTempTy),
222                                  Name.str());
223       return RefTemp;
224     }
225   }
226 
227   return CGF.CreateMemTemp(Type, "ref.tmp");
228 }
229 
230 static const Expr *
231 skipRValueSubobjectAdjustments(const Expr *E,
232                             SmallVectorImpl<SubobjectAdjustment> &Adjustments) {
233   while (true) {
234     E = E->IgnoreParens();
235 
236     if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
237       if ((CE->getCastKind() == CK_DerivedToBase ||
238            CE->getCastKind() == CK_UncheckedDerivedToBase) &&
239           E->getType()->isRecordType()) {
240         E = CE->getSubExpr();
241         CXXRecordDecl *Derived
242           = cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
243         Adjustments.push_back(SubobjectAdjustment(CE, Derived));
244         continue;
245       }
246 
247       if (CE->getCastKind() == CK_NoOp) {
248         E = CE->getSubExpr();
249         continue;
250       }
251     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
252       if (!ME->isArrow() && ME->getBase()->isRValue()) {
253         assert(ME->getBase()->getType()->isRecordType());
254         if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
255           E = ME->getBase();
256           Adjustments.push_back(SubobjectAdjustment(Field));
257           continue;
258         }
259       }
260     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
261       if (BO->isPtrMemOp()) {
262         assert(BO->getLHS()->isRValue());
263         E = BO->getLHS();
264         const MemberPointerType *MPT =
265           BO->getRHS()->getType()->getAs<MemberPointerType>();
266         Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
267       }
268     }
269 
270     // Nothing changed.
271     break;
272   }
273   return E;
274 }
275 
276 static llvm::Value *
277 EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
278                             llvm::Value *&ReferenceTemporary,
279                             const CXXDestructorDecl *&ReferenceTemporaryDtor,
280                             QualType &ObjCARCReferenceLifetimeType,
281                             const NamedDecl *InitializedDecl) {
282   // Look through single-element init lists that claim to be lvalues. They're
283   // just syntactic wrappers in this case.
284   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) {
285     if (ILE->getNumInits() == 1 && ILE->isGLValue())
286       E = ILE->getInit(0);
287   }
288 
289   // Look through expressions for materialized temporaries (for now).
290   if (const MaterializeTemporaryExpr *M
291                                       = dyn_cast<MaterializeTemporaryExpr>(E)) {
292     // Objective-C++ ARC:
293     //   If we are binding a reference to a temporary that has ownership, we
294     //   need to perform retain/release operations on the temporary.
295     if (CGF.getContext().getLangOpts().ObjCAutoRefCount &&
296         E->getType()->isObjCLifetimeType() &&
297         (E->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
298          E->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
299          E->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
300       ObjCARCReferenceLifetimeType = E->getType();
301 
302     E = M->GetTemporaryExpr();
303   }
304 
305   if (const CXXDefaultArgExpr *DAE = dyn_cast<CXXDefaultArgExpr>(E))
306     E = DAE->getExpr();
307 
308   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
309     CGF.enterFullExpression(EWC);
310     CodeGenFunction::RunCleanupsScope Scope(CGF);
311 
312     return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
313                                        ReferenceTemporary,
314                                        ReferenceTemporaryDtor,
315                                        ObjCARCReferenceLifetimeType,
316                                        InitializedDecl);
317   }
318 
319   RValue RV;
320   if (E->isGLValue()) {
321     // Emit the expression as an lvalue.
322     LValue LV = CGF.EmitLValue(E);
323 
324     if (LV.isSimple())
325       return LV.getAddress();
326 
327     // We have to load the lvalue.
328     RV = CGF.EmitLoadOfLValue(LV);
329   } else {
330     if (!ObjCARCReferenceLifetimeType.isNull()) {
331       ReferenceTemporary = CreateReferenceTemporary(CGF,
332                                                   ObjCARCReferenceLifetimeType,
333                                                     InitializedDecl);
334 
335 
336       LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
337                                              ObjCARCReferenceLifetimeType);
338 
339       CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
340                          RefTempDst, false);
341 
342       bool ExtendsLifeOfTemporary = false;
343       if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
344         if (Var->extendsLifetimeOfTemporary())
345           ExtendsLifeOfTemporary = true;
346       } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
347         ExtendsLifeOfTemporary = true;
348       }
349 
350       if (!ExtendsLifeOfTemporary) {
351         // Since the lifetime of this temporary isn't going to be extended,
352         // we need to clean it up ourselves at the end of the full expression.
353         switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
354         case Qualifiers::OCL_None:
355         case Qualifiers::OCL_ExplicitNone:
356         case Qualifiers::OCL_Autoreleasing:
357           break;
358 
359         case Qualifiers::OCL_Strong: {
360           assert(!ObjCARCReferenceLifetimeType->isArrayType());
361           CleanupKind cleanupKind = CGF.getARCCleanupKind();
362           CGF.pushDestroy(cleanupKind,
363                           ReferenceTemporary,
364                           ObjCARCReferenceLifetimeType,
365                           CodeGenFunction::destroyARCStrongImprecise,
366                           cleanupKind & EHCleanup);
367           break;
368         }
369 
370         case Qualifiers::OCL_Weak:
371           assert(!ObjCARCReferenceLifetimeType->isArrayType());
372           CGF.pushDestroy(NormalAndEHCleanup,
373                           ReferenceTemporary,
374                           ObjCARCReferenceLifetimeType,
375                           CodeGenFunction::destroyARCWeak,
376                           /*useEHCleanupForArray*/ true);
377           break;
378         }
379 
380         ObjCARCReferenceLifetimeType = QualType();
381       }
382 
383       return ReferenceTemporary;
384     }
385 
386     SmallVector<SubobjectAdjustment, 2> Adjustments;
387     E = skipRValueSubobjectAdjustments(E, Adjustments);
388     if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
389       if (opaque->getType()->isRecordType())
390         return CGF.EmitOpaqueValueLValue(opaque).getAddress();
391 
392     // Create a reference temporary if necessary.
393     AggValueSlot AggSlot = AggValueSlot::ignored();
394     if (CGF.hasAggregateLLVMType(E->getType()) &&
395         !E->getType()->isAnyComplexType()) {
396       ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
397                                                     InitializedDecl);
398       CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
399       AggValueSlot::IsDestructed_t isDestructed
400         = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
401       AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
402                                       Qualifiers(), isDestructed,
403                                       AggValueSlot::DoesNotNeedGCBarriers,
404                                       AggValueSlot::IsNotAliased);
405     }
406 
407     if (InitializedDecl) {
408       // Get the destructor for the reference temporary.
409       if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
410         CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
411         if (!ClassDecl->hasTrivialDestructor())
412           ReferenceTemporaryDtor = ClassDecl->getDestructor();
413       }
414     }
415 
416     RV = CGF.EmitAnyExpr(E, AggSlot);
417 
418     // Check if need to perform derived-to-base casts and/or field accesses, to
419     // get from the temporary object we created (and, potentially, for which we
420     // extended the lifetime) to the subobject we're binding the reference to.
421     if (!Adjustments.empty()) {
422       llvm::Value *Object = RV.getAggregateAddr();
423       for (unsigned I = Adjustments.size(); I != 0; --I) {
424         SubobjectAdjustment &Adjustment = Adjustments[I-1];
425         switch (Adjustment.Kind) {
426         case SubobjectAdjustment::DerivedToBaseAdjustment:
427           Object =
428               CGF.GetAddressOfBaseClass(Object,
429                                         Adjustment.DerivedToBase.DerivedClass,
430                               Adjustment.DerivedToBase.BasePath->path_begin(),
431                               Adjustment.DerivedToBase.BasePath->path_end(),
432                                         /*NullCheckValue=*/false);
433           break;
434 
435         case SubobjectAdjustment::FieldAdjustment: {
436           LValue LV = CGF.MakeAddrLValue(Object, E->getType());
437           LV = CGF.EmitLValueForField(LV, Adjustment.Field);
438           if (LV.isSimple()) {
439             Object = LV.getAddress();
440             break;
441           }
442 
443           // For non-simple lvalues, we actually have to create a copy of
444           // the object we're binding to.
445           QualType T = Adjustment.Field->getType().getNonReferenceType()
446                                                   .getUnqualifiedType();
447           Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
448           LValue TempLV = CGF.MakeAddrLValue(Object,
449                                              Adjustment.Field->getType());
450           CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
451           break;
452         }
453 
454         case SubobjectAdjustment::MemberPointerAdjustment: {
455           llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
456           Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
457                         CGF, Object, Ptr, Adjustment.Ptr.MPT);
458           break;
459         }
460         }
461       }
462 
463       return Object;
464     }
465   }
466 
467   if (RV.isAggregate())
468     return RV.getAggregateAddr();
469 
470   // Create a temporary variable that we can bind the reference to.
471   ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
472                                                 InitializedDecl);
473 
474 
475   unsigned Alignment =
476     CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
477   if (RV.isScalar())
478     CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
479                           /*Volatile=*/false, Alignment, E->getType());
480   else
481     CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
482                            /*Volatile=*/false);
483   return ReferenceTemporary;
484 }
485 
486 RValue
487 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
488                                             const NamedDecl *InitializedDecl) {
489   llvm::Value *ReferenceTemporary = 0;
490   const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
491   QualType ObjCARCReferenceLifetimeType;
492   llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
493                                                    ReferenceTemporaryDtor,
494                                                    ObjCARCReferenceLifetimeType,
495                                                    InitializedDecl);
496   if (CatchUndefined && !E->getType()->isFunctionType()) {
497     // C++11 [dcl.ref]p5 (as amended by core issue 453):
498     //   If a glvalue to which a reference is directly bound designates neither
499     //   an existing object or function of an appropriate type nor a region of
500     //   storage of suitable size and alignment to contain an object of the
501     //   reference's type, the behavior is undefined.
502     QualType Ty = E->getType();
503     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
504   }
505   if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
506     return RValue::get(Value);
507 
508   // Make sure to call the destructor for the reference temporary.
509   const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
510   if (VD && VD->hasGlobalStorage()) {
511     if (ReferenceTemporaryDtor) {
512       llvm::Constant *DtorFn =
513         CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
514       CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
515                                     cast<llvm::Constant>(ReferenceTemporary));
516     } else {
517       assert(!ObjCARCReferenceLifetimeType.isNull());
518       // Note: We intentionally do not register a global "destructor" to
519       // release the object.
520     }
521 
522     return RValue::get(Value);
523   }
524 
525   if (ReferenceTemporaryDtor)
526     PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
527   else {
528     switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
529     case Qualifiers::OCL_None:
530       llvm_unreachable(
531                       "Not a reference temporary that needs to be deallocated");
532     case Qualifiers::OCL_ExplicitNone:
533     case Qualifiers::OCL_Autoreleasing:
534       // Nothing to do.
535       break;
536 
537     case Qualifiers::OCL_Strong: {
538       bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
539       CleanupKind cleanupKind = getARCCleanupKind();
540       pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
541                   precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
542                   cleanupKind & EHCleanup);
543       break;
544     }
545 
546     case Qualifiers::OCL_Weak: {
547       // __weak objects always get EH cleanups; otherwise, exceptions
548       // could cause really nasty crashes instead of mere leaks.
549       pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
550                   ObjCARCReferenceLifetimeType, destroyARCWeak, true);
551       break;
552     }
553     }
554   }
555 
556   return RValue::get(Value);
557 }
558 
559 
560 /// getAccessedFieldNo - Given an encoded value and a result number, return the
561 /// input field number being accessed.
562 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
563                                              const llvm::Constant *Elts) {
564   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
565       ->getZExtValue();
566 }
567 
568 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
569 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
570                                     llvm::Value *High) {
571   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
572   llvm::Value *K47 = Builder.getInt64(47);
573   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
574   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
575   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
576   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
577   return Builder.CreateMul(B1, KMul);
578 }
579 
580 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
581                                     llvm::Value *Address,
582                                     QualType Ty, CharUnits Alignment) {
583   if (!CatchUndefined)
584     return;
585 
586   llvm::Value *Cond = 0;
587 
588   if (TCK != TCK_Load && TCK != TCK_Store) {
589     // The glvalue must not be an empty glvalue. Don't bother checking this for
590     // loads and stores, because we will get a segfault anyway (if the operation
591     // isn't optimized out).
592     Cond = Builder.CreateICmpNE(
593         Address, llvm::Constant::getNullValue(Address->getType()));
594   }
595 
596   uint64_t AlignVal = Alignment.getQuantity();
597 
598   if (!Ty->isIncompleteType()) {
599     uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
600     if (!AlignVal)
601       AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
602 
603     // This needs to be to the standard address space.
604     Address = Builder.CreateBitCast(Address, Int8PtrTy);
605 
606     // The glvalue must refer to a large enough storage region.
607     // FIXME: If -faddress-sanitizer is enabled, insert dynamic instrumentation
608     //        to check this.
609     llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
610     llvm::Value *Min = Builder.getFalse();
611     llvm::Value *LargeEnough =
612         Builder.CreateICmpUGE(Builder.CreateCall2(F, Address, Min),
613                               llvm::ConstantInt::get(IntPtrTy, Size));
614     Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
615   }
616 
617   if (AlignVal) {
618     // The glvalue must be suitably aligned.
619     llvm::Value *Align =
620         Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
621                           llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
622     Cond = Builder.CreateAnd(Cond,
623         Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0)));
624   }
625 
626   if (Cond) {
627     llvm::Constant *StaticData[] = {
628       EmitCheckSourceLocation(Loc),
629       EmitCheckTypeDescriptor(Ty),
630       llvm::ConstantInt::get(SizeTy, AlignVal),
631       llvm::ConstantInt::get(Int8Ty, TCK)
632     };
633     EmitCheck(Cond, "type_mismatch", StaticData, Address);
634   }
635 
636   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
637   if (TCK != TCK_ConstructorCall &&
638       RD && RD->hasDefinition() && RD->isDynamicClass()) {
639     // Check that the vptr indicates that there is a subobject of type Ty at
640     // offset zero within this object.
641     // FIXME: Produce a diagnostic if the user tries to combine this check with
642     //        -fno-rtti.
643 
644     // Compute a hash of the mangled name of the type.
645     //
646     // FIXME: This is not guaranteed to be deterministic! Move to a
647     //        fingerprinting mechanism once LLVM provides one. For the time
648     //        being the implementation happens to be deterministic.
649     llvm::SmallString<64> MangledName;
650     llvm::raw_svector_ostream Out(MangledName);
651     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
652                                                      Out);
653     llvm::hash_code TypeHash = hash_value(Out.str());
654 
655     // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
656     llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
657     llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
658     llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
659     llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
660     llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
661 
662     llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
663     Hash = Builder.CreateTrunc(Hash, IntPtrTy);
664 
665     // Look the hash up in our cache.
666     const int CacheSize = 128;
667     llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
668     llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
669                                                    "__ubsan_vptr_type_cache");
670     llvm::Value *Slot = Builder.CreateAnd(Hash,
671                                           llvm::ConstantInt::get(IntPtrTy,
672                                                                  CacheSize-1));
673     llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
674     llvm::Value *CacheVal =
675       Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
676 
677     // If the hash isn't in the cache, call a runtime handler to perform the
678     // hard work of checking whether the vptr is for an object of the right
679     // type. This will either fill in the cache and return, or produce a
680     // diagnostic.
681     llvm::Constant *StaticData[] = {
682       EmitCheckSourceLocation(Loc),
683       EmitCheckTypeDescriptor(Ty),
684       CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
685       llvm::ConstantInt::get(Int8Ty, TCK)
686     };
687     llvm::Value *DynamicData[] = { Address, Hash };
688     EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
689               "dynamic_type_cache_miss", StaticData, DynamicData, true);
690   }
691 }
692 
693 
694 CodeGenFunction::ComplexPairTy CodeGenFunction::
695 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
696                          bool isInc, bool isPre) {
697   ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
698                                             LV.isVolatileQualified());
699 
700   llvm::Value *NextVal;
701   if (isa<llvm::IntegerType>(InVal.first->getType())) {
702     uint64_t AmountVal = isInc ? 1 : -1;
703     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
704 
705     // Add the inc/dec to the real part.
706     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
707   } else {
708     QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
709     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
710     if (!isInc)
711       FVal.changeSign();
712     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
713 
714     // Add the inc/dec to the real part.
715     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
716   }
717 
718   ComplexPairTy IncVal(NextVal, InVal.second);
719 
720   // Store the updated result through the lvalue.
721   StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
722 
723   // If this is a postinc, return the value read from memory, otherwise use the
724   // updated value.
725   return isPre ? IncVal : InVal;
726 }
727 
728 
729 //===----------------------------------------------------------------------===//
730 //                         LValue Expression Emission
731 //===----------------------------------------------------------------------===//
732 
733 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
734   if (Ty->isVoidType())
735     return RValue::get(0);
736 
737   if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
738     llvm::Type *EltTy = ConvertType(CTy->getElementType());
739     llvm::Value *U = llvm::UndefValue::get(EltTy);
740     return RValue::getComplex(std::make_pair(U, U));
741   }
742 
743   // If this is a use of an undefined aggregate type, the aggregate must have an
744   // identifiable address.  Just because the contents of the value are undefined
745   // doesn't mean that the address can't be taken and compared.
746   if (hasAggregateLLVMType(Ty)) {
747     llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
748     return RValue::getAggregate(DestPtr);
749   }
750 
751   return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
752 }
753 
754 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
755                                               const char *Name) {
756   ErrorUnsupported(E, Name);
757   return GetUndefRValue(E->getType());
758 }
759 
760 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
761                                               const char *Name) {
762   ErrorUnsupported(E, Name);
763   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
764   return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
765 }
766 
767 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
768   LValue LV = EmitLValue(E);
769   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
770     EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
771                   E->getType(), LV.getAlignment());
772   return LV;
773 }
774 
775 /// EmitLValue - Emit code to compute a designator that specifies the location
776 /// of the expression.
777 ///
778 /// This can return one of two things: a simple address or a bitfield reference.
779 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
780 /// an LLVM pointer type.
781 ///
782 /// If this returns a bitfield reference, nothing about the pointee type of the
783 /// LLVM value is known: For example, it may not be a pointer to an integer.
784 ///
785 /// If this returns a normal address, and if the lvalue's C type is fixed size,
786 /// this method guarantees that the returned pointer type will point to an LLVM
787 /// type of the same size of the lvalue's type.  If the lvalue has a variable
788 /// length type, this is not possible.
789 ///
790 LValue CodeGenFunction::EmitLValue(const Expr *E) {
791   switch (E->getStmtClass()) {
792   default: return EmitUnsupportedLValue(E, "l-value expression");
793 
794   case Expr::ObjCPropertyRefExprClass:
795     llvm_unreachable("cannot emit a property reference directly");
796 
797   case Expr::ObjCSelectorExprClass:
798     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
799   case Expr::ObjCIsaExprClass:
800     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
801   case Expr::BinaryOperatorClass:
802     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
803   case Expr::CompoundAssignOperatorClass:
804     if (!E->getType()->isAnyComplexType())
805       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
806     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
807   case Expr::CallExprClass:
808   case Expr::CXXMemberCallExprClass:
809   case Expr::CXXOperatorCallExprClass:
810   case Expr::UserDefinedLiteralClass:
811     return EmitCallExprLValue(cast<CallExpr>(E));
812   case Expr::VAArgExprClass:
813     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
814   case Expr::DeclRefExprClass:
815     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
816   case Expr::ParenExprClass:
817     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
818   case Expr::GenericSelectionExprClass:
819     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
820   case Expr::PredefinedExprClass:
821     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
822   case Expr::StringLiteralClass:
823     return EmitStringLiteralLValue(cast<StringLiteral>(E));
824   case Expr::ObjCEncodeExprClass:
825     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
826   case Expr::PseudoObjectExprClass:
827     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
828   case Expr::InitListExprClass:
829     return EmitInitListLValue(cast<InitListExpr>(E));
830   case Expr::CXXTemporaryObjectExprClass:
831   case Expr::CXXConstructExprClass:
832     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
833   case Expr::CXXBindTemporaryExprClass:
834     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
835   case Expr::CXXUuidofExprClass:
836     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
837   case Expr::LambdaExprClass:
838     return EmitLambdaLValue(cast<LambdaExpr>(E));
839 
840   case Expr::ExprWithCleanupsClass: {
841     const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
842     enterFullExpression(cleanups);
843     RunCleanupsScope Scope(*this);
844     return EmitLValue(cleanups->getSubExpr());
845   }
846 
847   case Expr::CXXScalarValueInitExprClass:
848     return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
849   case Expr::CXXDefaultArgExprClass:
850     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
851   case Expr::CXXTypeidExprClass:
852     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
853 
854   case Expr::ObjCMessageExprClass:
855     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
856   case Expr::ObjCIvarRefExprClass:
857     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
858   case Expr::StmtExprClass:
859     return EmitStmtExprLValue(cast<StmtExpr>(E));
860   case Expr::UnaryOperatorClass:
861     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
862   case Expr::ArraySubscriptExprClass:
863     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
864   case Expr::ExtVectorElementExprClass:
865     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
866   case Expr::MemberExprClass:
867     return EmitMemberExpr(cast<MemberExpr>(E));
868   case Expr::CompoundLiteralExprClass:
869     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
870   case Expr::ConditionalOperatorClass:
871     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
872   case Expr::BinaryConditionalOperatorClass:
873     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
874   case Expr::ChooseExprClass:
875     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
876   case Expr::OpaqueValueExprClass:
877     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
878   case Expr::SubstNonTypeTemplateParmExprClass:
879     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
880   case Expr::ImplicitCastExprClass:
881   case Expr::CStyleCastExprClass:
882   case Expr::CXXFunctionalCastExprClass:
883   case Expr::CXXStaticCastExprClass:
884   case Expr::CXXDynamicCastExprClass:
885   case Expr::CXXReinterpretCastExprClass:
886   case Expr::CXXConstCastExprClass:
887   case Expr::ObjCBridgedCastExprClass:
888     return EmitCastLValue(cast<CastExpr>(E));
889 
890   case Expr::MaterializeTemporaryExprClass:
891     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
892   }
893 }
894 
895 /// Given an object of the given canonical type, can we safely copy a
896 /// value out of it based on its initializer?
897 static bool isConstantEmittableObjectType(QualType type) {
898   assert(type.isCanonical());
899   assert(!type->isReferenceType());
900 
901   // Must be const-qualified but non-volatile.
902   Qualifiers qs = type.getLocalQualifiers();
903   if (!qs.hasConst() || qs.hasVolatile()) return false;
904 
905   // Otherwise, all object types satisfy this except C++ classes with
906   // mutable subobjects or non-trivial copy/destroy behavior.
907   if (const RecordType *RT = dyn_cast<RecordType>(type))
908     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
909       if (RD->hasMutableFields() || !RD->isTrivial())
910         return false;
911 
912   return true;
913 }
914 
915 /// Can we constant-emit a load of a reference to a variable of the
916 /// given type?  This is different from predicates like
917 /// Decl::isUsableInConstantExpressions because we do want it to apply
918 /// in situations that don't necessarily satisfy the language's rules
919 /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
920 /// to do this with const float variables even if those variables
921 /// aren't marked 'constexpr'.
922 enum ConstantEmissionKind {
923   CEK_None,
924   CEK_AsReferenceOnly,
925   CEK_AsValueOrReference,
926   CEK_AsValueOnly
927 };
928 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
929   type = type.getCanonicalType();
930   if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
931     if (isConstantEmittableObjectType(ref->getPointeeType()))
932       return CEK_AsValueOrReference;
933     return CEK_AsReferenceOnly;
934   }
935   if (isConstantEmittableObjectType(type))
936     return CEK_AsValueOnly;
937   return CEK_None;
938 }
939 
940 /// Try to emit a reference to the given value without producing it as
941 /// an l-value.  This is actually more than an optimization: we can't
942 /// produce an l-value for variables that we never actually captured
943 /// in a block or lambda, which means const int variables or constexpr
944 /// literals or similar.
945 CodeGenFunction::ConstantEmission
946 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
947   ValueDecl *value = refExpr->getDecl();
948 
949   // The value needs to be an enum constant or a constant variable.
950   ConstantEmissionKind CEK;
951   if (isa<ParmVarDecl>(value)) {
952     CEK = CEK_None;
953   } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
954     CEK = checkVarTypeForConstantEmission(var->getType());
955   } else if (isa<EnumConstantDecl>(value)) {
956     CEK = CEK_AsValueOnly;
957   } else {
958     CEK = CEK_None;
959   }
960   if (CEK == CEK_None) return ConstantEmission();
961 
962   Expr::EvalResult result;
963   bool resultIsReference;
964   QualType resultType;
965 
966   // It's best to evaluate all the way as an r-value if that's permitted.
967   if (CEK != CEK_AsReferenceOnly &&
968       refExpr->EvaluateAsRValue(result, getContext())) {
969     resultIsReference = false;
970     resultType = refExpr->getType();
971 
972   // Otherwise, try to evaluate as an l-value.
973   } else if (CEK != CEK_AsValueOnly &&
974              refExpr->EvaluateAsLValue(result, getContext())) {
975     resultIsReference = true;
976     resultType = value->getType();
977 
978   // Failure.
979   } else {
980     return ConstantEmission();
981   }
982 
983   // In any case, if the initializer has side-effects, abandon ship.
984   if (result.HasSideEffects)
985     return ConstantEmission();
986 
987   // Emit as a constant.
988   llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
989 
990   // Make sure we emit a debug reference to the global variable.
991   // This should probably fire even for
992   if (isa<VarDecl>(value)) {
993     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
994       EmitDeclRefExprDbgValue(refExpr, C);
995   } else {
996     assert(isa<EnumConstantDecl>(value));
997     EmitDeclRefExprDbgValue(refExpr, C);
998   }
999 
1000   // If we emitted a reference constant, we need to dereference that.
1001   if (resultIsReference)
1002     return ConstantEmission::forReference(C);
1003 
1004   return ConstantEmission::forValue(C);
1005 }
1006 
1007 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
1008   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1009                           lvalue.getAlignment().getQuantity(),
1010                           lvalue.getType(), lvalue.getTBAAInfo());
1011 }
1012 
1013 static bool hasBooleanRepresentation(QualType Ty) {
1014   if (Ty->isBooleanType())
1015     return true;
1016 
1017   if (const EnumType *ET = Ty->getAs<EnumType>())
1018     return ET->getDecl()->getIntegerType()->isBooleanType();
1019 
1020   if (const AtomicType *AT = Ty->getAs<AtomicType>())
1021     return hasBooleanRepresentation(AT->getValueType());
1022 
1023   return false;
1024 }
1025 
1026 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1027   const EnumType *ET = Ty->getAs<EnumType>();
1028   bool IsRegularCPlusPlusEnum = (getLangOpts().CPlusPlus && ET &&
1029                                  CGM.getCodeGenOpts().StrictEnums &&
1030                                  !ET->getDecl()->isFixed());
1031   bool IsBool = hasBooleanRepresentation(Ty);
1032   if (!IsBool && !IsRegularCPlusPlusEnum)
1033     return NULL;
1034 
1035   llvm::APInt Min;
1036   llvm::APInt End;
1037   if (IsBool) {
1038     Min = llvm::APInt(8, 0);
1039     End = llvm::APInt(8, 2);
1040   } else {
1041     const EnumDecl *ED = ET->getDecl();
1042     llvm::Type *LTy = ConvertTypeForMem(ED->getIntegerType());
1043     unsigned Bitwidth = LTy->getScalarSizeInBits();
1044     unsigned NumNegativeBits = ED->getNumNegativeBits();
1045     unsigned NumPositiveBits = ED->getNumPositiveBits();
1046 
1047     if (NumNegativeBits) {
1048       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1049       assert(NumBits <= Bitwidth);
1050       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1051       Min = -End;
1052     } else {
1053       assert(NumPositiveBits <= Bitwidth);
1054       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1055       Min = llvm::APInt(Bitwidth, 0);
1056     }
1057   }
1058 
1059   llvm::MDBuilder MDHelper(getLLVMContext());
1060   return MDHelper.createRange(Min, End);
1061 }
1062 
1063 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1064                                               unsigned Alignment, QualType Ty,
1065                                               llvm::MDNode *TBAAInfo) {
1066 
1067   // For better performance, handle vector loads differently.
1068   if (Ty->isVectorType()) {
1069     llvm::Value *V;
1070     const llvm::Type *EltTy =
1071     cast<llvm::PointerType>(Addr->getType())->getElementType();
1072 
1073     const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
1074 
1075     // Handle vectors of size 3, like size 4 for better performance.
1076     if (VTy->getNumElements() == 3) {
1077 
1078       // Bitcast to vec4 type.
1079       llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1080                                                          4);
1081       llvm::PointerType *ptVec4Ty =
1082       llvm::PointerType::get(vec4Ty,
1083                              (cast<llvm::PointerType>(
1084                                       Addr->getType()))->getAddressSpace());
1085       llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1086                                                 "castToVec4");
1087       // Now load value.
1088       llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1089 
1090       // Shuffle vector to get vec3.
1091       llvm::SmallVector<llvm::Constant*, 3> Mask;
1092       Mask.push_back(llvm::ConstantInt::get(
1093                                     llvm::Type::getInt32Ty(getLLVMContext()),
1094                                             0));
1095       Mask.push_back(llvm::ConstantInt::get(
1096                                     llvm::Type::getInt32Ty(getLLVMContext()),
1097                                             1));
1098       Mask.push_back(llvm::ConstantInt::get(
1099                                      llvm::Type::getInt32Ty(getLLVMContext()),
1100                                             2));
1101 
1102       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1103       V = Builder.CreateShuffleVector(LoadVal,
1104                                       llvm::UndefValue::get(vec4Ty),
1105                                       MaskV, "extractVec");
1106       return EmitFromMemory(V, Ty);
1107     }
1108   }
1109 
1110   llvm::LoadInst *Load = Builder.CreateLoad(Addr);
1111   if (Volatile)
1112     Load->setVolatile(true);
1113   if (Alignment)
1114     Load->setAlignment(Alignment);
1115   if (TBAAInfo)
1116     CGM.DecorateInstruction(Load, TBAAInfo);
1117   // If this is an atomic type, all normal reads must be atomic
1118   if (Ty->isAtomicType())
1119     Load->setAtomic(llvm::SequentiallyConsistent);
1120 
1121   if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1122     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1123       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1124 
1125   return EmitFromMemory(Load, Ty);
1126 }
1127 
1128 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1129   // Bool has a different representation in memory than in registers.
1130   if (hasBooleanRepresentation(Ty)) {
1131     // This should really always be an i1, but sometimes it's already
1132     // an i8, and it's awkward to track those cases down.
1133     if (Value->getType()->isIntegerTy(1))
1134       return Builder.CreateZExt(Value, Builder.getInt8Ty(), "frombool");
1135     assert(Value->getType()->isIntegerTy(8) && "value rep of bool not i1/i8");
1136   }
1137 
1138   return Value;
1139 }
1140 
1141 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1142   // Bool has a different representation in memory than in registers.
1143   if (hasBooleanRepresentation(Ty)) {
1144     assert(Value->getType()->isIntegerTy(8) && "memory rep of bool not i8");
1145     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1146   }
1147 
1148   return Value;
1149 }
1150 
1151 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1152                                         bool Volatile, unsigned Alignment,
1153                                         QualType Ty,
1154                                         llvm::MDNode *TBAAInfo,
1155                                         bool isInit) {
1156 
1157   // Handle vectors differently to get better performance.
1158   if (Ty->isVectorType()) {
1159     llvm::Type *SrcTy = Value->getType();
1160     llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1161     // Handle vec3 special.
1162     if (VecTy->getNumElements() == 3) {
1163       llvm::LLVMContext &VMContext = getLLVMContext();
1164 
1165       // Our source is a vec3, do a shuffle vector to make it a vec4.
1166       llvm::SmallVector<llvm::Constant*, 4> Mask;
1167       Mask.push_back(llvm::ConstantInt::get(
1168                                             llvm::Type::getInt32Ty(VMContext),
1169                                             0));
1170       Mask.push_back(llvm::ConstantInt::get(
1171                                             llvm::Type::getInt32Ty(VMContext),
1172                                             1));
1173       Mask.push_back(llvm::ConstantInt::get(
1174                                             llvm::Type::getInt32Ty(VMContext),
1175                                             2));
1176       Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1177 
1178       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1179       Value = Builder.CreateShuffleVector(Value,
1180                                           llvm::UndefValue::get(VecTy),
1181                                           MaskV, "extractVec");
1182       SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1183     }
1184     llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1185     if (DstPtr->getElementType() != SrcTy) {
1186       llvm::Type *MemTy =
1187       llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1188       Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1189     }
1190   }
1191 
1192   Value = EmitToMemory(Value, Ty);
1193 
1194   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1195   if (Alignment)
1196     Store->setAlignment(Alignment);
1197   if (TBAAInfo)
1198     CGM.DecorateInstruction(Store, TBAAInfo);
1199   if (!isInit && Ty->isAtomicType())
1200     Store->setAtomic(llvm::SequentiallyConsistent);
1201 }
1202 
1203 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1204     bool isInit) {
1205   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1206                     lvalue.getAlignment().getQuantity(), lvalue.getType(),
1207                     lvalue.getTBAAInfo(), isInit);
1208 }
1209 
1210 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1211 /// method emits the address of the lvalue, then loads the result as an rvalue,
1212 /// returning the rvalue.
1213 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
1214   if (LV.isObjCWeak()) {
1215     // load of a __weak object.
1216     llvm::Value *AddrWeakObj = LV.getAddress();
1217     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1218                                                              AddrWeakObj));
1219   }
1220   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak)
1221     return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1222 
1223   if (LV.isSimple()) {
1224     assert(!LV.getType()->isFunctionType());
1225 
1226     // Everything needs a load.
1227     return RValue::get(EmitLoadOfScalar(LV));
1228   }
1229 
1230   if (LV.isVectorElt()) {
1231     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1232                                               LV.isVolatileQualified());
1233     Load->setAlignment(LV.getAlignment().getQuantity());
1234     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1235                                                     "vecext"));
1236   }
1237 
1238   // If this is a reference to a subset of the elements of a vector, either
1239   // shuffle the input or extract/insert them as appropriate.
1240   if (LV.isExtVectorElt())
1241     return EmitLoadOfExtVectorElementLValue(LV);
1242 
1243   assert(LV.isBitField() && "Unknown LValue type!");
1244   return EmitLoadOfBitfieldLValue(LV);
1245 }
1246 
1247 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1248   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1249 
1250   // Get the output type.
1251   llvm::Type *ResLTy = ConvertType(LV.getType());
1252   unsigned ResSizeInBits = CGM.getDataLayout().getTypeSizeInBits(ResLTy);
1253 
1254   // Compute the result as an OR of all of the individual component accesses.
1255   llvm::Value *Res = 0;
1256   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1257     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
1258     CharUnits AccessAlignment = AI.AccessAlignment;
1259     if (!LV.getAlignment().isZero())
1260       AccessAlignment = std::min(AccessAlignment, LV.getAlignment());
1261 
1262     // Get the field pointer.
1263     llvm::Value *Ptr = LV.getBitFieldBaseAddr();
1264 
1265     // Only offset by the field index if used, so that incoming values are not
1266     // required to be structures.
1267     if (AI.FieldIndex)
1268       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
1269 
1270     // Offset by the byte offset, if used.
1271     if (!AI.FieldByteOffset.isZero()) {
1272       Ptr = EmitCastToVoidPtr(Ptr);
1273       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1274                                        "bf.field.offs");
1275     }
1276 
1277     // Cast to the access type.
1278     llvm::Type *PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), AI.AccessWidth,
1279                        CGM.getContext().getTargetAddressSpace(LV.getType()));
1280     Ptr = Builder.CreateBitCast(Ptr, PTy);
1281 
1282     // Perform the load.
1283     llvm::LoadInst *Load = Builder.CreateLoad(Ptr, LV.isVolatileQualified());
1284     Load->setAlignment(AccessAlignment.getQuantity());
1285 
1286     // Shift out unused low bits and mask out unused high bits.
1287     llvm::Value *Val = Load;
1288     if (AI.FieldBitStart)
1289       Val = Builder.CreateLShr(Load, AI.FieldBitStart);
1290     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(AI.AccessWidth,
1291                                                             AI.TargetBitWidth),
1292                             "bf.clear");
1293 
1294     // Extend or truncate to the target size.
1295     if (AI.AccessWidth < ResSizeInBits)
1296       Val = Builder.CreateZExt(Val, ResLTy);
1297     else if (AI.AccessWidth > ResSizeInBits)
1298       Val = Builder.CreateTrunc(Val, ResLTy);
1299 
1300     // Shift into place, and OR into the result.
1301     if (AI.TargetBitOffset)
1302       Val = Builder.CreateShl(Val, AI.TargetBitOffset);
1303     Res = Res ? Builder.CreateOr(Res, Val) : Val;
1304   }
1305 
1306   // If the bit-field is signed, perform the sign-extension.
1307   //
1308   // FIXME: This can easily be folded into the load of the high bits, which
1309   // could also eliminate the mask of high bits in some situations.
1310   if (Info.isSigned()) {
1311     unsigned ExtraBits = ResSizeInBits - Info.getSize();
1312     if (ExtraBits)
1313       Res = Builder.CreateAShr(Builder.CreateShl(Res, ExtraBits),
1314                                ExtraBits, "bf.val.sext");
1315   }
1316 
1317   return RValue::get(Res);
1318 }
1319 
1320 // If this is a reference to a subset of the elements of a vector, create an
1321 // appropriate shufflevector.
1322 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1323   llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1324                                             LV.isVolatileQualified());
1325   Load->setAlignment(LV.getAlignment().getQuantity());
1326   llvm::Value *Vec = Load;
1327 
1328   const llvm::Constant *Elts = LV.getExtVectorElts();
1329 
1330   // If the result of the expression is a non-vector type, we must be extracting
1331   // a single element.  Just codegen as an extractelement.
1332   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1333   if (!ExprVT) {
1334     unsigned InIdx = getAccessedFieldNo(0, Elts);
1335     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1336     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1337   }
1338 
1339   // Always use shuffle vector to try to retain the original program structure
1340   unsigned NumResultElts = ExprVT->getNumElements();
1341 
1342   SmallVector<llvm::Constant*, 4> Mask;
1343   for (unsigned i = 0; i != NumResultElts; ++i)
1344     Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1345 
1346   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1347   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1348                                     MaskV);
1349   return RValue::get(Vec);
1350 }
1351 
1352 
1353 
1354 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1355 /// lvalue, where both are guaranteed to the have the same type, and that type
1356 /// is 'Ty'.
1357 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
1358   if (!Dst.isSimple()) {
1359     if (Dst.isVectorElt()) {
1360       // Read/modify/write the vector, inserting the new element.
1361       llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1362                                                 Dst.isVolatileQualified());
1363       Load->setAlignment(Dst.getAlignment().getQuantity());
1364       llvm::Value *Vec = Load;
1365       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1366                                         Dst.getVectorIdx(), "vecins");
1367       llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1368                                                    Dst.isVolatileQualified());
1369       Store->setAlignment(Dst.getAlignment().getQuantity());
1370       return;
1371     }
1372 
1373     // If this is an update of extended vector elements, insert them as
1374     // appropriate.
1375     if (Dst.isExtVectorElt())
1376       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1377 
1378     assert(Dst.isBitField() && "Unknown LValue type");
1379     return EmitStoreThroughBitfieldLValue(Src, Dst);
1380   }
1381 
1382   // There's special magic for assigning into an ARC-qualified l-value.
1383   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1384     switch (Lifetime) {
1385     case Qualifiers::OCL_None:
1386       llvm_unreachable("present but none");
1387 
1388     case Qualifiers::OCL_ExplicitNone:
1389       // nothing special
1390       break;
1391 
1392     case Qualifiers::OCL_Strong:
1393       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1394       return;
1395 
1396     case Qualifiers::OCL_Weak:
1397       EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1398       return;
1399 
1400     case Qualifiers::OCL_Autoreleasing:
1401       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1402                                                      Src.getScalarVal()));
1403       // fall into the normal path
1404       break;
1405     }
1406   }
1407 
1408   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1409     // load of a __weak object.
1410     llvm::Value *LvalueDst = Dst.getAddress();
1411     llvm::Value *src = Src.getScalarVal();
1412      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1413     return;
1414   }
1415 
1416   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1417     // load of a __strong object.
1418     llvm::Value *LvalueDst = Dst.getAddress();
1419     llvm::Value *src = Src.getScalarVal();
1420     if (Dst.isObjCIvar()) {
1421       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1422       llvm::Type *ResultType = ConvertType(getContext().LongTy);
1423       llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
1424       llvm::Value *dst = RHS;
1425       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1426       llvm::Value *LHS =
1427         Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1428       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1429       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1430                                               BytesBetween);
1431     } else if (Dst.isGlobalObjCRef()) {
1432       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1433                                                 Dst.isThreadLocalRef());
1434     }
1435     else
1436       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1437     return;
1438   }
1439 
1440   assert(Src.isScalar() && "Can't emit an agg store with this method");
1441   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1442 }
1443 
1444 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1445                                                      llvm::Value **Result) {
1446   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1447 
1448   // Get the output type.
1449   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1450   unsigned ResSizeInBits = CGM.getDataLayout().getTypeSizeInBits(ResLTy);
1451 
1452   // Get the source value, truncated to the width of the bit-field.
1453   llvm::Value *SrcVal = Src.getScalarVal();
1454 
1455   if (hasBooleanRepresentation(Dst.getType()))
1456     SrcVal = Builder.CreateIntCast(SrcVal, ResLTy, /*IsSigned=*/false);
1457 
1458   SrcVal = Builder.CreateAnd(SrcVal, llvm::APInt::getLowBitsSet(ResSizeInBits,
1459                                                                 Info.getSize()),
1460                              "bf.value");
1461 
1462   // Return the new value of the bit-field, if requested.
1463   if (Result) {
1464     // Cast back to the proper type for result.
1465     llvm::Type *SrcTy = Src.getScalarVal()->getType();
1466     llvm::Value *ReloadVal = Builder.CreateIntCast(SrcVal, SrcTy, false,
1467                                                    "bf.reload.val");
1468 
1469     // Sign extend if necessary.
1470     if (Info.isSigned()) {
1471       unsigned ExtraBits = ResSizeInBits - Info.getSize();
1472       if (ExtraBits)
1473         ReloadVal = Builder.CreateAShr(Builder.CreateShl(ReloadVal, ExtraBits),
1474                                        ExtraBits, "bf.reload.sext");
1475     }
1476 
1477     *Result = ReloadVal;
1478   }
1479 
1480   // Iterate over the components, writing each piece to memory.
1481   for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
1482     const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
1483     CharUnits AccessAlignment = AI.AccessAlignment;
1484     if (!Dst.getAlignment().isZero())
1485       AccessAlignment = std::min(AccessAlignment, Dst.getAlignment());
1486 
1487     // Get the field pointer.
1488     llvm::Value *Ptr = Dst.getBitFieldBaseAddr();
1489     unsigned addressSpace =
1490       cast<llvm::PointerType>(Ptr->getType())->getAddressSpace();
1491 
1492     // Only offset by the field index if used, so that incoming values are not
1493     // required to be structures.
1494     if (AI.FieldIndex)
1495       Ptr = Builder.CreateStructGEP(Ptr, AI.FieldIndex, "bf.field");
1496 
1497     // Offset by the byte offset, if used.
1498     if (!AI.FieldByteOffset.isZero()) {
1499       Ptr = EmitCastToVoidPtr(Ptr);
1500       Ptr = Builder.CreateConstGEP1_32(Ptr, AI.FieldByteOffset.getQuantity(),
1501                                        "bf.field.offs");
1502     }
1503 
1504     // Cast to the access type.
1505     llvm::Type *AccessLTy =
1506       llvm::Type::getIntNTy(getLLVMContext(), AI.AccessWidth);
1507 
1508     llvm::Type *PTy = AccessLTy->getPointerTo(addressSpace);
1509     Ptr = Builder.CreateBitCast(Ptr, PTy);
1510 
1511     // Extract the piece of the bit-field value to write in this access, limited
1512     // to the values that are part of this access.
1513     llvm::Value *Val = SrcVal;
1514     if (AI.TargetBitOffset)
1515       Val = Builder.CreateLShr(Val, AI.TargetBitOffset);
1516     Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(ResSizeInBits,
1517                                                             AI.TargetBitWidth));
1518 
1519     // Extend or truncate to the access size.
1520     if (ResSizeInBits < AI.AccessWidth)
1521       Val = Builder.CreateZExt(Val, AccessLTy);
1522     else if (ResSizeInBits > AI.AccessWidth)
1523       Val = Builder.CreateTrunc(Val, AccessLTy);
1524 
1525     // Shift into the position in memory.
1526     if (AI.FieldBitStart)
1527       Val = Builder.CreateShl(Val, AI.FieldBitStart);
1528 
1529     // If necessary, load and OR in bits that are outside of the bit-field.
1530     if (AI.TargetBitWidth != AI.AccessWidth) {
1531       llvm::LoadInst *Load = Builder.CreateLoad(Ptr, Dst.isVolatileQualified());
1532       Load->setAlignment(AccessAlignment.getQuantity());
1533 
1534       // Compute the mask for zeroing the bits that are part of the bit-field.
1535       llvm::APInt InvMask =
1536         ~llvm::APInt::getBitsSet(AI.AccessWidth, AI.FieldBitStart,
1537                                  AI.FieldBitStart + AI.TargetBitWidth);
1538 
1539       // Apply the mask and OR in to the value to write.
1540       Val = Builder.CreateOr(Builder.CreateAnd(Load, InvMask), Val);
1541     }
1542 
1543     // Write the value.
1544     llvm::StoreInst *Store = Builder.CreateStore(Val, Ptr,
1545                                                  Dst.isVolatileQualified());
1546     Store->setAlignment(AccessAlignment.getQuantity());
1547   }
1548 }
1549 
1550 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1551                                                                LValue Dst) {
1552   // This access turns into a read/modify/write of the vector.  Load the input
1553   // value now.
1554   llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1555                                             Dst.isVolatileQualified());
1556   Load->setAlignment(Dst.getAlignment().getQuantity());
1557   llvm::Value *Vec = Load;
1558   const llvm::Constant *Elts = Dst.getExtVectorElts();
1559 
1560   llvm::Value *SrcVal = Src.getScalarVal();
1561 
1562   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1563     unsigned NumSrcElts = VTy->getNumElements();
1564     unsigned NumDstElts =
1565        cast<llvm::VectorType>(Vec->getType())->getNumElements();
1566     if (NumDstElts == NumSrcElts) {
1567       // Use shuffle vector is the src and destination are the same number of
1568       // elements and restore the vector mask since it is on the side it will be
1569       // stored.
1570       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1571       for (unsigned i = 0; i != NumSrcElts; ++i)
1572         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1573 
1574       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1575       Vec = Builder.CreateShuffleVector(SrcVal,
1576                                         llvm::UndefValue::get(Vec->getType()),
1577                                         MaskV);
1578     } else if (NumDstElts > NumSrcElts) {
1579       // Extended the source vector to the same length and then shuffle it
1580       // into the destination.
1581       // FIXME: since we're shuffling with undef, can we just use the indices
1582       //        into that?  This could be simpler.
1583       SmallVector<llvm::Constant*, 4> ExtMask;
1584       for (unsigned i = 0; i != NumSrcElts; ++i)
1585         ExtMask.push_back(Builder.getInt32(i));
1586       ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1587       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1588       llvm::Value *ExtSrcVal =
1589         Builder.CreateShuffleVector(SrcVal,
1590                                     llvm::UndefValue::get(SrcVal->getType()),
1591                                     ExtMaskV);
1592       // build identity
1593       SmallVector<llvm::Constant*, 4> Mask;
1594       for (unsigned i = 0; i != NumDstElts; ++i)
1595         Mask.push_back(Builder.getInt32(i));
1596 
1597       // modify when what gets shuffled in
1598       for (unsigned i = 0; i != NumSrcElts; ++i)
1599         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1600       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1601       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1602     } else {
1603       // We should never shorten the vector
1604       llvm_unreachable("unexpected shorten vector length");
1605     }
1606   } else {
1607     // If the Src is a scalar (not a vector) it must be updating one element.
1608     unsigned InIdx = getAccessedFieldNo(0, Elts);
1609     llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
1610     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1611   }
1612 
1613   llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1614                                                Dst.isVolatileQualified());
1615   Store->setAlignment(Dst.getAlignment().getQuantity());
1616 }
1617 
1618 // setObjCGCLValueClass - sets class of he lvalue for the purpose of
1619 // generating write-barries API. It is currently a global, ivar,
1620 // or neither.
1621 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1622                                  LValue &LV,
1623                                  bool IsMemberAccess=false) {
1624   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1625     return;
1626 
1627   if (isa<ObjCIvarRefExpr>(E)) {
1628     QualType ExpTy = E->getType();
1629     if (IsMemberAccess && ExpTy->isPointerType()) {
1630       // If ivar is a structure pointer, assigning to field of
1631       // this struct follows gcc's behavior and makes it a non-ivar
1632       // writer-barrier conservatively.
1633       ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1634       if (ExpTy->isRecordType()) {
1635         LV.setObjCIvar(false);
1636         return;
1637       }
1638     }
1639     LV.setObjCIvar(true);
1640     ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1641     LV.setBaseIvarExp(Exp->getBase());
1642     LV.setObjCArray(E->getType()->isArrayType());
1643     return;
1644   }
1645 
1646   if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1647     if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1648       if (VD->hasGlobalStorage()) {
1649         LV.setGlobalObjCRef(true);
1650         LV.setThreadLocalRef(VD->isThreadSpecified());
1651       }
1652     }
1653     LV.setObjCArray(E->getType()->isArrayType());
1654     return;
1655   }
1656 
1657   if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
1658     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1659     return;
1660   }
1661 
1662   if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
1663     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1664     if (LV.isObjCIvar()) {
1665       // If cast is to a structure pointer, follow gcc's behavior and make it
1666       // a non-ivar write-barrier.
1667       QualType ExpTy = E->getType();
1668       if (ExpTy->isPointerType())
1669         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1670       if (ExpTy->isRecordType())
1671         LV.setObjCIvar(false);
1672     }
1673     return;
1674   }
1675 
1676   if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1677     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1678     return;
1679   }
1680 
1681   if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1682     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1683     return;
1684   }
1685 
1686   if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
1687     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1688     return;
1689   }
1690 
1691   if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1692     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1693     return;
1694   }
1695 
1696   if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1697     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1698     if (LV.isObjCIvar() && !LV.isObjCArray())
1699       // Using array syntax to assigning to what an ivar points to is not
1700       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1701       LV.setObjCIvar(false);
1702     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1703       // Using array syntax to assigning to what global points to is not
1704       // same as assigning to the global itself. {id *G;} G[i] = 0;
1705       LV.setGlobalObjCRef(false);
1706     return;
1707   }
1708 
1709   if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
1710     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1711     // We don't know if member is an 'ivar', but this flag is looked at
1712     // only in the context of LV.isObjCIvar().
1713     LV.setObjCArray(E->getType()->isArrayType());
1714     return;
1715   }
1716 }
1717 
1718 static llvm::Value *
1719 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1720                                 llvm::Value *V, llvm::Type *IRType,
1721                                 StringRef Name = StringRef()) {
1722   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1723   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1724 }
1725 
1726 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1727                                       const Expr *E, const VarDecl *VD) {
1728   assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
1729          "Var decl must have external storage or be a file var decl!");
1730 
1731   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1732   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1733   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
1734   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
1735   QualType T = E->getType();
1736   LValue LV;
1737   if (VD->getType()->isReferenceType()) {
1738     llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
1739     LI->setAlignment(Alignment.getQuantity());
1740     V = LI;
1741     LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1742   } else {
1743     LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1744   }
1745   setObjCGCLValueClass(CGF.getContext(), E, LV);
1746   return LV;
1747 }
1748 
1749 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1750                                      const Expr *E, const FunctionDecl *FD) {
1751   llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1752   if (!FD->hasPrototype()) {
1753     if (const FunctionProtoType *Proto =
1754             FD->getType()->getAs<FunctionProtoType>()) {
1755       // Ugly case: for a K&R-style definition, the type of the definition
1756       // isn't the same as the type of a use.  Correct for this with a
1757       // bitcast.
1758       QualType NoProtoType =
1759           CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1760       NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1761       V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
1762     }
1763   }
1764   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
1765   return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1766 }
1767 
1768 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1769   const NamedDecl *ND = E->getDecl();
1770   CharUnits Alignment = getContext().getDeclAlign(ND);
1771   QualType T = E->getType();
1772 
1773   // A DeclRefExpr for a reference initialized by a constant expression can
1774   // appear without being odr-used. Directly emit the constant initializer.
1775   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1776     const Expr *Init = VD->getAnyInitializer(VD);
1777     if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1778         VD->isUsableInConstantExpressions(getContext()) &&
1779         VD->checkInitIsICE()) {
1780       llvm::Constant *Val =
1781         CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1782       assert(Val && "failed to emit reference constant expression");
1783       // FIXME: Eventually we will want to emit vector element references.
1784       return MakeAddrLValue(Val, T, Alignment);
1785     }
1786   }
1787 
1788   // FIXME: We should be able to assert this for FunctionDecls as well!
1789   // FIXME: We should be able to assert this for all DeclRefExprs, not just
1790   // those with a valid source location.
1791   assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1792           !E->getLocation().isValid()) &&
1793          "Should not use decl without marking it used!");
1794 
1795   if (ND->hasAttr<WeakRefAttr>()) {
1796     const ValueDecl *VD = cast<ValueDecl>(ND);
1797     llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1798     return MakeAddrLValue(Aliasee, T, Alignment);
1799   }
1800 
1801   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1802     // Check if this is a global variable.
1803     if (VD->hasExternalStorage() || VD->isFileVarDecl())
1804       return EmitGlobalVarDeclLValue(*this, E, VD);
1805 
1806     bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1807 
1808     bool NonGCable = VD->hasLocalStorage() &&
1809                      !VD->getType()->isReferenceType() &&
1810                      !isBlockVariable;
1811 
1812     llvm::Value *V = LocalDeclMap[VD];
1813     if (!V && VD->isStaticLocal())
1814       V = CGM.getStaticLocalDeclAddress(VD);
1815 
1816     // Use special handling for lambdas.
1817     if (!V) {
1818       if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1819         QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1820         LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1821                                                      LambdaTagType);
1822         return EmitLValueForField(LambdaLV, FD);
1823       }
1824 
1825       assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
1826       return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
1827                             T, Alignment);
1828     }
1829 
1830     assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1831 
1832     if (isBlockVariable)
1833       V = BuildBlockByrefAddress(V, VD);
1834 
1835     LValue LV;
1836     if (VD->getType()->isReferenceType()) {
1837       llvm::LoadInst *LI = Builder.CreateLoad(V);
1838       LI->setAlignment(Alignment.getQuantity());
1839       V = LI;
1840       LV = MakeNaturalAlignAddrLValue(V, T);
1841     } else {
1842       LV = MakeAddrLValue(V, T, Alignment);
1843     }
1844 
1845     if (NonGCable) {
1846       LV.getQuals().removeObjCGCAttr();
1847       LV.setNonGC(true);
1848     }
1849     setObjCGCLValueClass(getContext(), E, LV);
1850     return LV;
1851   }
1852 
1853   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1854     return EmitFunctionDeclLValue(*this, E, fn);
1855 
1856   llvm_unreachable("Unhandled DeclRefExpr");
1857 }
1858 
1859 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1860   // __extension__ doesn't affect lvalue-ness.
1861   if (E->getOpcode() == UO_Extension)
1862     return EmitLValue(E->getSubExpr());
1863 
1864   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
1865   switch (E->getOpcode()) {
1866   default: llvm_unreachable("Unknown unary operator lvalue!");
1867   case UO_Deref: {
1868     QualType T = E->getSubExpr()->getType()->getPointeeType();
1869     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1870 
1871     LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
1872     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
1873 
1874     // We should not generate __weak write barrier on indirect reference
1875     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1876     // But, we continue to generate __strong write barrier on indirect write
1877     // into a pointer to object.
1878     if (getContext().getLangOpts().ObjC1 &&
1879         getContext().getLangOpts().getGC() != LangOptions::NonGC &&
1880         LV.isObjCWeak())
1881       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
1882     return LV;
1883   }
1884   case UO_Real:
1885   case UO_Imag: {
1886     LValue LV = EmitLValue(E->getSubExpr());
1887     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1888     llvm::Value *Addr = LV.getAddress();
1889 
1890     // __real is valid on scalars.  This is a faster way of testing that.
1891     // __imag can only produce an rvalue on scalars.
1892     if (E->getOpcode() == UO_Real &&
1893         !cast<llvm::PointerType>(Addr->getType())
1894            ->getElementType()->isStructTy()) {
1895       assert(E->getSubExpr()->getType()->isArithmeticType());
1896       return LV;
1897     }
1898 
1899     assert(E->getSubExpr()->getType()->isAnyComplexType());
1900 
1901     unsigned Idx = E->getOpcode() == UO_Imag;
1902     return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
1903                                                   Idx, "idx"),
1904                           ExprTy);
1905   }
1906   case UO_PreInc:
1907   case UO_PreDec: {
1908     LValue LV = EmitLValue(E->getSubExpr());
1909     bool isInc = E->getOpcode() == UO_PreInc;
1910 
1911     if (E->getType()->isAnyComplexType())
1912       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1913     else
1914       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1915     return LV;
1916   }
1917   }
1918 }
1919 
1920 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
1921   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1922                         E->getType());
1923 }
1924 
1925 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
1926   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1927                         E->getType());
1928 }
1929 
1930 static llvm::Constant*
1931 GetAddrOfConstantWideString(StringRef Str,
1932                             const char *GlobalName,
1933                             ASTContext &Context,
1934                             QualType Ty, SourceLocation Loc,
1935                             CodeGenModule &CGM) {
1936 
1937   StringLiteral *SL = StringLiteral::Create(Context,
1938                                             Str,
1939                                             StringLiteral::Wide,
1940                                             /*Pascal = */false,
1941                                             Ty, Loc);
1942   llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1943   llvm::GlobalVariable *GV =
1944     new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1945                              !CGM.getLangOpts().WritableStrings,
1946                              llvm::GlobalValue::PrivateLinkage,
1947                              C, GlobalName);
1948   const unsigned WideAlignment =
1949     Context.getTypeAlignInChars(Ty).getQuantity();
1950   GV->setAlignment(WideAlignment);
1951   return GV;
1952 }
1953 
1954 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1955                                     SmallString<32>& Target) {
1956   Target.resize(CharByteWidth * (Source.size() + 1));
1957   char *ResultPtr = &Target[0];
1958   const UTF8 *ErrorPtr;
1959   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
1960   (void)success;
1961   assert(success);
1962   Target.resize(ResultPtr - &Target[0]);
1963 }
1964 
1965 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
1966   switch (E->getIdentType()) {
1967   default:
1968     return EmitUnsupportedLValue(E, "predefined expression");
1969 
1970   case PredefinedExpr::Func:
1971   case PredefinedExpr::Function:
1972   case PredefinedExpr::LFunction:
1973   case PredefinedExpr::PrettyFunction: {
1974     unsigned IdentType = E->getIdentType();
1975     std::string GlobalVarName;
1976 
1977     switch (IdentType) {
1978     default: llvm_unreachable("Invalid type");
1979     case PredefinedExpr::Func:
1980       GlobalVarName = "__func__.";
1981       break;
1982     case PredefinedExpr::Function:
1983       GlobalVarName = "__FUNCTION__.";
1984       break;
1985     case PredefinedExpr::LFunction:
1986       GlobalVarName = "L__FUNCTION__.";
1987       break;
1988     case PredefinedExpr::PrettyFunction:
1989       GlobalVarName = "__PRETTY_FUNCTION__.";
1990       break;
1991     }
1992 
1993     StringRef FnName = CurFn->getName();
1994     if (FnName.startswith("\01"))
1995       FnName = FnName.substr(1);
1996     GlobalVarName += FnName;
1997 
1998     const Decl *CurDecl = CurCodeDecl;
1999     if (CurDecl == 0)
2000       CurDecl = getContext().getTranslationUnitDecl();
2001 
2002     std::string FunctionName =
2003         (isa<BlockDecl>(CurDecl)
2004          ? FnName.str()
2005          : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
2006                                        CurDecl));
2007 
2008     const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
2009     llvm::Constant *C;
2010     if (ElemType->isWideCharType()) {
2011       SmallString<32> RawChars;
2012       ConvertUTF8ToWideString(
2013           getContext().getTypeSizeInChars(ElemType).getQuantity(),
2014           FunctionName, RawChars);
2015       C = GetAddrOfConstantWideString(RawChars,
2016                                       GlobalVarName.c_str(),
2017                                       getContext(),
2018                                       E->getType(),
2019                                       E->getLocation(),
2020                                       CGM);
2021     } else {
2022       C = CGM.GetAddrOfConstantCString(FunctionName,
2023                                        GlobalVarName.c_str(),
2024                                        1);
2025     }
2026     return MakeAddrLValue(C, E->getType());
2027   }
2028   }
2029 }
2030 
2031 /// Emit a type description suitable for use by a runtime sanitizer library. The
2032 /// format of a type descriptor is
2033 ///
2034 /// \code
2035 ///   { i16 TypeKind, i16 TypeInfo }
2036 /// \endcode
2037 ///
2038 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2039 /// integer, 1 for a floating point value, and -1 for anything else.
2040 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2041   // FIXME: Only emit each type's descriptor once.
2042   uint16_t TypeKind = -1;
2043   uint16_t TypeInfo = 0;
2044 
2045   if (T->isIntegerType()) {
2046     TypeKind = 0;
2047     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2048                T->isSignedIntegerType();
2049   } else if (T->isFloatingType()) {
2050     TypeKind = 1;
2051     TypeInfo = getContext().getTypeSize(T);
2052   }
2053 
2054   // Format the type name as if for a diagnostic, including quotes and
2055   // optionally an 'aka'.
2056   llvm::SmallString<32> Buffer;
2057   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2058                                     (intptr_t)T.getAsOpaquePtr(),
2059                                     0, 0, 0, 0, 0, 0, Buffer,
2060                                     ArrayRef<intptr_t>());
2061 
2062   llvm::Constant *Components[] = {
2063     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2064     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2065   };
2066   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2067 
2068   llvm::GlobalVariable *GV =
2069     new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
2070                              /*isConstant=*/true,
2071                              llvm::GlobalVariable::PrivateLinkage,
2072                              Descriptor);
2073   GV->setUnnamedAddr(true);
2074   return GV;
2075 }
2076 
2077 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2078   llvm::Type *TargetTy = IntPtrTy;
2079 
2080   // Integers which fit in intptr_t are zero-extended and passed directly.
2081   if (V->getType()->isIntegerTy() &&
2082       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2083     return Builder.CreateZExt(V, TargetTy);
2084 
2085   // Pointers are passed directly, everything else is passed by address.
2086   if (!V->getType()->isPointerTy()) {
2087     llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
2088     Builder.CreateStore(V, Ptr);
2089     V = Ptr;
2090   }
2091   return Builder.CreatePtrToInt(V, TargetTy);
2092 }
2093 
2094 /// \brief Emit a representation of a SourceLocation for passing to a handler
2095 /// in a sanitizer runtime library. The format for this data is:
2096 /// \code
2097 ///   struct SourceLocation {
2098 ///     const char *Filename;
2099 ///     int32_t Line, Column;
2100 ///   };
2101 /// \endcode
2102 /// For an invalid SourceLocation, the Filename pointer is null.
2103 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2104   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2105 
2106   llvm::Constant *Data[] = {
2107     // FIXME: Only emit each file name once.
2108     PLoc.isValid() ? cast<llvm::Constant>(
2109                        Builder.CreateGlobalStringPtr(PLoc.getFilename()))
2110                    : llvm::Constant::getNullValue(Int8PtrTy),
2111     Builder.getInt32(PLoc.getLine()),
2112     Builder.getInt32(PLoc.getColumn())
2113   };
2114 
2115   return llvm::ConstantStruct::getAnon(Data);
2116 }
2117 
2118 void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
2119                                 llvm::ArrayRef<llvm::Constant *> StaticArgs,
2120                                 llvm::ArrayRef<llvm::Value *> DynamicArgs,
2121                                 bool Recoverable) {
2122   llvm::BasicBlock *Cont = createBasicBlock("cont");
2123 
2124   // If -fcatch-undefined-behavior is not enabled, just emit a trap. This
2125   // happens when using -ftrapv.
2126   // FIXME: Should -ftrapv require the ubsan runtime library?
2127   if (!CatchUndefined) {
2128     // If we're optimizing, collapse all calls to trap down to just one per
2129     // function to save on code size.
2130     if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2131       TrapBB = createBasicBlock("trap");
2132       Builder.CreateCondBr(Checked, Cont, TrapBB);
2133       EmitBlock(TrapBB);
2134       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2135       llvm::CallInst *TrapCall = Builder.CreateCall(F);
2136       TrapCall->setDoesNotReturn();
2137       TrapCall->setDoesNotThrow();
2138       Builder.CreateUnreachable();
2139     } else {
2140       Builder.CreateCondBr(Checked, Cont, TrapBB);
2141     }
2142 
2143     EmitBlock(Cont);
2144     return;
2145   }
2146 
2147   llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
2148   Builder.CreateCondBr(Checked, Cont, Handler);
2149   EmitBlock(Handler);
2150 
2151   llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2152   llvm::GlobalValue *InfoPtr =
2153       new llvm::GlobalVariable(CGM.getModule(), Info->getType(), true,
2154                                llvm::GlobalVariable::PrivateLinkage, Info);
2155   InfoPtr->setUnnamedAddr(true);
2156 
2157   llvm::SmallVector<llvm::Value *, 4> Args;
2158   llvm::SmallVector<llvm::Type *, 4> ArgTypes;
2159   Args.reserve(DynamicArgs.size() + 1);
2160   ArgTypes.reserve(DynamicArgs.size() + 1);
2161 
2162   // Handler functions take an i8* pointing to the (handler-specific) static
2163   // information block, followed by a sequence of intptr_t arguments
2164   // representing operand values.
2165   Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2166   ArgTypes.push_back(Int8PtrTy);
2167   for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2168     Args.push_back(EmitCheckValue(DynamicArgs[i]));
2169     ArgTypes.push_back(IntPtrTy);
2170   }
2171 
2172   llvm::FunctionType *FnType =
2173     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2174   llvm::AttrBuilder B;
2175   if (!Recoverable) {
2176     B.addAttribute(llvm::Attributes::NoReturn)
2177      .addAttribute(llvm::Attributes::NoUnwind);
2178   }
2179   B.addAttribute(llvm::Attributes::UWTable);
2180   llvm::Value *Fn = CGM.CreateRuntimeFunction(FnType,
2181                                           ("__ubsan_handle_" + CheckName).str(),
2182                                          llvm::Attributes::get(getLLVMContext(),
2183                                                                B));
2184   llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
2185   if (Recoverable) {
2186     Builder.CreateBr(Cont);
2187   } else {
2188     HandlerCall->setDoesNotReturn();
2189     HandlerCall->setDoesNotThrow();
2190     Builder.CreateUnreachable();
2191   }
2192 
2193   EmitBlock(Cont);
2194 }
2195 
2196 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2197 /// array to pointer, return the array subexpression.
2198 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2199   // If this isn't just an array->pointer decay, bail out.
2200   const CastExpr *CE = dyn_cast<CastExpr>(E);
2201   if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
2202     return 0;
2203 
2204   // If this is a decay from variable width array, bail out.
2205   const Expr *SubExpr = CE->getSubExpr();
2206   if (SubExpr->getType()->isVariableArrayType())
2207     return 0;
2208 
2209   return SubExpr;
2210 }
2211 
2212 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2213   // The index must always be an integer, which is not an aggregate.  Emit it.
2214   llvm::Value *Idx = EmitScalarExpr(E->getIdx());
2215   QualType IdxTy  = E->getIdx()->getType();
2216   bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2217 
2218   // If the base is a vector type, then we are forming a vector element lvalue
2219   // with this subscript.
2220   if (E->getBase()->getType()->isVectorType()) {
2221     // Emit the vector as an lvalue to get its address.
2222     LValue LHS = EmitLValue(E->getBase());
2223     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2224     Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
2225     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2226                                  E->getBase()->getType(), LHS.getAlignment());
2227   }
2228 
2229   // Extend or truncate the index type to 32 or 64-bits.
2230   if (Idx->getType() != IntPtrTy)
2231     Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2232 
2233   // We know that the pointer points to a type of the correct size, unless the
2234   // size is a VLA or Objective-C interface.
2235   llvm::Value *Address = 0;
2236   CharUnits ArrayAlignment;
2237   if (const VariableArrayType *vla =
2238         getContext().getAsVariableArrayType(E->getType())) {
2239     // The base must be a pointer, which is not an aggregate.  Emit
2240     // it.  It needs to be emitted first in case it's what captures
2241     // the VLA bounds.
2242     Address = EmitScalarExpr(E->getBase());
2243 
2244     // The element count here is the total number of non-VLA elements.
2245     llvm::Value *numElements = getVLASize(vla).first;
2246 
2247     // Effectively, the multiply by the VLA size is part of the GEP.
2248     // GEP indexes are signed, and scaling an index isn't permitted to
2249     // signed-overflow, so we use the same semantics for our explicit
2250     // multiply.  We suppress this if overflow is not undefined behavior.
2251     if (getLangOpts().isSignedOverflowDefined()) {
2252       Idx = Builder.CreateMul(Idx, numElements);
2253       Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2254     } else {
2255       Idx = Builder.CreateNSWMul(Idx, numElements);
2256       Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
2257     }
2258   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2259     // Indexing over an interface, as in "NSString *P; P[4];"
2260     llvm::Value *InterfaceSize =
2261       llvm::ConstantInt::get(Idx->getType(),
2262           getContext().getTypeSizeInChars(OIT).getQuantity());
2263 
2264     Idx = Builder.CreateMul(Idx, InterfaceSize);
2265 
2266     // The base must be a pointer, which is not an aggregate.  Emit it.
2267     llvm::Value *Base = EmitScalarExpr(E->getBase());
2268     Address = EmitCastToVoidPtr(Base);
2269     Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2270     Address = Builder.CreateBitCast(Address, Base->getType());
2271   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2272     // If this is A[i] where A is an array, the frontend will have decayed the
2273     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
2274     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2275     // "gep x, i" here.  Emit one "gep A, 0, i".
2276     assert(Array->getType()->isArrayType() &&
2277            "Array to pointer decay must have array source type!");
2278     LValue ArrayLV = EmitLValue(Array);
2279     llvm::Value *ArrayPtr = ArrayLV.getAddress();
2280     llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2281     llvm::Value *Args[] = { Zero, Idx };
2282 
2283     // Propagate the alignment from the array itself to the result.
2284     ArrayAlignment = ArrayLV.getAlignment();
2285 
2286     if (getContext().getLangOpts().isSignedOverflowDefined())
2287       Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
2288     else
2289       Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
2290   } else {
2291     // The base must be a pointer, which is not an aggregate.  Emit it.
2292     llvm::Value *Base = EmitScalarExpr(E->getBase());
2293     if (getContext().getLangOpts().isSignedOverflowDefined())
2294       Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2295     else
2296       Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
2297   }
2298 
2299   QualType T = E->getBase()->getType()->getPointeeType();
2300   assert(!T.isNull() &&
2301          "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
2302 
2303 
2304   // Limit the alignment to that of the result type.
2305   LValue LV;
2306   if (!ArrayAlignment.isZero()) {
2307     CharUnits Align = getContext().getTypeAlignInChars(T);
2308     ArrayAlignment = std::min(Align, ArrayAlignment);
2309     LV = MakeAddrLValue(Address, T, ArrayAlignment);
2310   } else {
2311     LV = MakeNaturalAlignAddrLValue(Address, T);
2312   }
2313 
2314   LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
2315 
2316   if (getContext().getLangOpts().ObjC1 &&
2317       getContext().getLangOpts().getGC() != LangOptions::NonGC) {
2318     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2319     setObjCGCLValueClass(getContext(), E, LV);
2320   }
2321   return LV;
2322 }
2323 
2324 static
2325 llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
2326                                        SmallVector<unsigned, 4> &Elts) {
2327   SmallVector<llvm::Constant*, 4> CElts;
2328   for (unsigned i = 0, e = Elts.size(); i != e; ++i)
2329     CElts.push_back(Builder.getInt32(Elts[i]));
2330 
2331   return llvm::ConstantVector::get(CElts);
2332 }
2333 
2334 LValue CodeGenFunction::
2335 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
2336   // Emit the base vector as an l-value.
2337   LValue Base;
2338 
2339   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
2340   if (E->isArrow()) {
2341     // If it is a pointer to a vector, emit the address and form an lvalue with
2342     // it.
2343     llvm::Value *Ptr = EmitScalarExpr(E->getBase());
2344     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
2345     Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2346     Base.getQuals().removeObjCGCAttr();
2347   } else if (E->getBase()->isGLValue()) {
2348     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2349     // emit the base as an lvalue.
2350     assert(E->getBase()->getType()->isVectorType());
2351     Base = EmitLValue(E->getBase());
2352   } else {
2353     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
2354     assert(E->getBase()->getType()->isVectorType() &&
2355            "Result must be a vector");
2356     llvm::Value *Vec = EmitScalarExpr(E->getBase());
2357 
2358     // Store the vector to memory (because LValue wants an address).
2359     llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
2360     Builder.CreateStore(Vec, VecMem);
2361     Base = MakeAddrLValue(VecMem, E->getBase()->getType());
2362   }
2363 
2364   QualType type =
2365     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
2366 
2367   // Encode the element access list into a vector of unsigned indices.
2368   SmallVector<unsigned, 4> Indices;
2369   E->getEncodedElementAccess(Indices);
2370 
2371   if (Base.isSimple()) {
2372     llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
2373     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2374                                     Base.getAlignment());
2375   }
2376   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2377 
2378   llvm::Constant *BaseElts = Base.getExtVectorElts();
2379   SmallVector<llvm::Constant *, 4> CElts;
2380 
2381   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2382     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
2383   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2384   return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2385                                   Base.getAlignment());
2386 }
2387 
2388 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
2389   Expr *BaseExpr = E->getBase();
2390 
2391   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
2392   LValue BaseLV;
2393   if (E->isArrow()) {
2394     llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2395     QualType PtrTy = BaseExpr->getType()->getPointeeType();
2396     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
2397     BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2398   } else
2399     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
2400 
2401   NamedDecl *ND = E->getMemberDecl();
2402   if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
2403     LValue LV = EmitLValueForField(BaseLV, Field);
2404     setObjCGCLValueClass(getContext(), E, LV);
2405     return LV;
2406   }
2407 
2408   if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2409     return EmitGlobalVarDeclLValue(*this, E, VD);
2410 
2411   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2412     return EmitFunctionDeclLValue(*this, E, FD);
2413 
2414   llvm_unreachable("Unhandled member declaration!");
2415 }
2416 
2417 LValue CodeGenFunction::EmitLValueForField(LValue base,
2418                                            const FieldDecl *field) {
2419   if (field->isBitField()) {
2420     const CGRecordLayout &RL =
2421       CGM.getTypes().getCGRecordLayout(field->getParent());
2422     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
2423     QualType fieldType =
2424       field->getType().withCVRQualifiers(base.getVRQualifiers());
2425     return LValue::MakeBitfield(base.getAddress(), Info, fieldType,
2426                                 base.getAlignment());
2427   }
2428 
2429   const RecordDecl *rec = field->getParent();
2430   QualType type = field->getType();
2431   CharUnits alignment = getContext().getDeclAlign(field);
2432 
2433   // FIXME: It should be impossible to have an LValue without alignment for a
2434   // complete type.
2435   if (!base.getAlignment().isZero())
2436     alignment = std::min(alignment, base.getAlignment());
2437 
2438   bool mayAlias = rec->hasAttr<MayAliasAttr>();
2439 
2440   llvm::Value *addr = base.getAddress();
2441   unsigned cvr = base.getVRQualifiers();
2442   if (rec->isUnion()) {
2443     // For unions, there is no pointer adjustment.
2444     assert(!type->isReferenceType() && "union has reference member");
2445   } else {
2446     // For structs, we GEP to the field that the record layout suggests.
2447     unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
2448     addr = Builder.CreateStructGEP(addr, idx, field->getName());
2449 
2450     // If this is a reference field, load the reference right now.
2451     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2452       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2453       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
2454       load->setAlignment(alignment.getQuantity());
2455 
2456       if (CGM.shouldUseTBAA()) {
2457         llvm::MDNode *tbaa;
2458         if (mayAlias)
2459           tbaa = CGM.getTBAAInfo(getContext().CharTy);
2460         else
2461           tbaa = CGM.getTBAAInfo(type);
2462         CGM.DecorateInstruction(load, tbaa);
2463       }
2464 
2465       addr = load;
2466       mayAlias = false;
2467       type = refType->getPointeeType();
2468       if (type->isIncompleteType())
2469         alignment = CharUnits();
2470       else
2471         alignment = getContext().getTypeAlignInChars(type);
2472       cvr = 0; // qualifiers don't recursively apply to referencee
2473     }
2474   }
2475 
2476   // Make sure that the address is pointing to the right type.  This is critical
2477   // for both unions and structs.  A union needs a bitcast, a struct element
2478   // will need a bitcast if the LLVM type laid out doesn't match the desired
2479   // type.
2480   addr = EmitBitCastOfLValueToProperType(*this, addr,
2481                                          CGM.getTypes().ConvertTypeForMem(type),
2482                                          field->getName());
2483 
2484   if (field->hasAttr<AnnotateAttr>())
2485     addr = EmitFieldAnnotations(field, addr);
2486 
2487   LValue LV = MakeAddrLValue(addr, type, alignment);
2488   LV.getQuals().addCVRQualifiers(cvr);
2489 
2490   // __weak attribute on a field is ignored.
2491   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2492     LV.getQuals().removeObjCGCAttr();
2493 
2494   // Fields of may_alias structs act like 'char' for TBAA purposes.
2495   // FIXME: this should get propagated down through anonymous structs
2496   // and unions.
2497   if (mayAlias && LV.getTBAAInfo())
2498     LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2499 
2500   return LV;
2501 }
2502 
2503 LValue
2504 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2505                                                   const FieldDecl *Field) {
2506   QualType FieldType = Field->getType();
2507 
2508   if (!FieldType->isReferenceType())
2509     return EmitLValueForField(Base, Field);
2510 
2511   const CGRecordLayout &RL =
2512     CGM.getTypes().getCGRecordLayout(Field->getParent());
2513   unsigned idx = RL.getLLVMFieldNo(Field);
2514   llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
2515   assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2516 
2517   // Make sure that the address is pointing to the right type.  This is critical
2518   // for both unions and structs.  A union needs a bitcast, a struct element
2519   // will need a bitcast if the LLVM type laid out doesn't match the desired
2520   // type.
2521   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
2522   V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2523 
2524   CharUnits Alignment = getContext().getDeclAlign(Field);
2525 
2526   // FIXME: It should be impossible to have an LValue without alignment for a
2527   // complete type.
2528   if (!Base.getAlignment().isZero())
2529     Alignment = std::min(Alignment, Base.getAlignment());
2530 
2531   return MakeAddrLValue(V, FieldType, Alignment);
2532 }
2533 
2534 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
2535   if (E->isFileScope()) {
2536     llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2537     return MakeAddrLValue(GlobalPtr, E->getType());
2538   }
2539   if (E->getType()->isVariablyModifiedType())
2540     // make sure to emit the VLA size.
2541     EmitVariablyModifiedType(E->getType());
2542 
2543   llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
2544   const Expr *InitExpr = E->getInitializer();
2545   LValue Result = MakeAddrLValue(DeclPtr, E->getType());
2546 
2547   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2548                    /*Init*/ true);
2549 
2550   return Result;
2551 }
2552 
2553 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2554   if (!E->isGLValue())
2555     // Initializing an aggregate temporary in C++11: T{...}.
2556     return EmitAggExprToLValue(E);
2557 
2558   // An lvalue initializer list must be initializing a reference.
2559   assert(E->getNumInits() == 1 && "reference init with multiple values");
2560   return EmitLValue(E->getInit(0));
2561 }
2562 
2563 LValue CodeGenFunction::
2564 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2565   if (!expr->isGLValue()) {
2566     // ?: here should be an aggregate.
2567     assert((hasAggregateLLVMType(expr->getType()) &&
2568             !expr->getType()->isAnyComplexType()) &&
2569            "Unexpected conditional operator!");
2570     return EmitAggExprToLValue(expr);
2571   }
2572 
2573   OpaqueValueMapping binding(*this, expr);
2574 
2575   const Expr *condExpr = expr->getCond();
2576   bool CondExprBool;
2577   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2578     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
2579     if (!CondExprBool) std::swap(live, dead);
2580 
2581     if (!ContainsLabel(dead))
2582       return EmitLValue(live);
2583   }
2584 
2585   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2586   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2587   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
2588 
2589   ConditionalEvaluation eval(*this);
2590   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
2591 
2592   // Any temporaries created here are conditional.
2593   EmitBlock(lhsBlock);
2594   eval.begin(*this);
2595   LValue lhs = EmitLValue(expr->getTrueExpr());
2596   eval.end(*this);
2597 
2598   if (!lhs.isSimple())
2599     return EmitUnsupportedLValue(expr, "conditional operator");
2600 
2601   lhsBlock = Builder.GetInsertBlock();
2602   Builder.CreateBr(contBlock);
2603 
2604   // Any temporaries created here are conditional.
2605   EmitBlock(rhsBlock);
2606   eval.begin(*this);
2607   LValue rhs = EmitLValue(expr->getFalseExpr());
2608   eval.end(*this);
2609   if (!rhs.isSimple())
2610     return EmitUnsupportedLValue(expr, "conditional operator");
2611   rhsBlock = Builder.GetInsertBlock();
2612 
2613   EmitBlock(contBlock);
2614 
2615   llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
2616                                          "cond-lvalue");
2617   phi->addIncoming(lhs.getAddress(), lhsBlock);
2618   phi->addIncoming(rhs.getAddress(), rhsBlock);
2619   return MakeAddrLValue(phi, expr->getType());
2620 }
2621 
2622 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2623 /// type. If the cast is to a reference, we can have the usual lvalue result,
2624 /// otherwise if a cast is needed by the code generator in an lvalue context,
2625 /// then it must mean that we need the address of an aggregate in order to
2626 /// access one of its members.  This can happen for all the reasons that casts
2627 /// are permitted with aggregate result, including noop aggregate casts, and
2628 /// cast from scalar to union.
2629 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
2630   switch (E->getCastKind()) {
2631   case CK_ToVoid:
2632     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
2633 
2634   case CK_Dependent:
2635     llvm_unreachable("dependent cast kind in IR gen!");
2636 
2637   case CK_BuiltinFnToFnPtr:
2638     llvm_unreachable("builtin functions are handled elsewhere");
2639 
2640   // These two casts are currently treated as no-ops, although they could
2641   // potentially be real operations depending on the target's ABI.
2642   case CK_NonAtomicToAtomic:
2643   case CK_AtomicToNonAtomic:
2644 
2645   case CK_NoOp:
2646   case CK_LValueToRValue:
2647     if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2648         || E->getType()->isRecordType())
2649       return EmitLValue(E->getSubExpr());
2650     // Fall through to synthesize a temporary.
2651 
2652   case CK_BitCast:
2653   case CK_ArrayToPointerDecay:
2654   case CK_FunctionToPointerDecay:
2655   case CK_NullToMemberPointer:
2656   case CK_NullToPointer:
2657   case CK_IntegralToPointer:
2658   case CK_PointerToIntegral:
2659   case CK_PointerToBoolean:
2660   case CK_VectorSplat:
2661   case CK_IntegralCast:
2662   case CK_IntegralToBoolean:
2663   case CK_IntegralToFloating:
2664   case CK_FloatingToIntegral:
2665   case CK_FloatingToBoolean:
2666   case CK_FloatingCast:
2667   case CK_FloatingRealToComplex:
2668   case CK_FloatingComplexToReal:
2669   case CK_FloatingComplexToBoolean:
2670   case CK_FloatingComplexCast:
2671   case CK_FloatingComplexToIntegralComplex:
2672   case CK_IntegralRealToComplex:
2673   case CK_IntegralComplexToReal:
2674   case CK_IntegralComplexToBoolean:
2675   case CK_IntegralComplexCast:
2676   case CK_IntegralComplexToFloatingComplex:
2677   case CK_DerivedToBaseMemberPointer:
2678   case CK_BaseToDerivedMemberPointer:
2679   case CK_MemberPointerToBoolean:
2680   case CK_ReinterpretMemberPointer:
2681   case CK_AnyPointerToBlockPointerCast:
2682   case CK_ARCProduceObject:
2683   case CK_ARCConsumeObject:
2684   case CK_ARCReclaimReturnedObject:
2685   case CK_ARCExtendBlockObject:
2686   case CK_CopyAndAutoreleaseBlockObject: {
2687     // These casts only produce lvalues when we're binding a reference to a
2688     // temporary realized from a (converted) pure rvalue. Emit the expression
2689     // as a value, copy it into a temporary, and return an lvalue referring to
2690     // that temporary.
2691     llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
2692     EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
2693     return MakeAddrLValue(V, E->getType());
2694   }
2695 
2696   case CK_Dynamic: {
2697     LValue LV = EmitLValue(E->getSubExpr());
2698     llvm::Value *V = LV.getAddress();
2699     const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
2700     return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
2701   }
2702 
2703   case CK_ConstructorConversion:
2704   case CK_UserDefinedConversion:
2705   case CK_CPointerToObjCPointerCast:
2706   case CK_BlockPointerToObjCPointerCast:
2707     return EmitLValue(E->getSubExpr());
2708 
2709   case CK_UncheckedDerivedToBase:
2710   case CK_DerivedToBase: {
2711     const RecordType *DerivedClassTy =
2712       E->getSubExpr()->getType()->getAs<RecordType>();
2713     CXXRecordDecl *DerivedClassDecl =
2714       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2715 
2716     LValue LV = EmitLValue(E->getSubExpr());
2717     llvm::Value *This = LV.getAddress();
2718 
2719     // Perform the derived-to-base conversion
2720     llvm::Value *Base =
2721       GetAddressOfBaseClass(This, DerivedClassDecl,
2722                             E->path_begin(), E->path_end(),
2723                             /*NullCheckValue=*/false);
2724 
2725     return MakeAddrLValue(Base, E->getType());
2726   }
2727   case CK_ToUnion:
2728     return EmitAggExprToLValue(E);
2729   case CK_BaseToDerived: {
2730     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2731     CXXRecordDecl *DerivedClassDecl =
2732       cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2733 
2734     LValue LV = EmitLValue(E->getSubExpr());
2735 
2736     // Perform the base-to-derived conversion
2737     llvm::Value *Derived =
2738       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
2739                                E->path_begin(), E->path_end(),
2740                                /*NullCheckValue=*/false);
2741 
2742     return MakeAddrLValue(Derived, E->getType());
2743   }
2744   case CK_LValueBitCast: {
2745     // This must be a reinterpret_cast (or c-style equivalent).
2746     const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
2747 
2748     LValue LV = EmitLValue(E->getSubExpr());
2749     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2750                                            ConvertType(CE->getTypeAsWritten()));
2751     return MakeAddrLValue(V, E->getType());
2752   }
2753   case CK_ObjCObjectLValueCast: {
2754     LValue LV = EmitLValue(E->getSubExpr());
2755     QualType ToType = getContext().getLValueReferenceType(E->getType());
2756     llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2757                                            ConvertType(ToType));
2758     return MakeAddrLValue(V, E->getType());
2759   }
2760   }
2761 
2762   llvm_unreachable("Unhandled lvalue cast kind?");
2763 }
2764 
2765 LValue CodeGenFunction::EmitNullInitializationLValue(
2766                                               const CXXScalarValueInitExpr *E) {
2767   QualType Ty = E->getType();
2768   LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
2769   EmitNullInitialization(LV.getAddress(), Ty);
2770   return LV;
2771 }
2772 
2773 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
2774   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
2775   return getOpaqueLValueMapping(e);
2776 }
2777 
2778 LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2779                                            const MaterializeTemporaryExpr *E) {
2780   RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
2781   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2782 }
2783 
2784 RValue CodeGenFunction::EmitRValueForField(LValue LV,
2785                                            const FieldDecl *FD) {
2786   QualType FT = FD->getType();
2787   LValue FieldLV = EmitLValueForField(LV, FD);
2788   if (FT->isAnyComplexType())
2789     return RValue::getComplex(
2790         LoadComplexFromAddr(FieldLV.getAddress(),
2791                             FieldLV.isVolatileQualified()));
2792   else if (CodeGenFunction::hasAggregateLLVMType(FT))
2793     return FieldLV.asAggregateRValue();
2794 
2795   return EmitLoadOfLValue(FieldLV);
2796 }
2797 
2798 //===--------------------------------------------------------------------===//
2799 //                             Expression Emission
2800 //===--------------------------------------------------------------------===//
2801 
2802 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2803                                      ReturnValueSlot ReturnValue) {
2804   if (CGDebugInfo *DI = getDebugInfo())
2805     DI->EmitLocation(Builder, E->getLocStart());
2806 
2807   // Builtins never have block type.
2808   if (E->getCallee()->getType()->isBlockPointerType())
2809     return EmitBlockCallExpr(E, ReturnValue);
2810 
2811   if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
2812     return EmitCXXMemberCallExpr(CE, ReturnValue);
2813 
2814   if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2815     return EmitCUDAKernelCallExpr(CE, ReturnValue);
2816 
2817   const Decl *TargetDecl = E->getCalleeDecl();
2818   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2819     if (unsigned builtinID = FD->getBuiltinID())
2820       return EmitBuiltinExpr(FD, builtinID, E);
2821   }
2822 
2823   if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
2824     if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
2825       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
2826 
2827   if (const CXXPseudoDestructorExpr *PseudoDtor
2828           = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2829     QualType DestroyedType = PseudoDtor->getDestroyedType();
2830     if (getContext().getLangOpts().ObjCAutoRefCount &&
2831         DestroyedType->isObjCLifetimeType() &&
2832         (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2833          DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
2834       // Automatic Reference Counting:
2835       //   If the pseudo-expression names a retainable object with weak or
2836       //   strong lifetime, the object shall be released.
2837       Expr *BaseExpr = PseudoDtor->getBase();
2838       llvm::Value *BaseValue = NULL;
2839       Qualifiers BaseQuals;
2840 
2841       // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2842       if (PseudoDtor->isArrow()) {
2843         BaseValue = EmitScalarExpr(BaseExpr);
2844         const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2845         BaseQuals = PTy->getPointeeType().getQualifiers();
2846       } else {
2847         LValue BaseLV = EmitLValue(BaseExpr);
2848         BaseValue = BaseLV.getAddress();
2849         QualType BaseTy = BaseExpr->getType();
2850         BaseQuals = BaseTy.getQualifiers();
2851       }
2852 
2853       switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2854       case Qualifiers::OCL_None:
2855       case Qualifiers::OCL_ExplicitNone:
2856       case Qualifiers::OCL_Autoreleasing:
2857         break;
2858 
2859       case Qualifiers::OCL_Strong:
2860         EmitARCRelease(Builder.CreateLoad(BaseValue,
2861                           PseudoDtor->getDestroyedType().isVolatileQualified()),
2862                        /*precise*/ true);
2863         break;
2864 
2865       case Qualifiers::OCL_Weak:
2866         EmitARCDestroyWeak(BaseValue);
2867         break;
2868       }
2869     } else {
2870       // C++ [expr.pseudo]p1:
2871       //   The result shall only be used as the operand for the function call
2872       //   operator (), and the result of such a call has type void. The only
2873       //   effect is the evaluation of the postfix-expression before the dot or
2874       //   arrow.
2875       EmitScalarExpr(E->getCallee());
2876     }
2877 
2878     return RValue::get(0);
2879   }
2880 
2881   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
2882   return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
2883                   E->arg_begin(), E->arg_end(), TargetDecl);
2884 }
2885 
2886 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
2887   // Comma expressions just emit their LHS then their RHS as an l-value.
2888   if (E->getOpcode() == BO_Comma) {
2889     EmitIgnoredExpr(E->getLHS());
2890     EnsureInsertPoint();
2891     return EmitLValue(E->getRHS());
2892   }
2893 
2894   if (E->getOpcode() == BO_PtrMemD ||
2895       E->getOpcode() == BO_PtrMemI)
2896     return EmitPointerToDataMemberBinaryExpr(E);
2897 
2898   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
2899 
2900   // Note that in all of these cases, __block variables need the RHS
2901   // evaluated first just in case the variable gets moved by the RHS.
2902 
2903   if (!hasAggregateLLVMType(E->getType())) {
2904     switch (E->getLHS()->getType().getObjCLifetime()) {
2905     case Qualifiers::OCL_Strong:
2906       return EmitARCStoreStrong(E, /*ignored*/ false).first;
2907 
2908     case Qualifiers::OCL_Autoreleasing:
2909       return EmitARCStoreAutoreleasing(E).first;
2910 
2911     // No reason to do any of these differently.
2912     case Qualifiers::OCL_None:
2913     case Qualifiers::OCL_ExplicitNone:
2914     case Qualifiers::OCL_Weak:
2915       break;
2916     }
2917 
2918     RValue RV = EmitAnyExpr(E->getRHS());
2919     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
2920     EmitStoreThroughLValue(RV, LV);
2921     return LV;
2922   }
2923 
2924   if (E->getType()->isAnyComplexType())
2925     return EmitComplexAssignmentLValue(E);
2926 
2927   return EmitAggExprToLValue(E);
2928 }
2929 
2930 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
2931   RValue RV = EmitCallExpr(E);
2932 
2933   if (!RV.isScalar())
2934     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2935 
2936   assert(E->getCallReturnType()->isReferenceType() &&
2937          "Can't have a scalar return unless the return type is a "
2938          "reference type!");
2939 
2940   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2941 }
2942 
2943 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2944   // FIXME: This shouldn't require another copy.
2945   return EmitAggExprToLValue(E);
2946 }
2947 
2948 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
2949   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2950          && "binding l-value to type which needs a temporary");
2951   AggValueSlot Slot = CreateAggTemp(E->getType());
2952   EmitCXXConstructExpr(E, Slot);
2953   return MakeAddrLValue(Slot.getAddr(), E->getType());
2954 }
2955 
2956 LValue
2957 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
2958   return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
2959 }
2960 
2961 llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2962   return CGM.GetAddrOfUuidDescriptor(E);
2963 }
2964 
2965 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2966   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2967 }
2968 
2969 LValue
2970 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
2971   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2972   Slot.setExternallyDestructed();
2973   EmitAggExpr(E->getSubExpr(), Slot);
2974   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
2975   return MakeAddrLValue(Slot.getAddr(), E->getType());
2976 }
2977 
2978 LValue
2979 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
2980   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
2981   EmitLambdaExpr(E, Slot);
2982   return MakeAddrLValue(Slot.getAddr(), E->getType());
2983 }
2984 
2985 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
2986   RValue RV = EmitObjCMessageExpr(E);
2987 
2988   if (!RV.isScalar())
2989     return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
2990 
2991   assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2992          "Can't have a scalar return unless the return type is a "
2993          "reference type!");
2994 
2995   return MakeAddrLValue(RV.getScalarVal(), E->getType());
2996 }
2997 
2998 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2999   llvm::Value *V =
3000     CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
3001   return MakeAddrLValue(V, E->getType());
3002 }
3003 
3004 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3005                                              const ObjCIvarDecl *Ivar) {
3006   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
3007 }
3008 
3009 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3010                                           llvm::Value *BaseValue,
3011                                           const ObjCIvarDecl *Ivar,
3012                                           unsigned CVRQualifiers) {
3013   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
3014                                                    Ivar, CVRQualifiers);
3015 }
3016 
3017 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
3018   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3019   llvm::Value *BaseValue = 0;
3020   const Expr *BaseExpr = E->getBase();
3021   Qualifiers BaseQuals;
3022   QualType ObjectTy;
3023   if (E->isArrow()) {
3024     BaseValue = EmitScalarExpr(BaseExpr);
3025     ObjectTy = BaseExpr->getType()->getPointeeType();
3026     BaseQuals = ObjectTy.getQualifiers();
3027   } else {
3028     LValue BaseLV = EmitLValue(BaseExpr);
3029     // FIXME: this isn't right for bitfields.
3030     BaseValue = BaseLV.getAddress();
3031     ObjectTy = BaseExpr->getType();
3032     BaseQuals = ObjectTy.getQualifiers();
3033   }
3034 
3035   LValue LV =
3036     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3037                       BaseQuals.getCVRQualifiers());
3038   setObjCGCLValueClass(getContext(), E, LV);
3039   return LV;
3040 }
3041 
3042 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
3043   // Can only get l-value for message expression returning aggregate type
3044   RValue RV = EmitAnyExprToTemp(E);
3045   return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3046 }
3047 
3048 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
3049                                  ReturnValueSlot ReturnValue,
3050                                  CallExpr::const_arg_iterator ArgBeg,
3051                                  CallExpr::const_arg_iterator ArgEnd,
3052                                  const Decl *TargetDecl) {
3053   // Get the actual function type. The callee type will always be a pointer to
3054   // function type or a block pointer type.
3055   assert(CalleeType->isFunctionPointerType() &&
3056          "Call must have function pointer type!");
3057 
3058   CalleeType = getContext().getCanonicalType(CalleeType);
3059 
3060   const FunctionType *FnType
3061     = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
3062 
3063   CallArgList Args;
3064   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
3065 
3066   const CGFunctionInfo &FnInfo =
3067     CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
3068 
3069   // C99 6.5.2.2p6:
3070   //   If the expression that denotes the called function has a type
3071   //   that does not include a prototype, [the default argument
3072   //   promotions are performed]. If the number of arguments does not
3073   //   equal the number of parameters, the behavior is undefined. If
3074   //   the function is defined with a type that includes a prototype,
3075   //   and either the prototype ends with an ellipsis (, ...) or the
3076   //   types of the arguments after promotion are not compatible with
3077   //   the types of the parameters, the behavior is undefined. If the
3078   //   function is defined with a type that does not include a
3079   //   prototype, and the types of the arguments after promotion are
3080   //   not compatible with those of the parameters after promotion,
3081   //   the behavior is undefined [except in some trivial cases].
3082   // That is, in the general case, we should assume that a call
3083   // through an unprototyped function type works like a *non-variadic*
3084   // call.  The way we make this work is to cast to the exact type
3085   // of the promoted arguments.
3086   if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
3087     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
3088     CalleeTy = CalleeTy->getPointerTo();
3089     Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3090   }
3091 
3092   return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
3093 }
3094 
3095 LValue CodeGenFunction::
3096 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
3097   llvm::Value *BaseV;
3098   if (E->getOpcode() == BO_PtrMemI)
3099     BaseV = EmitScalarExpr(E->getLHS());
3100   else
3101     BaseV = EmitLValue(E->getLHS()).getAddress();
3102 
3103   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3104 
3105   const MemberPointerType *MPT
3106     = E->getRHS()->getType()->getAs<MemberPointerType>();
3107 
3108   llvm::Value *AddV =
3109     CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
3110 
3111   return MakeAddrLValue(AddV, MPT->getPointeeType());
3112 }
3113 
3114 static void
3115 EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
3116              llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
3117              uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
3118   llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
3119   llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
3120 
3121   switch (E->getOp()) {
3122   case AtomicExpr::AO__c11_atomic_init:
3123     llvm_unreachable("Already handled!");
3124 
3125   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3126   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3127   case AtomicExpr::AO__atomic_compare_exchange:
3128   case AtomicExpr::AO__atomic_compare_exchange_n: {
3129     // Note that cmpxchg only supports specifying one ordering and
3130     // doesn't support weak cmpxchg, at least at the moment.
3131     llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3132     LoadVal1->setAlignment(Align);
3133     llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
3134     LoadVal2->setAlignment(Align);
3135     llvm::AtomicCmpXchgInst *CXI =
3136         CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
3137     CXI->setVolatile(E->isVolatile());
3138     llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
3139     StoreVal1->setAlignment(Align);
3140     llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
3141     CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
3142     return;
3143   }
3144 
3145   case AtomicExpr::AO__c11_atomic_load:
3146   case AtomicExpr::AO__atomic_load_n:
3147   case AtomicExpr::AO__atomic_load: {
3148     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
3149     Load->setAtomic(Order);
3150     Load->setAlignment(Size);
3151     Load->setVolatile(E->isVolatile());
3152     llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3153     StoreDest->setAlignment(Align);
3154     return;
3155   }
3156 
3157   case AtomicExpr::AO__c11_atomic_store:
3158   case AtomicExpr::AO__atomic_store:
3159   case AtomicExpr::AO__atomic_store_n: {
3160     assert(!Dest && "Store does not return a value");
3161     llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3162     LoadVal1->setAlignment(Align);
3163     llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3164     Store->setAtomic(Order);
3165     Store->setAlignment(Size);
3166     Store->setVolatile(E->isVolatile());
3167     return;
3168   }
3169 
3170   case AtomicExpr::AO__c11_atomic_exchange:
3171   case AtomicExpr::AO__atomic_exchange_n:
3172   case AtomicExpr::AO__atomic_exchange:
3173     Op = llvm::AtomicRMWInst::Xchg;
3174     break;
3175 
3176   case AtomicExpr::AO__atomic_add_fetch:
3177     PostOp = llvm::Instruction::Add;
3178     // Fall through.
3179   case AtomicExpr::AO__c11_atomic_fetch_add:
3180   case AtomicExpr::AO__atomic_fetch_add:
3181     Op = llvm::AtomicRMWInst::Add;
3182     break;
3183 
3184   case AtomicExpr::AO__atomic_sub_fetch:
3185     PostOp = llvm::Instruction::Sub;
3186     // Fall through.
3187   case AtomicExpr::AO__c11_atomic_fetch_sub:
3188   case AtomicExpr::AO__atomic_fetch_sub:
3189     Op = llvm::AtomicRMWInst::Sub;
3190     break;
3191 
3192   case AtomicExpr::AO__atomic_and_fetch:
3193     PostOp = llvm::Instruction::And;
3194     // Fall through.
3195   case AtomicExpr::AO__c11_atomic_fetch_and:
3196   case AtomicExpr::AO__atomic_fetch_and:
3197     Op = llvm::AtomicRMWInst::And;
3198     break;
3199 
3200   case AtomicExpr::AO__atomic_or_fetch:
3201     PostOp = llvm::Instruction::Or;
3202     // Fall through.
3203   case AtomicExpr::AO__c11_atomic_fetch_or:
3204   case AtomicExpr::AO__atomic_fetch_or:
3205     Op = llvm::AtomicRMWInst::Or;
3206     break;
3207 
3208   case AtomicExpr::AO__atomic_xor_fetch:
3209     PostOp = llvm::Instruction::Xor;
3210     // Fall through.
3211   case AtomicExpr::AO__c11_atomic_fetch_xor:
3212   case AtomicExpr::AO__atomic_fetch_xor:
3213     Op = llvm::AtomicRMWInst::Xor;
3214     break;
3215 
3216   case AtomicExpr::AO__atomic_nand_fetch:
3217     PostOp = llvm::Instruction::And;
3218     // Fall through.
3219   case AtomicExpr::AO__atomic_fetch_nand:
3220     Op = llvm::AtomicRMWInst::Nand;
3221     break;
3222   }
3223 
3224   llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3225   LoadVal1->setAlignment(Align);
3226   llvm::AtomicRMWInst *RMWI =
3227       CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3228   RMWI->setVolatile(E->isVolatile());
3229 
3230   // For __atomic_*_fetch operations, perform the operation again to
3231   // determine the value which was written.
3232   llvm::Value *Result = RMWI;
3233   if (PostOp)
3234     Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
3235   if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3236     Result = CGF.Builder.CreateNot(Result);
3237   llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
3238   StoreDest->setAlignment(Align);
3239 }
3240 
3241 // This function emits any expression (scalar, complex, or aggregate)
3242 // into a temporary alloca.
3243 static llvm::Value *
3244 EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3245   llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
3246   CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3247                        /*Init*/ true);
3248   return DeclPtr;
3249 }
3250 
3251 static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3252                                   llvm::Value *Dest) {
3253   if (Ty->isAnyComplexType())
3254     return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3255   if (CGF.hasAggregateLLVMType(Ty))
3256     return RValue::getAggregate(Dest);
3257   return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3258 }
3259 
3260 RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3261   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
3262   QualType MemTy = AtomicTy;
3263   if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3264     MemTy = AT->getValueType();
3265   CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3266   uint64_t Size = sizeChars.getQuantity();
3267   CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3268   unsigned Align = alignChars.getQuantity();
3269   unsigned MaxInlineWidth =
3270       getContext().getTargetInfo().getMaxAtomicInlineWidth();
3271   bool UseLibcall = (Size != Align || Size > MaxInlineWidth);
3272 
3273 
3274 
3275   llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3276   Ptr = EmitScalarExpr(E->getPtr());
3277 
3278   if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
3279     assert(!Dest && "Init does not return a value");
3280     if (!hasAggregateLLVMType(E->getVal1()->getType())) {
3281       QualType PointeeType
3282         = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3283       EmitScalarInit(EmitScalarExpr(E->getVal1()),
3284                      LValue::MakeAddr(Ptr, PointeeType, alignChars,
3285                                       getContext()));
3286     } else if (E->getType()->isAnyComplexType()) {
3287       EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3288     } else {
3289       AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3290                                         AtomicTy.getQualifiers(),
3291                                         AggValueSlot::IsNotDestructed,
3292                                         AggValueSlot::DoesNotNeedGCBarriers,
3293                                         AggValueSlot::IsNotAliased);
3294       EmitAggExpr(E->getVal1(), Slot);
3295     }
3296     return RValue::get(0);
3297   }
3298 
3299   Order = EmitScalarExpr(E->getOrder());
3300 
3301   switch (E->getOp()) {
3302   case AtomicExpr::AO__c11_atomic_init:
3303     llvm_unreachable("Already handled!");
3304 
3305   case AtomicExpr::AO__c11_atomic_load:
3306   case AtomicExpr::AO__atomic_load_n:
3307     break;
3308 
3309   case AtomicExpr::AO__atomic_load:
3310     Dest = EmitScalarExpr(E->getVal1());
3311     break;
3312 
3313   case AtomicExpr::AO__atomic_store:
3314     Val1 = EmitScalarExpr(E->getVal1());
3315     break;
3316 
3317   case AtomicExpr::AO__atomic_exchange:
3318     Val1 = EmitScalarExpr(E->getVal1());
3319     Dest = EmitScalarExpr(E->getVal2());
3320     break;
3321 
3322   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3323   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3324   case AtomicExpr::AO__atomic_compare_exchange_n:
3325   case AtomicExpr::AO__atomic_compare_exchange:
3326     Val1 = EmitScalarExpr(E->getVal1());
3327     if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3328       Val2 = EmitScalarExpr(E->getVal2());
3329     else
3330       Val2 = EmitValToTemp(*this, E->getVal2());
3331     OrderFail = EmitScalarExpr(E->getOrderFail());
3332     // Evaluate and discard the 'weak' argument.
3333     if (E->getNumSubExprs() == 6)
3334       EmitScalarExpr(E->getWeak());
3335     break;
3336 
3337   case AtomicExpr::AO__c11_atomic_fetch_add:
3338   case AtomicExpr::AO__c11_atomic_fetch_sub:
3339     if (MemTy->isPointerType()) {
3340       // For pointer arithmetic, we're required to do a bit of math:
3341       // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
3342       // ... but only for the C11 builtins. The GNU builtins expect the
3343       // user to multiply by sizeof(T).
3344       QualType Val1Ty = E->getVal1()->getType();
3345       llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3346       CharUnits PointeeIncAmt =
3347           getContext().getTypeSizeInChars(MemTy->getPointeeType());
3348       Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3349       Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3350       EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3351       break;
3352     }
3353     // Fall through.
3354   case AtomicExpr::AO__atomic_fetch_add:
3355   case AtomicExpr::AO__atomic_fetch_sub:
3356   case AtomicExpr::AO__atomic_add_fetch:
3357   case AtomicExpr::AO__atomic_sub_fetch:
3358   case AtomicExpr::AO__c11_atomic_store:
3359   case AtomicExpr::AO__c11_atomic_exchange:
3360   case AtomicExpr::AO__atomic_store_n:
3361   case AtomicExpr::AO__atomic_exchange_n:
3362   case AtomicExpr::AO__c11_atomic_fetch_and:
3363   case AtomicExpr::AO__c11_atomic_fetch_or:
3364   case AtomicExpr::AO__c11_atomic_fetch_xor:
3365   case AtomicExpr::AO__atomic_fetch_and:
3366   case AtomicExpr::AO__atomic_fetch_or:
3367   case AtomicExpr::AO__atomic_fetch_xor:
3368   case AtomicExpr::AO__atomic_fetch_nand:
3369   case AtomicExpr::AO__atomic_and_fetch:
3370   case AtomicExpr::AO__atomic_or_fetch:
3371   case AtomicExpr::AO__atomic_xor_fetch:
3372   case AtomicExpr::AO__atomic_nand_fetch:
3373     Val1 = EmitValToTemp(*this, E->getVal1());
3374     break;
3375   }
3376 
3377   if (!E->getType()->isVoidType() && !Dest)
3378     Dest = CreateMemTemp(E->getType(), ".atomicdst");
3379 
3380   // Use a library call.  See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
3381   if (UseLibcall) {
3382 
3383     llvm::SmallVector<QualType, 5> Params;
3384     CallArgList Args;
3385     // Size is always the first parameter
3386     Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3387              getContext().getSizeType());
3388     // Atomic address is always the second parameter
3389     Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3390              getContext().VoidPtrTy);
3391 
3392     const char* LibCallName;
3393     QualType RetTy = getContext().VoidTy;
3394     switch (E->getOp()) {
3395     // There is only one libcall for compare an exchange, because there is no
3396     // optimisation benefit possible from a libcall version of a weak compare
3397     // and exchange.
3398     // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
3399     //                                void *desired, int success, int failure)
3400     case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3401     case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3402     case AtomicExpr::AO__atomic_compare_exchange:
3403     case AtomicExpr::AO__atomic_compare_exchange_n:
3404       LibCallName = "__atomic_compare_exchange";
3405       RetTy = getContext().BoolTy;
3406       Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3407                getContext().VoidPtrTy);
3408       Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3409                getContext().VoidPtrTy);
3410       Args.add(RValue::get(Order),
3411                getContext().IntTy);
3412       Order = OrderFail;
3413       break;
3414     // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3415     //                        int order)
3416     case AtomicExpr::AO__c11_atomic_exchange:
3417     case AtomicExpr::AO__atomic_exchange_n:
3418     case AtomicExpr::AO__atomic_exchange:
3419       LibCallName = "__atomic_exchange";
3420       Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3421                getContext().VoidPtrTy);
3422       Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3423                getContext().VoidPtrTy);
3424       break;
3425     // void __atomic_store(size_t size, void *mem, void *val, int order)
3426     case AtomicExpr::AO__c11_atomic_store:
3427     case AtomicExpr::AO__atomic_store:
3428     case AtomicExpr::AO__atomic_store_n:
3429       LibCallName = "__atomic_store";
3430       Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3431                getContext().VoidPtrTy);
3432       break;
3433     // void __atomic_load(size_t size, void *mem, void *return, int order)
3434     case AtomicExpr::AO__c11_atomic_load:
3435     case AtomicExpr::AO__atomic_load:
3436     case AtomicExpr::AO__atomic_load_n:
3437       LibCallName = "__atomic_load";
3438       Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3439                getContext().VoidPtrTy);
3440       break;
3441 #if 0
3442     // These are only defined for 1-16 byte integers.  It is not clear what
3443     // their semantics would be on anything else...
3444     case AtomicExpr::Add:   LibCallName = "__atomic_fetch_add_generic"; break;
3445     case AtomicExpr::Sub:   LibCallName = "__atomic_fetch_sub_generic"; break;
3446     case AtomicExpr::And:   LibCallName = "__atomic_fetch_and_generic"; break;
3447     case AtomicExpr::Or:    LibCallName = "__atomic_fetch_or_generic"; break;
3448     case AtomicExpr::Xor:   LibCallName = "__atomic_fetch_xor_generic"; break;
3449 #endif
3450     default: return EmitUnsupportedRValue(E, "atomic library call");
3451     }
3452     // order is always the last parameter
3453     Args.add(RValue::get(Order),
3454              getContext().IntTy);
3455 
3456     const CGFunctionInfo &FuncInfo =
3457         CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
3458             FunctionType::ExtInfo(), RequiredArgs::All);
3459     llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
3460     llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3461     RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3462     if (E->isCmpXChg())
3463       return Res;
3464     if (E->getType()->isVoidType())
3465       return RValue::get(0);
3466     return ConvertTempToRValue(*this, E->getType(), Dest);
3467   }
3468 
3469   llvm::Type *IPtrTy =
3470       llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3471   llvm::Value *OrigDest = Dest;
3472   Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3473   if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3474   if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3475   if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3476 
3477   if (isa<llvm::ConstantInt>(Order)) {
3478     int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3479     switch (ord) {
3480     case 0:  // memory_order_relaxed
3481       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3482                    llvm::Monotonic);
3483       break;
3484     case 1:  // memory_order_consume
3485     case 2:  // memory_order_acquire
3486       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3487                    llvm::Acquire);
3488       break;
3489     case 3:  // memory_order_release
3490       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3491                    llvm::Release);
3492       break;
3493     case 4:  // memory_order_acq_rel
3494       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3495                    llvm::AcquireRelease);
3496       break;
3497     case 5:  // memory_order_seq_cst
3498       EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3499                    llvm::SequentiallyConsistent);
3500       break;
3501     default: // invalid order
3502       // We should not ever get here normally, but it's hard to
3503       // enforce that in general.
3504       break;
3505     }
3506     if (E->getType()->isVoidType())
3507       return RValue::get(0);
3508     return ConvertTempToRValue(*this, E->getType(), OrigDest);
3509   }
3510 
3511   // Long case, when Order isn't obviously constant.
3512 
3513   bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3514                  E->getOp() == AtomicExpr::AO__atomic_store ||
3515                  E->getOp() == AtomicExpr::AO__atomic_store_n;
3516   bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3517                 E->getOp() == AtomicExpr::AO__atomic_load ||
3518                 E->getOp() == AtomicExpr::AO__atomic_load_n;
3519 
3520   // Create all the relevant BB's
3521   llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3522                    *AcqRelBB = 0, *SeqCstBB = 0;
3523   MonotonicBB = createBasicBlock("monotonic", CurFn);
3524   if (!IsStore)
3525     AcquireBB = createBasicBlock("acquire", CurFn);
3526   if (!IsLoad)
3527     ReleaseBB = createBasicBlock("release", CurFn);
3528   if (!IsLoad && !IsStore)
3529     AcqRelBB = createBasicBlock("acqrel", CurFn);
3530   SeqCstBB = createBasicBlock("seqcst", CurFn);
3531   llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3532 
3533   // Create the switch for the split
3534   // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3535   // doesn't matter unless someone is crazy enough to use something that
3536   // doesn't fold to a constant for the ordering.
3537   Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3538   llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3539 
3540   // Emit all the different atomics
3541   Builder.SetInsertPoint(MonotonicBB);
3542   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3543                llvm::Monotonic);
3544   Builder.CreateBr(ContBB);
3545   if (!IsStore) {
3546     Builder.SetInsertPoint(AcquireBB);
3547     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3548                  llvm::Acquire);
3549     Builder.CreateBr(ContBB);
3550     SI->addCase(Builder.getInt32(1), AcquireBB);
3551     SI->addCase(Builder.getInt32(2), AcquireBB);
3552   }
3553   if (!IsLoad) {
3554     Builder.SetInsertPoint(ReleaseBB);
3555     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3556                  llvm::Release);
3557     Builder.CreateBr(ContBB);
3558     SI->addCase(Builder.getInt32(3), ReleaseBB);
3559   }
3560   if (!IsLoad && !IsStore) {
3561     Builder.SetInsertPoint(AcqRelBB);
3562     EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3563                  llvm::AcquireRelease);
3564     Builder.CreateBr(ContBB);
3565     SI->addCase(Builder.getInt32(4), AcqRelBB);
3566   }
3567   Builder.SetInsertPoint(SeqCstBB);
3568   EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3569                llvm::SequentiallyConsistent);
3570   Builder.CreateBr(ContBB);
3571   SI->addCase(Builder.getInt32(5), SeqCstBB);
3572 
3573   // Cleanup and return
3574   Builder.SetInsertPoint(ContBB);
3575   if (E->getType()->isVoidType())
3576     return RValue::get(0);
3577   return ConvertTempToRValue(*this, E->getType(), OrigDest);
3578 }
3579 
3580 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
3581   assert(Val->getType()->isFPOrFPVectorTy());
3582   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
3583     return;
3584 
3585   llvm::MDBuilder MDHelper(getLLVMContext());
3586   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
3587 
3588   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
3589 }
3590 
3591 namespace {
3592   struct LValueOrRValue {
3593     LValue LV;
3594     RValue RV;
3595   };
3596 }
3597 
3598 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3599                                            const PseudoObjectExpr *E,
3600                                            bool forLValue,
3601                                            AggValueSlot slot) {
3602   llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3603 
3604   // Find the result expression, if any.
3605   const Expr *resultExpr = E->getResultExpr();
3606   LValueOrRValue result;
3607 
3608   for (PseudoObjectExpr::const_semantics_iterator
3609          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3610     const Expr *semantic = *i;
3611 
3612     // If this semantic expression is an opaque value, bind it
3613     // to the result of its source expression.
3614     if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3615 
3616       // If this is the result expression, we may need to evaluate
3617       // directly into the slot.
3618       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3619       OVMA opaqueData;
3620       if (ov == resultExpr && ov->isRValue() && !forLValue &&
3621           CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3622           !ov->getType()->isAnyComplexType()) {
3623         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3624 
3625         LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3626         opaqueData = OVMA::bind(CGF, ov, LV);
3627         result.RV = slot.asRValue();
3628 
3629       // Otherwise, emit as normal.
3630       } else {
3631         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3632 
3633         // If this is the result, also evaluate the result now.
3634         if (ov == resultExpr) {
3635           if (forLValue)
3636             result.LV = CGF.EmitLValue(ov);
3637           else
3638             result.RV = CGF.EmitAnyExpr(ov, slot);
3639         }
3640       }
3641 
3642       opaques.push_back(opaqueData);
3643 
3644     // Otherwise, if the expression is the result, evaluate it
3645     // and remember the result.
3646     } else if (semantic == resultExpr) {
3647       if (forLValue)
3648         result.LV = CGF.EmitLValue(semantic);
3649       else
3650         result.RV = CGF.EmitAnyExpr(semantic, slot);
3651 
3652     // Otherwise, evaluate the expression in an ignored context.
3653     } else {
3654       CGF.EmitIgnoredExpr(semantic);
3655     }
3656   }
3657 
3658   // Unbind all the opaques now.
3659   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3660     opaques[i].unbind(CGF);
3661 
3662   return result;
3663 }
3664 
3665 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3666                                                AggValueSlot slot) {
3667   return emitPseudoObjectExpr(*this, E, false, slot).RV;
3668 }
3669 
3670 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3671   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3672 }
3673