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