Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGExpr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This contains code to emit Expr nodes as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCUDARuntime.h"
14
#include "CGCXXABI.h"
15
#include "CGCall.h"
16
#include "CGCleanup.h"
17
#include "CGDebugInfo.h"
18
#include "CGObjCRuntime.h"
19
#include "CGOpenMPRuntime.h"
20
#include "CGRecordLayout.h"
21
#include "CodeGenFunction.h"
22
#include "CodeGenModule.h"
23
#include "ConstantEmitter.h"
24
#include "TargetInfo.h"
25
#include "clang/AST/ASTContext.h"
26
#include "clang/AST/Attr.h"
27
#include "clang/AST/DeclObjC.h"
28
#include "clang/AST/NSAPI.h"
29
#include "clang/Basic/Builtins.h"
30
#include "clang/Basic/CodeGenOptions.h"
31
#include "clang/Basic/SourceManager.h"
32
#include "llvm/ADT/Hashing.h"
33
#include "llvm/ADT/StringExtras.h"
34
#include "llvm/IR/DataLayout.h"
35
#include "llvm/IR/Intrinsics.h"
36
#include "llvm/IR/LLVMContext.h"
37
#include "llvm/IR/MDBuilder.h"
38
#include "llvm/IR/MatrixBuilder.h"
39
#include "llvm/Support/ConvertUTF.h"
40
#include "llvm/Support/MathExtras.h"
41
#include "llvm/Support/Path.h"
42
#include "llvm/Support/SaveAndRestore.h"
43
#include "llvm/Transforms/Utils/SanitizerStats.h"
44
45
#include <string>
46
47
using namespace clang;
48
using namespace CodeGen;
49
50
//===--------------------------------------------------------------------===//
51
//                        Miscellaneous Helper Methods
52
//===--------------------------------------------------------------------===//
53
54
2.03k
llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
55
2.03k
  unsigned addressSpace =
56
2.03k
      cast<llvm::PointerType>(value->getType())->getAddressSpace();
57
58
2.03k
  llvm::PointerType *destType = Int8PtrTy;
59
2.03k
  if (addressSpace)
60
15
    destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
61
62
2.03k
  if (value->getType() == destType) 
return value288
;
63
1.74k
  return Builder.CreateBitCast(value, destType);
64
2.03k
}
65
66
/// CreateTempAlloca - This creates a alloca and inserts it into the entry
67
/// block.
68
Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
69
                                                     CharUnits Align,
70
                                                     const Twine &Name,
71
1.05M
                                                     llvm::Value *ArraySize) {
72
1.05M
  auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
73
1.05M
  Alloca->setAlignment(Align.getAsAlign());
74
1.05M
  return Address(Alloca, Ty, Align);
75
1.05M
}
76
77
/// CreateTempAlloca - This creates a alloca and inserts it into the entry
78
/// block. The alloca is casted to default address space if necessary.
79
Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
80
                                          const Twine &Name,
81
                                          llvm::Value *ArraySize,
82
1.05M
                                          Address *AllocaAddr) {
83
1.05M
  auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
84
1.05M
  if (AllocaAddr)
85
786k
    *AllocaAddr = Alloca;
86
1.05M
  llvm::Value *V = Alloca.getPointer();
87
  // Alloca always returns a pointer in alloca address space, which may
88
  // be different from the type defined by the language. For example,
89
  // in C++ the auto variables are in the default address space. Therefore
90
  // cast alloca to the default address space when necessary.
91
1.05M
  if (getASTAllocaAddressSpace() != LangAS::Default) {
92
6.30k
    auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
93
6.30k
    llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
94
    // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
95
    // otherwise alloca is inserted at the current insertion point of the
96
    // builder.
97
6.30k
    if (!ArraySize)
98
6.29k
      Builder.SetInsertPoint(getPostAllocaInsertPoint());
99
6.30k
    V = getTargetHooks().performAddrSpaceCast(
100
6.30k
        *this, V, getASTAllocaAddressSpace(), LangAS::Default,
101
6.30k
        Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
102
6.30k
  }
103
104
1.05M
  return Address(V, Ty, Align);
105
1.05M
}
106
107
/// CreateTempAlloca - This creates an alloca and inserts it into the entry
108
/// block if \p ArraySize is nullptr, otherwise inserts it at the current
109
/// insertion point of the builder.
110
llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
111
                                                    const Twine &Name,
112
1.05M
                                                    llvm::Value *ArraySize) {
113
1.05M
  if (ArraySize)
114
2.18k
    return Builder.CreateAlloca(Ty, ArraySize, Name);
115
1.05M
  return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
116
1.05M
                              ArraySize, Name, AllocaInsertPt);
117
1.05M
}
118
119
/// CreateDefaultAlignTempAlloca - This creates an alloca with the
120
/// default alignment of the corresponding LLVM type, which is *not*
121
/// guaranteed to be related in any way to the expected alignment of
122
/// an AST type that might have been lowered to Ty.
123
Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
124
10.6k
                                                      const Twine &Name) {
125
10.6k
  CharUnits Align =
126
10.6k
      CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlignment(Ty));
127
10.6k
  return CreateTempAlloca(Ty, Align, Name);
128
10.6k
}
129
130
147k
Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
131
147k
  CharUnits Align = getContext().getTypeAlignInChars(Ty);
132
147k
  return CreateTempAlloca(ConvertType(Ty), Align, Name);
133
147k
}
134
135
Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
136
110k
                                       Address *Alloca) {
137
  // FIXME: Should we prefer the preferred type alignment here?
138
110k
  return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
139
110k
}
140
141
Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
142
632k
                                       const Twine &Name, Address *Alloca) {
143
632k
  Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
144
632k
                                    /*ArraySize=*/nullptr, Alloca);
145
146
632k
  if (Ty->isConstantMatrixType()) {
147
306
    auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
148
306
    auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
149
306
                                                ArrayTy->getNumElements());
150
151
306
    Result = Address(
152
306
        Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
153
306
        VectorTy, Result.getAlignment());
154
306
  }
155
632k
  return Result;
156
632k
}
157
158
Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
159
299
                                                  const Twine &Name) {
160
299
  return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
161
299
}
162
163
Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
164
0
                                                  const Twine &Name) {
165
0
  return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
166
0
                                  Name);
167
0
}
168
169
/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
170
/// expression and compare the result against zero, returning an Int1Ty value.
171
179k
llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
172
179k
  PGO.setCurrentStmt(E);
173
179k
  if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
174
0
    llvm::Value *MemPtr = EmitScalarExpr(E);
175
0
    return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
176
0
  }
177
178
179k
  QualType BoolTy = getContext().BoolTy;
179
179k
  SourceLocation Loc = E->getExprLoc();
180
179k
  CGFPOptionsRAII FPOptsRAII(*this, E);
181
179k
  if (!E->getType()->isAnyComplexType())
182
179k
    return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
183
184
1
  return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
185
1
                                       Loc);
186
179k
}
187
188
/// EmitIgnoredExpr - Emit code to compute the specified expression,
189
/// ignoring the result.
190
380k
void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
191
380k
  if (E->isPRValue())
192
195k
    return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
193
194
  // if this is a bitfield-resulting conditional operator, we can special case
195
  // emit this. The normal 'EmitLValue' version of this is particularly
196
  // difficult to codegen for, since creating a single "LValue" for two
197
  // different sized arguments here is not particularly doable.
198
185k
  if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
199
185k
          E->IgnoreParenNoopCasts(getContext()))) {
200
10
    if (CondOp->getObjectKind() == OK_BitField)
201
4
      return EmitIgnoredConditionalOperator(CondOp);
202
10
  }
203
204
  // Just emit it as an l-value and drop the result.
205
185k
  EmitLValue(E);
206
185k
}
207
208
/// EmitAnyExpr - Emit code to compute the specified expression which
209
/// can have any type.  The result is returned as an RValue struct.
210
/// If this is an aggregate expression, AggSlot indicates where the
211
/// result should be returned.
212
RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
213
                                    AggValueSlot aggSlot,
214
688k
                                    bool ignoreResult) {
215
688k
  switch (getEvaluationKind(E->getType())) {
216
676k
  case TEK_Scalar:
217
676k
    return RValue::get(EmitScalarExpr(E, ignoreResult));
218
893
  case TEK_Complex:
219
893
    return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
220
11.3k
  case TEK_Aggregate:
221
11.3k
    if (!ignoreResult && 
aggSlot.isIgnored()9.87k
)
222
0
      aggSlot = CreateAggTemp(E->getType(), "agg-temp");
223
11.3k
    EmitAggExpr(E, aggSlot);
224
11.3k
    return aggSlot.asRValue();
225
688k
  }
226
0
  llvm_unreachable("bad evaluation kind");
227
0
}
228
229
/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
230
/// always be accessible even if no aggregate location is provided.
231
344k
RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
232
344k
  AggValueSlot AggSlot = AggValueSlot::ignored();
233
234
344k
  if (hasAggregateEvaluationKind(E->getType()))
235
9.82k
    AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
236
344k
  return EmitAnyExpr(E, AggSlot);
237
344k
}
238
239
/// EmitAnyExprToMem - Evaluate an expression into a given memory
240
/// location.
241
void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
242
                                       Address Location,
243
                                       Qualifiers Quals,
244
23.0k
                                       bool IsInit) {
245
  // FIXME: This function should take an LValue as an argument.
246
23.0k
  switch (getEvaluationKind(E->getType())) {
247
12
  case TEK_Complex:
248
12
    EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
249
12
                              /*isInit*/ false);
250
12
    return;
251
252
12.0k
  case TEK_Aggregate: {
253
12.0k
    EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
254
12.0k
                                         AggValueSlot::IsDestructed_t(IsInit),
255
12.0k
                                         AggValueSlot::DoesNotNeedGCBarriers,
256
12.0k
                                         AggValueSlot::IsAliased_t(!IsInit),
257
12.0k
                                         AggValueSlot::MayOverlap));
258
12.0k
    return;
259
0
  }
260
261
10.9k
  case TEK_Scalar: {
262
10.9k
    RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
263
10.9k
    LValue LV = MakeAddrLValue(Location, E->getType());
264
10.9k
    EmitStoreThroughLValue(RV, LV);
265
10.9k
    return;
266
0
  }
267
23.0k
  }
268
0
  llvm_unreachable("bad evaluation kind");
269
0
}
270
271
static void
272
pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
273
15.7k
                     const Expr *E, Address ReferenceTemporary) {
274
  // Objective-C++ ARC:
275
  //   If we are binding a reference to a temporary that has ownership, we
276
  //   need to perform retain/release operations on the temporary.
277
  //
278
  // FIXME: This should be looking at E, not M.
279
15.7k
  if (auto Lifetime = M->getType().getObjCLifetime()) {
280
15
    switch (Lifetime) {
281
0
    case Qualifiers::OCL_None:
282
0
    case Qualifiers::OCL_ExplicitNone:
283
      // Carry on to normal cleanup handling.
284
0
      break;
285
286
6
    case Qualifiers::OCL_Autoreleasing:
287
      // Nothing to do; cleaned up by an autorelease pool.
288
6
      return;
289
290
8
    case Qualifiers::OCL_Strong:
291
9
    case Qualifiers::OCL_Weak:
292
9
      switch (StorageDuration Duration = M->getStorageDuration()) {
293
2
      case SD_Static:
294
        // Note: we intentionally do not register a cleanup to release
295
        // the object on program termination.
296
2
        return;
297
298
0
      case SD_Thread:
299
        // FIXME: We should probably register a cleanup in this case.
300
0
        return;
301
302
4
      case SD_Automatic:
303
7
      case SD_FullExpression:
304
7
        CodeGenFunction::Destroyer *Destroy;
305
7
        CleanupKind CleanupKind;
306
7
        if (Lifetime == Qualifiers::OCL_Strong) {
307
6
          const ValueDecl *VD = M->getExtendingDecl();
308
6
          bool Precise =
309
6
              VD && 
isa<VarDecl>(VD)3
&&
VD->hasAttr<ObjCPreciseLifetimeAttr>()3
;
310
6
          CleanupKind = CGF.getARCCleanupKind();
311
6
          Destroy = Precise ? 
&CodeGenFunction::destroyARCStrongPrecise0
312
6
                            : &CodeGenFunction::destroyARCStrongImprecise;
313
6
        } else {
314
          // __weak objects always get EH cleanups; otherwise, exceptions
315
          // could cause really nasty crashes instead of mere leaks.
316
1
          CleanupKind = NormalAndEHCleanup;
317
1
          Destroy = &CodeGenFunction::destroyARCWeak;
318
1
        }
319
7
        if (Duration == SD_FullExpression)
320
3
          CGF.pushDestroy(CleanupKind, ReferenceTemporary,
321
3
                          M->getType(), *Destroy,
322
3
                          CleanupKind & EHCleanup);
323
4
        else
324
4
          CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
325
4
                                          M->getType(),
326
4
                                          *Destroy, CleanupKind & EHCleanup);
327
7
        return;
328
329
0
      case SD_Dynamic:
330
0
        llvm_unreachable("temporary cannot have dynamic storage duration");
331
9
      }
332
15
      
llvm_unreachable0
("unknown storage duration");
333
15
    }
334
15
  }
335
336
15.7k
  CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
337
15.7k
  if (const RecordType *RT =
338
15.7k
          E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
339
    // Get the destructor for the reference temporary.
340
10.7k
    auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
341
10.7k
    if (!ClassDecl->hasTrivialDestructor())
342
2.37k
      ReferenceTemporaryDtor = ClassDecl->getDestructor();
343
10.7k
  }
344
345
15.7k
  if (!ReferenceTemporaryDtor)
346
13.4k
    return;
347
348
  // Call the destructor for the temporary.
349
2.37k
  switch (M->getStorageDuration()) {
350
56
  case SD_Static:
351
65
  case SD_Thread: {
352
65
    llvm::FunctionCallee CleanupFn;
353
65
    llvm::Constant *CleanupArg;
354
65
    if (E->getType()->isArrayType()) {
355
4
      CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
356
4
          ReferenceTemporary, E->getType(),
357
4
          CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
358
4
          dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
359
4
      CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
360
61
    } else {
361
61
      CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
362
61
          GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
363
61
      CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
364
61
    }
365
65
    CGF.CGM.getCXXABI().registerGlobalDtor(
366
65
        CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
367
65
    break;
368
56
  }
369
370
2.19k
  case SD_FullExpression:
371
2.19k
    CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
372
2.19k
                    CodeGenFunction::destroyCXXObject,
373
2.19k
                    CGF.getLangOpts().Exceptions);
374
2.19k
    break;
375
376
114
  case SD_Automatic:
377
114
    CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
378
114
                                    ReferenceTemporary, E->getType(),
379
114
                                    CodeGenFunction::destroyCXXObject,
380
114
                                    CGF.getLangOpts().Exceptions);
381
114
    break;
382
383
0
  case SD_Dynamic:
384
0
    llvm_unreachable("temporary cannot have dynamic storage duration");
385
2.37k
  }
386
2.37k
}
387
388
static Address createReferenceTemporary(CodeGenFunction &CGF,
389
                                        const MaterializeTemporaryExpr *M,
390
                                        const Expr *Inner,
391
15.7k
                                        Address *Alloca = nullptr) {
392
15.7k
  auto &TCG = CGF.getTargetHooks();
393
15.7k
  switch (M->getStorageDuration()) {
394
15.4k
  case SD_FullExpression:
395
15.6k
  case SD_Automatic: {
396
    // If we have a constant temporary array or record try to promote it into a
397
    // constant global under the same rules a normal constant would've been
398
    // promoted. This is easier on the optimizer and generally emits fewer
399
    // instructions.
400
15.6k
    QualType Ty = Inner->getType();
401
15.6k
    if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
402
15.6k
        
(786
Ty->isArrayType()786
||
Ty->isRecordType()736
) &&
403
15.6k
        
CGF.CGM.isTypeConstant(Ty, true)418
)
404
26
      if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
405
10
        auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
406
10
        auto *GV = new llvm::GlobalVariable(
407
10
            CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
408
10
            llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
409
10
            llvm::GlobalValue::NotThreadLocal,
410
10
            CGF.getContext().getTargetAddressSpace(AS));
411
10
        CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
412
10
        GV->setAlignment(alignment.getAsAlign());
413
10
        llvm::Constant *C = GV;
414
10
        if (AS != LangAS::Default)
415
3
          C = TCG.performAddrSpaceCast(
416
3
              CGF.CGM, GV, AS, LangAS::Default,
417
3
              GV->getValueType()->getPointerTo(
418
3
                  CGF.getContext().getTargetAddressSpace(LangAS::Default)));
419
        // FIXME: Should we put the new global into a COMDAT?
420
10
        return Address(C, GV->getValueType(), alignment);
421
10
      }
422
15.6k
    return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
423
15.6k
  }
424
10
  case SD_Thread:
425
108
  case SD_Static:
426
108
    return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
427
428
0
  case SD_Dynamic:
429
0
    llvm_unreachable("temporary can't have dynamic storage duration");
430
15.7k
  }
431
0
  llvm_unreachable("unknown storage duration");
432
0
}
433
434
/// Helper method to check if the underlying ABI is AAPCS
435
7.34k
static bool isAAPCS(const TargetInfo &TargetInfo) {
436
7.34k
  return TargetInfo.getABI().startswith("aapcs");
437
7.34k
}
438
439
LValue CodeGenFunction::
440
15.8k
EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
441
15.8k
  const Expr *E = M->getSubExpr();
442
443
15.8k
  assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
444
15.8k
          !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
445
15.8k
         "Reference should never be pseudo-strong!");
446
447
  // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
448
  // as that will cause the lifetime adjustment to be lost for ARC
449
0
  auto ownership = M->getType().getObjCLifetime();
450
15.8k
  if (ownership != Qualifiers::OCL_None &&
451
15.8k
      
ownership != Qualifiers::OCL_ExplicitNone16
) {
452
16
    Address Object = createReferenceTemporary(*this, M, E);
453
16
    if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
454
3
      llvm::Type *Ty = ConvertTypeForMem(E->getType());
455
3
      Object = Address(llvm::ConstantExpr::getBitCast(
456
3
                           Var, Ty->getPointerTo(Object.getAddressSpace())),
457
3
                       Ty, Object.getAlignment());
458
459
      // createReferenceTemporary will promote the temporary to a global with a
460
      // constant initializer if it can.  It can only do this to a value of
461
      // ARC-manageable type if the value is global and therefore "immune" to
462
      // ref-counting operations.  Therefore we have no need to emit either a
463
      // dynamic initialization or a cleanup and we can just return the address
464
      // of the temporary.
465
3
      if (Var->hasInitializer())
466
1
        return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
467
468
2
      Var->setInitializer(CGM.EmitNullConstant(E->getType()));
469
2
    }
470
15
    LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
471
15
                                       AlignmentSource::Decl);
472
473
15
    switch (getEvaluationKind(E->getType())) {
474
0
    default: llvm_unreachable("expected scalar or aggregate expression");
475
11
    case TEK_Scalar:
476
11
      EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
477
11
      break;
478
4
    case TEK_Aggregate: {
479
4
      EmitAggExpr(E, AggValueSlot::forAddr(Object,
480
4
                                           E->getType().getQualifiers(),
481
4
                                           AggValueSlot::IsDestructed,
482
4
                                           AggValueSlot::DoesNotNeedGCBarriers,
483
4
                                           AggValueSlot::IsNotAliased,
484
4
                                           AggValueSlot::DoesNotOverlap));
485
4
      break;
486
0
    }
487
15
    }
488
489
15
    pushTemporaryCleanup(*this, M, E, Object);
490
15
    return RefTempDst;
491
15
  }
492
493
15.7k
  SmallVector<const Expr *, 2> CommaLHSs;
494
15.7k
  SmallVector<SubobjectAdjustment, 2> Adjustments;
495
15.7k
  E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
496
497
15.7k
  for (const auto &Ignored : CommaLHSs)
498
0
    EmitIgnoredExpr(Ignored);
499
500
15.7k
  if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
501
3
    if (opaque->getType()->isRecordType()) {
502
3
      assert(Adjustments.empty());
503
0
      return EmitOpaqueValueLValue(opaque);
504
3
    }
505
3
  }
506
507
  // Create and initialize the reference temporary.
508
15.7k
  Address Alloca = Address::invalid();
509
15.7k
  Address Object = createReferenceTemporary(*this, M, E, &Alloca);
510
15.7k
  if (auto *Var = dyn_cast<llvm::GlobalVariable>(
511
15.7k
          Object.getPointer()->stripPointerCasts())) {
512
115
    llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
513
115
    Object = Address(llvm::ConstantExpr::getBitCast(
514
115
                         cast<llvm::Constant>(Object.getPointer()),
515
115
                         TemporaryType->getPointerTo()),
516
115
                     TemporaryType,
517
115
                     Object.getAlignment());
518
    // If the temporary is a global and has a constant initializer or is a
519
    // constant temporary that we promoted to a global, we may have already
520
    // initialized it.
521
115
    if (!Var->hasInitializer()) {
522
98
      Var->setInitializer(CGM.EmitNullConstant(E->getType()));
523
98
      EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
524
98
    }
525
15.6k
  } else {
526
15.6k
    switch (M->getStorageDuration()) {
527
228
    case SD_Automatic:
528
228
      if (auto *Size = EmitLifetimeStart(
529
228
              CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
530
228
              Alloca.getPointer())) {
531
17
        pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
532
17
                                                  Alloca, Size);
533
17
      }
534
228
      break;
535
536
15.4k
    case SD_FullExpression: {
537
15.4k
      if (!ShouldEmitLifetimeMarkers)
538
14.6k
        break;
539
540
      // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
541
      // marker. Instead, start the lifetime of a conditional temporary earlier
542
      // so that it's unconditional. Don't do this with sanitizers which need
543
      // more precise lifetime marks.
544
782
      ConditionalEvaluation *OldConditional = nullptr;
545
782
      CGBuilderTy::InsertPoint OldIP;
546
782
      if (isInConditionalBranch() && 
!E->getType().isDestructedType()56
&&
547
782
          
!SanOpts.has(SanitizerKind::HWAddress)12
&&
548
782
          
!SanOpts.has(SanitizerKind::Memory)11
&&
549
782
          
!CGM.getCodeGenOpts().SanitizeAddressUseAfterScope10
) {
550
9
        OldConditional = OutermostConditional;
551
9
        OutermostConditional = nullptr;
552
553
9
        OldIP = Builder.saveIP();
554
9
        llvm::BasicBlock *Block = OldConditional->getStartingBlock();
555
9
        Builder.restoreIP(CGBuilderTy::InsertPoint(
556
9
            Block, llvm::BasicBlock::iterator(Block->back())));
557
9
      }
558
559
782
      if (auto *Size = EmitLifetimeStart(
560
782
              CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
561
782
              Alloca.getPointer())) {
562
782
        pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
563
782
                                             Size);
564
782
      }
565
566
782
      if (OldConditional) {
567
9
        OutermostConditional = OldConditional;
568
9
        Builder.restoreIP(OldIP);
569
9
      }
570
782
      break;
571
15.4k
    }
572
573
0
    default:
574
0
      break;
575
15.6k
    }
576
15.6k
    EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
577
15.6k
  }
578
15.7k
  pushTemporaryCleanup(*this, M, E, Object);
579
580
  // Perform derived-to-base casts and/or field accesses, to get from the
581
  // temporary object we created (and, potentially, for which we extended
582
  // the lifetime) to the subobject we're binding the reference to.
583
15.7k
  for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
584
1
    switch (Adjustment.Kind) {
585
0
    case SubobjectAdjustment::DerivedToBaseAdjustment:
586
0
      Object =
587
0
          GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
588
0
                                Adjustment.DerivedToBase.BasePath->path_begin(),
589
0
                                Adjustment.DerivedToBase.BasePath->path_end(),
590
0
                                /*NullCheckValue=*/ false, E->getExprLoc());
591
0
      break;
592
593
1
    case SubobjectAdjustment::FieldAdjustment: {
594
1
      LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
595
1
      LV = EmitLValueForField(LV, Adjustment.Field);
596
1
      assert(LV.isSimple() &&
597
1
             "materialized temporary field is not a simple lvalue");
598
0
      Object = LV.getAddress(*this);
599
1
      break;
600
0
    }
601
602
0
    case SubobjectAdjustment::MemberPointerAdjustment: {
603
0
      llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
604
0
      Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
605
0
                                               Adjustment.Ptr.MPT);
606
0
      break;
607
0
    }
608
1
    }
609
1
  }
610
611
15.7k
  return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
612
15.7k
}
613
614
RValue
615
77.3k
CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
616
  // Emit the expression as an lvalue.
617
77.3k
  LValue LV = EmitLValue(E);
618
77.3k
  assert(LV.isSimple());
619
0
  llvm::Value *Value = LV.getPointer(*this);
620
621
77.3k
  if (sanitizePerformTypeCheck() && 
!E->getType()->isFunctionType()55
) {
622
    // C++11 [dcl.ref]p5 (as amended by core issue 453):
623
    //   If a glvalue to which a reference is directly bound designates neither
624
    //   an existing object or function of an appropriate type nor a region of
625
    //   storage of suitable size and alignment to contain an object of the
626
    //   reference's type, the behavior is undefined.
627
55
    QualType Ty = E->getType();
628
55
    EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
629
55
  }
630
631
77.3k
  return RValue::get(Value);
632
77.3k
}
633
634
635
/// getAccessedFieldNo - Given an encoded value and a result number, return the
636
/// input field number being accessed.
637
unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
638
397
                                             const llvm::Constant *Elts) {
639
397
  return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
640
397
      ->getZExtValue();
641
397
}
642
643
/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
644
static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
645
49
                                    llvm::Value *High) {
646
49
  llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
647
49
  llvm::Value *K47 = Builder.getInt64(47);
648
49
  llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
649
49
  llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
650
49
  llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
651
49
  llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
652
49
  return Builder.CreateMul(B1, KMul);
653
49
}
654
655
720
bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
656
720
  return TCK == TCK_DowncastPointer || 
TCK == TCK_Upcast710
||
657
720
         
TCK == TCK_UpcastToVirtualBase691
||
TCK == TCK_DynamicOperation688
;
658
720
}
659
660
423
bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
661
423
  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
662
423
  return (RD && 
RD->hasDefinition()210
&&
RD->isDynamicClass()210
) &&
663
423
         
(80
TCK == TCK_MemberAccess80
||
TCK == TCK_MemberCall77
||
664
80
          
TCK == TCK_DowncastPointer46
||
TCK == TCK_DowncastReference39
||
665
80
          
TCK == TCK_UpcastToVirtualBase35
||
TCK == TCK_DynamicOperation32
);
666
423
}
667
668
695k
bool CodeGenFunction::sanitizePerformTypeCheck() const {
669
695k
  return SanOpts.has(SanitizerKind::Null) ||
670
695k
         
SanOpts.has(SanitizerKind::Alignment)695k
||
671
695k
         
SanOpts.has(SanitizerKind::ObjectSize)695k
||
672
695k
         
SanOpts.has(SanitizerKind::Vptr)695k
;
673
695k
}
674
675
void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
676
                                    llvm::Value *Ptr, QualType Ty,
677
                                    CharUnits Alignment,
678
                                    SanitizerSet SkippedChecks,
679
598k
                                    llvm::Value *ArraySize) {
680
598k
  if (!sanitizePerformTypeCheck())
681
598k
    return;
682
683
  // Don't check pointers outside the default address space. The null check
684
  // isn't correct, the object-size check isn't supported by LLVM, and we can't
685
  // communicate the addresses to the runtime handler for the vptr check.
686
723
  if (Ptr->getType()->getPointerAddressSpace())
687
2
    return;
688
689
  // Don't check pointers to volatile data. The behavior here is implementation-
690
  // defined.
691
721
  if (Ty.isVolatileQualified())
692
1
    return;
693
694
720
  SanitizerScope SanScope(this);
695
696
720
  SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
697
720
  llvm::BasicBlock *Done = nullptr;
698
699
  // Quickly determine whether we have a pointer to an alloca. It's possible
700
  // to skip null checks, and some alignment checks, for these pointers. This
701
  // can reduce compile-time significantly.
702
720
  auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
703
704
720
  llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
705
720
  llvm::Value *IsNonNull = nullptr;
706
720
  bool IsGuaranteedNonNull =
707
720
      SkippedChecks.has(SanitizerKind::Null) || 
PtrToAlloca574
;
708
720
  bool AllowNullPointers = isNullPointerAllowed(TCK);
709
720
  if ((SanOpts.has(SanitizerKind::Null) || 
AllowNullPointers379
) &&
710
720
      
!IsGuaranteedNonNull356
) {
711
    // The glvalue must not be an empty glvalue.
712
233
    IsNonNull = Builder.CreateIsNotNull(Ptr);
713
714
    // The IR builder can constant-fold the null check if the pointer points to
715
    // a constant.
716
233
    IsGuaranteedNonNull = IsNonNull == True;
717
718
    // Skip the null check if the pointer is known to be non-null.
719
233
    if (!IsGuaranteedNonNull) {
720
227
      if (AllowNullPointers) {
721
        // When performing pointer casts, it's OK if the value is null.
722
        // Skip the remaining checks in that case.
723
17
        Done = createBasicBlock("null");
724
17
        llvm::BasicBlock *Rest = createBasicBlock("not.null");
725
17
        Builder.CreateCondBr(IsNonNull, Rest, Done);
726
17
        EmitBlock(Rest);
727
210
      } else {
728
210
        Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
729
210
      }
730
227
    }
731
233
  }
732
733
720
  if (SanOpts.has(SanitizerKind::ObjectSize) &&
734
720
      
!SkippedChecks.has(SanitizerKind::ObjectSize)142
&&
735
720
      
!Ty->isIncompleteType()105
) {
736
105
    uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
737
105
    llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
738
105
    if (ArraySize)
739
5
      Size = Builder.CreateMul(Size, ArraySize);
740
741
    // Degenerate case: new X[0] does not need an objectsize check.
742
105
    llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
743
105
    if (!ConstantSize || 
!ConstantSize->isNullValue()104
) {
744
      // The glvalue must refer to a large enough storage region.
745
      // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
746
      //        to check this.
747
      // FIXME: Get object address space
748
103
      llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
749
103
      llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
750
103
      llvm::Value *Min = Builder.getFalse();
751
103
      llvm::Value *NullIsUnknown = Builder.getFalse();
752
103
      llvm::Value *Dynamic = Builder.getFalse();
753
103
      llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
754
103
      llvm::Value *LargeEnough = Builder.CreateICmpUGE(
755
103
          Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
756
103
      Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
757
103
    }
758
105
  }
759
760
720
  llvm::MaybeAlign AlignVal;
761
720
  llvm::Value *PtrAsInt = nullptr;
762
763
720
  if (SanOpts.has(SanitizerKind::Alignment) &&
764
720
      
!SkippedChecks.has(SanitizerKind::Alignment)309
) {
765
271
    AlignVal = Alignment.getAsMaybeAlign();
766
271
    if (!Ty->isIncompleteType() && !AlignVal)
767
104
      AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
768
104
                                             /*ForPointeeType=*/true)
769
104
                     .getAsMaybeAlign();
770
771
    // The glvalue must be suitably aligned.
772
271
    if (AlignVal && *AlignVal > llvm::Align(1) &&
773
271
        
(188
!PtrToAlloca188
||
PtrToAlloca->getAlign() < *AlignVal23
)) {
774
165
      PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
775
165
      llvm::Value *Align = Builder.CreateAnd(
776
165
          PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
777
165
      llvm::Value *Aligned =
778
165
          Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
779
165
      if (Aligned != True)
780
162
        Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
781
165
    }
782
271
  }
783
784
720
  if (Checks.size() > 0) {
785
344
    llvm::Constant *StaticData[] = {
786
344
        EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
787
344
        llvm::ConstantInt::get(Int8Ty, AlignVal ? 
llvm::Log2(*AlignVal)239
:
1105
),
788
344
        llvm::ConstantInt::get(Int8Ty, TCK)};
789
344
    EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
790
344
              PtrAsInt ? 
PtrAsInt162
:
Ptr182
);
791
344
  }
792
793
  // If possible, check that the vptr indicates that there is a subobject of
794
  // type Ty at offset zero within this object.
795
  //
796
  // C++11 [basic.life]p5,6:
797
  //   [For storage which does not refer to an object within its lifetime]
798
  //   The program has undefined behavior if:
799
  //    -- the [pointer or glvalue] is used to access a non-static data member
800
  //       or call a non-static member function
801
720
  if (SanOpts.has(SanitizerKind::Vptr) &&
802
720
      
!SkippedChecks.has(SanitizerKind::Vptr)423
&&
isVptrCheckRequired(TCK, Ty)423
) {
803
    // Ensure that the pointer is non-null before loading it. If there is no
804
    // compile-time guarantee, reuse the run-time null check or emit a new one.
805
50
    if (!IsGuaranteedNonNull) {
806
22
      if (!IsNonNull)
807
7
        IsNonNull = Builder.CreateIsNotNull(Ptr);
808
22
      if (!Done)
809
17
        Done = createBasicBlock("vptr.null");
810
22
      llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
811
22
      Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
812
22
      EmitBlock(VptrNotNull);
813
22
    }
814
815
    // Compute a hash of the mangled name of the type.
816
    //
817
    // FIXME: This is not guaranteed to be deterministic! Move to a
818
    //        fingerprinting mechanism once LLVM provides one. For the time
819
    //        being the implementation happens to be deterministic.
820
50
    SmallString<64> MangledName;
821
50
    llvm::raw_svector_ostream Out(MangledName);
822
50
    CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
823
50
                                                     Out);
824
825
    // Contained in NoSanitizeList based on the mangled type.
826
50
    if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
827
50
                                                           Out.str())) {
828
49
      llvm::hash_code TypeHash = hash_value(Out.str());
829
830
      // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
831
49
      llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
832
49
      llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
833
49
      Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), IntPtrTy,
834
49
                       getPointerAlign());
835
49
      llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
836
49
      llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
837
838
49
      llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
839
49
      Hash = Builder.CreateTrunc(Hash, IntPtrTy);
840
841
      // Look the hash up in our cache.
842
49
      const int CacheSize = 128;
843
49
      llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
844
49
      llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
845
49
                                                     "__ubsan_vptr_type_cache");
846
49
      llvm::Value *Slot = Builder.CreateAnd(Hash,
847
49
                                            llvm::ConstantInt::get(IntPtrTy,
848
49
                                                                   CacheSize-1));
849
49
      llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
850
49
      llvm::Value *CacheVal = Builder.CreateAlignedLoad(
851
49
          IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
852
49
          getPointerAlign());
853
854
      // If the hash isn't in the cache, call a runtime handler to perform the
855
      // hard work of checking whether the vptr is for an object of the right
856
      // type. This will either fill in the cache and return, or produce a
857
      // diagnostic.
858
49
      llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
859
49
      llvm::Constant *StaticData[] = {
860
49
        EmitCheckSourceLocation(Loc),
861
49
        EmitCheckTypeDescriptor(Ty),
862
49
        CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
863
49
        llvm::ConstantInt::get(Int8Ty, TCK)
864
49
      };
865
49
      llvm::Value *DynamicData[] = { Ptr, Hash };
866
49
      EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
867
49
                SanitizerHandler::DynamicTypeCacheMiss, StaticData,
868
49
                DynamicData);
869
49
    }
870
50
  }
871
872
720
  if (Done) {
873
34
    Builder.CreateBr(Done);
874
34
    EmitBlock(Done);
875
34
  }
876
720
}
877
878
/// Determine whether this expression refers to a flexible array member in a
879
/// struct. We disable array bounds checks for such members.
880
49
static bool isFlexibleArrayMemberExpr(const Expr *E) {
881
  // For compatibility with existing code, we treat arrays of length 0 or
882
  // 1 as flexible array members.
883
  // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
884
  // the two mechanisms.
885
49
  const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
886
49
  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
887
    // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
888
    // was produced by macro expansion.
889
47
    if (CAT->getSize().ugt(1))
890
27
      return false;
891
47
  } else 
if (2
!isa<IncompleteArrayType>(AT)2
)
892
1
    return false;
893
894
21
  E = E->IgnoreParens();
895
896
  // A flexible array member must be the last member in the class.
897
21
  if (const auto *ME = dyn_cast<MemberExpr>(E)) {
898
    // FIXME: If the base type of the member expr is not FD->getParent(),
899
    // this should not be treated as a flexible array member access.
900
15
    if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
901
      // FIXME: Sema doesn't treat a T[1] union member as a flexible array
902
      // member, only a T[0] or T[] member gets that treatment.
903
15
      if (FD->getParent()->isUnion())
904
2
        return true;
905
13
      RecordDecl::field_iterator FI(
906
13
          DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
907
13
      return ++FI == FD->getParent()->field_end();
908
15
    }
909
15
  } else 
if (const auto *6
IRE6
= dyn_cast<ObjCIvarRefExpr>(E)) {
910
4
    return IRE->getDecl()->getNextIvar() == nullptr;
911
4
  }
912
913
2
  return false;
914
21
}
915
916
llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
917
26
                                                   QualType EltTy) {
918
26
  ASTContext &C = getContext();
919
26
  uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
920
26
  if (!EltSize)
921
1
    return nullptr;
922
923
25
  auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
924
25
  if (!ArrayDeclRef)
925
17
    return nullptr;
926
927
8
  auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
928
8
  if (!ParamDecl)
929
2
    return nullptr;
930
931
6
  auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
932
6
  if (!POSAttr)
933
2
    return nullptr;
934
935
  // Don't load the size if it's a lower bound.
936
4
  int POSType = POSAttr->getType();
937
4
  if (POSType != 0 && 
POSType != 13
)
938
2
    return nullptr;
939
940
  // Find the implicit size parameter.
941
2
  auto PassedSizeIt = SizeArguments.find(ParamDecl);
942
2
  if (PassedSizeIt == SizeArguments.end())
943
0
    return nullptr;
944
945
2
  const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
946
2
  assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
947
0
  Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
948
2
  llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
949
2
                                              C.getSizeType(), E->getExprLoc());
950
2
  llvm::Value *SizeOfElement =
951
2
      llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
952
2
  return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
953
2
}
954
955
/// If Base is known to point to the start of an array, return the length of
956
/// that array. Return 0 if the length cannot be determined.
957
static llvm::Value *getArrayIndexingBound(
958
58
    CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
959
  // For the vector indexing extension, the bound is the number of elements.
960
58
  if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
961
1
    IndexedType = Base->getType();
962
1
    return CGF.Builder.getInt32(VT->getNumElements());
963
1
  }
964
965
57
  Base = Base->IgnoreParens();
966
967
57
  if (const auto *CE = dyn_cast<CastExpr>(Base)) {
968
57
    if (CE->getCastKind() == CK_ArrayToPointerDecay &&
969
57
        
!isFlexibleArrayMemberExpr(CE->getSubExpr())49
) {
970
32
      IndexedType = CE->getSubExpr()->getType();
971
32
      const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
972
32
      if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
973
30
        return CGF.Builder.getInt(CAT->getSize());
974
2
      else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
975
1
        return CGF.getVLASize(VAT).NumElts;
976
      // Ignore pass_object_size here. It's not applicable on decayed pointers.
977
32
    }
978
57
  }
979
980
26
  QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
981
26
  if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
982
2
    IndexedType = Base->getType();
983
2
    return POS;
984
2
  }
985
986
24
  return nullptr;
987
26
}
988
989
void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
990
                                      llvm::Value *Index, QualType IndexType,
991
58
                                      bool Accessed) {
992
58
  assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
993
58
         "should not be called unless adding bounds checks");
994
0
  SanitizerScope SanScope(this);
995
996
58
  QualType IndexedType;
997
58
  llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
998
58
  if (!Bound)
999
24
    return;
1000
1001
34
  bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1002
34
  llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
1003
34
  llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
1004
1005
34
  llvm::Constant *StaticData[] = {
1006
34
    EmitCheckSourceLocation(E->getExprLoc()),
1007
34
    EmitCheckTypeDescriptor(IndexedType),
1008
34
    EmitCheckTypeDescriptor(IndexType)
1009
34
  };
1010
34
  llvm::Value *Check = Accessed ? 
Builder.CreateICmpULT(IndexVal, BoundVal)31
1011
34
                                : 
Builder.CreateICmpULE(IndexVal, BoundVal)3
;
1012
34
  EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
1013
34
            SanitizerHandler::OutOfBounds, StaticData, Index);
1014
34
}
1015
1016
1017
CodeGenFunction::ComplexPairTy CodeGenFunction::
1018
EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1019
8
                         bool isInc, bool isPre) {
1020
8
  ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1021
1022
8
  llvm::Value *NextVal;
1023
8
  if (isa<llvm::IntegerType>(InVal.first->getType())) {
1024
4
    uint64_t AmountVal = isInc ? 
12
:
-12
;
1025
4
    NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1026
1027
    // Add the inc/dec to the real part.
1028
4
    NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? 
"inc"2
:
"dec"2
);
1029
4
  } else {
1030
4
    QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1031
4
    llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1032
4
    if (!isInc)
1033
2
      FVal.changeSign();
1034
4
    NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1035
1036
    // Add the inc/dec to the real part.
1037
4
    NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? 
"inc"2
:
"dec"2
);
1038
4
  }
1039
1040
8
  ComplexPairTy IncVal(NextVal, InVal.second);
1041
1042
  // Store the updated result through the lvalue.
1043
8
  EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1044
8
  if (getLangOpts().OpenMP)
1045
0
    CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1046
0
                                                              E->getSubExpr());
1047
1048
  // If this is a postinc, return the value read from memory, otherwise use the
1049
  // updated value.
1050
8
  return isPre ? 
IncVal4
:
InVal4
;
1051
8
}
1052
1053
void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1054
148k
                                             CodeGenFunction *CGF) {
1055
  // Bind VLAs in the cast type.
1056
148k
  if (CGF && 
E->getType()->isVariablyModifiedType()148k
)
1057
14
    CGF->EmitVariablyModifiedType(E->getType());
1058
1059
148k
  if (CGDebugInfo *DI = getModuleDebugInfo())
1060
61.3k
    DI->EmitExplicitCastType(E->getType());
1061
148k
}
1062
1063
//===----------------------------------------------------------------------===//
1064
//                         LValue Expression Emission
1065
//===----------------------------------------------------------------------===//
1066
1067
/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1068
/// derive a more accurate bound on the alignment of the pointer.
1069
Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
1070
                                                  LValueBaseInfo *BaseInfo,
1071
286k
                                                  TBAAAccessInfo *TBAAInfo) {
1072
  // We allow this with ObjC object pointers because of fragile ABIs.
1073
286k
  assert(E->getType()->isPointerType() ||
1074
286k
         E->getType()->isObjCObjectPointerType());
1075
0
  E = E->IgnoreParens();
1076
1077
  // Casts:
1078
286k
  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1079
199k
    if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1080
3.48k
      CGM.EmitExplicitCastExprType(ECE, this);
1081
1082
199k
    switch (CE->getCastKind()) {
1083
    // Non-converting casts (but not C's implicit conversion from void*).
1084
2.49k
    case CK_BitCast:
1085
11.3k
    case CK_NoOp:
1086
11.3k
    case CK_AddressSpaceConversion:
1087
11.3k
      if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1088
11.3k
        if (PtrTy->getPointeeType()->isVoidType())
1089
1.02k
          break;
1090
1091
10.3k
        LValueBaseInfo InnerBaseInfo;
1092
10.3k
        TBAAAccessInfo InnerTBAAInfo;
1093
10.3k
        Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
1094
10.3k
                                                &InnerBaseInfo,
1095
10.3k
                                                &InnerTBAAInfo);
1096
10.3k
        if (BaseInfo) 
*BaseInfo = InnerBaseInfo6.99k
;
1097
10.3k
        if (TBAAInfo) 
*TBAAInfo = InnerTBAAInfo6.98k
;
1098
1099
10.3k
        if (isa<ExplicitCastExpr>(CE)) {
1100
2.43k
          LValueBaseInfo TargetTypeBaseInfo;
1101
2.43k
          TBAAAccessInfo TargetTypeTBAAInfo;
1102
2.43k
          CharUnits Align = CGM.getNaturalPointeeTypeAlignment(
1103
2.43k
              E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1104
2.43k
          if (TBAAInfo)
1105
2.31k
            *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1106
2.31k
                                                 TargetTypeTBAAInfo);
1107
          // If the source l-value is opaque, honor the alignment of the
1108
          // casted-to type.
1109
2.43k
          if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1110
1.91k
            if (BaseInfo)
1111
1.88k
              BaseInfo->mergeForCast(TargetTypeBaseInfo);
1112
1.91k
            Addr = Address(Addr.getPointer(), Addr.getElementType(), Align);
1113
1.91k
          }
1114
2.43k
        }
1115
1116
10.3k
        if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1117
10.3k
            
CE->getCastKind() == CK_BitCast4
) {
1118
2
          if (auto PT = E->getType()->getAs<PointerType>())
1119
2
            EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1120
2
                                      /*MayBeNull=*/true,
1121
2
                                      CodeGenFunction::CFITCK_UnrelatedCast,
1122
2
                                      CE->getBeginLoc());
1123
2
        }
1124
1125
10.3k
        llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
1126
10.3k
        Addr = Builder.CreateElementBitCast(Addr, ElemTy);
1127
10.3k
        if (CE->getCastKind() == CK_AddressSpaceConversion)
1128
5
          Addr = Builder.CreateAddrSpaceCast(Addr, ConvertType(E->getType()));
1129
10.3k
        return Addr;
1130
11.3k
      }
1131
4
      break;
1132
1133
    // Array-to-pointer decay.
1134
4.85k
    case CK_ArrayToPointerDecay:
1135
4.85k
      return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1136
1137
    // Derived-to-base conversions.
1138
6.44k
    case CK_UncheckedDerivedToBase:
1139
7.59k
    case CK_DerivedToBase: {
1140
      // TODO: Support accesses to members of base classes in TBAA. For now, we
1141
      // conservatively pretend that the complete object is of the base class
1142
      // type.
1143
7.59k
      if (TBAAInfo)
1144
6.23k
        *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
1145
7.59k
      Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
1146
7.59k
      auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1147
7.59k
      return GetAddressOfBaseClass(Addr, Derived,
1148
7.59k
                                   CE->path_begin(), CE->path_end(),
1149
7.59k
                                   ShouldNullCheckClassCastValue(CE),
1150
7.59k
                                   CE->getExprLoc());
1151
6.44k
    }
1152
1153
    // TODO: Is there any reason to treat base-to-derived conversions
1154
    // specially?
1155
175k
    default:
1156
175k
      break;
1157
199k
    }
1158
199k
  }
1159
1160
  // Unary &.
1161
263k
  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1162
2.40k
    if (UO->getOpcode() == UO_AddrOf) {
1163
2.31k
      LValue LV = EmitLValue(UO->getSubExpr());
1164
2.31k
      if (BaseInfo) 
*BaseInfo = LV.getBaseInfo()659
;
1165
2.31k
      if (TBAAInfo) 
*TBAAInfo = LV.getTBAAInfo()655
;
1166
2.31k
      return LV.getAddress(*this);
1167
2.31k
    }
1168
2.40k
  }
1169
1170
  // std::addressof and variants.
1171
260k
  if (auto *Call = dyn_cast<CallExpr>(E)) {
1172
3.01k
    switch (Call->getBuiltinCallee()) {
1173
3.01k
    default:
1174
3.01k
      break;
1175
3.01k
    case Builtin::BIaddressof:
1176
1
    case Builtin::BI__addressof:
1177
1
    case Builtin::BI__builtin_addressof: {
1178
1
      LValue LV = EmitLValue(Call->getArg(0));
1179
1
      if (BaseInfo) 
*BaseInfo = LV.getBaseInfo()0
;
1180
1
      if (TBAAInfo) 
*TBAAInfo = LV.getTBAAInfo()0
;
1181
1
      return LV.getAddress(*this);
1182
1
    }
1183
3.01k
    }
1184
3.01k
  }
1185
1186
  // TODO: conditional operators, comma.
1187
1188
  // Otherwise, use the alignment of the type.
1189
260k
  CharUnits Align =
1190
260k
      CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
1191
260k
  llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
1192
260k
  return Address(EmitScalarExpr(E), ElemTy, Align);
1193
260k
}
1194
1195
34
llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1196
34
  llvm::Value *V = RV.getScalarVal();
1197
34
  if (auto MPT = T->getAs<MemberPointerType>())
1198
4
    return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1199
30
  return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1200
34
}
1201
1202
137k
RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1203
137k
  if (Ty->isVoidType())
1204
137k
    return RValue::get(nullptr);
1205
1206
672
  switch (getEvaluationKind(Ty)) {
1207
0
  case TEK_Complex: {
1208
0
    llvm::Type *EltTy =
1209
0
      ConvertType(Ty->castAs<ComplexType>()->getElementType());
1210
0
    llvm::Value *U = llvm::UndefValue::get(EltTy);
1211
0
    return RValue::getComplex(std::make_pair(U, U));
1212
0
  }
1213
1214
  // If this is a use of an undefined aggregate type, the aggregate must have an
1215
  // identifiable address.  Just because the contents of the value are undefined
1216
  // doesn't mean that the address can't be taken and compared.
1217
638
  case TEK_Aggregate: {
1218
638
    Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1219
638
    return RValue::getAggregate(DestPtr);
1220
0
  }
1221
1222
34
  case TEK_Scalar:
1223
34
    return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1224
672
  }
1225
0
  llvm_unreachable("bad evaluation kind");
1226
0
}
1227
1228
RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1229
0
                                              const char *Name) {
1230
0
  ErrorUnsupported(E, Name);
1231
0
  return GetUndefRValue(E->getType());
1232
0
}
1233
1234
LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1235
0
                                              const char *Name) {
1236
0
  ErrorUnsupported(E, Name);
1237
0
  llvm::Type *ElTy = ConvertType(E->getType());
1238
0
  llvm::Type *Ty = llvm::PointerType::getUnqual(ElTy);
1239
0
  return MakeAddrLValue(
1240
0
      Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1241
0
}
1242
1243
343k
bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1244
343k
  const Expr *Base = Obj;
1245
528k
  while (!isa<CXXThisExpr>(Base)) {
1246
    // The result of a dynamic_cast can be null.
1247
432k
    if (isa<CXXDynamicCastExpr>(Base))
1248
3
      return false;
1249
1250
432k
    if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1251
183k
      Base = CE->getSubExpr();
1252
248k
    } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1253
1.02k
      Base = PE->getSubExpr();
1254
247k
    } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1255
5.24k
      if (UO->getOpcode() == UO_Extension)
1256
6
        Base = UO->getSubExpr();
1257
5.23k
      else
1258
5.23k
        return false;
1259
242k
    } else {
1260
242k
      return false;
1261
242k
    }
1262
432k
  }
1263
95.6k
  return true;
1264
343k
}
1265
1266
1.34M
LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1267
1.34M
  LValue LV;
1268
1.34M
  if (SanOpts.has(SanitizerKind::ArrayBounds) && 
isa<ArraySubscriptExpr>(E)265
)
1269
52
    LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1270
1.34M
  else
1271
1.34M
    LV = EmitLValue(E);
1272
1.34M
  if (!isa<DeclRefExpr>(E) && 
!LV.isBitField()267k
&&
LV.isSimple()260k
) {
1273
259k
    SanitizerSet SkippedChecks;
1274
259k
    if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1275
145k
      bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1276
145k
      if (IsBaseCXXThis)
1277
22.4k
        SkippedChecks.set(SanitizerKind::Alignment, true);
1278
145k
      if (IsBaseCXXThis || 
isa<DeclRefExpr>(ME->getBase())122k
)
1279
33.3k
        SkippedChecks.set(SanitizerKind::Null, true);
1280
145k
    }
1281
259k
    EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1282
259k
                  LV.getAlignment(), SkippedChecks);
1283
259k
  }
1284
1.34M
  return LV;
1285
1.34M
}
1286
1287
/// EmitLValue - Emit code to compute a designator that specifies the location
1288
/// of the expression.
1289
///
1290
/// This can return one of two things: a simple address or a bitfield reference.
1291
/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1292
/// an LLVM pointer type.
1293
///
1294
/// If this returns a bitfield reference, nothing about the pointee type of the
1295
/// LLVM value is known: For example, it may not be a pointer to an integer.
1296
///
1297
/// If this returns a normal address, and if the lvalue's C type is fixed size,
1298
/// this method guarantees that the returned pointer type will point to an LLVM
1299
/// type of the same size of the lvalue's type.  If the lvalue has a variable
1300
/// length type, this is not possible.
1301
///
1302
2.11M
LValue CodeGenFunction::EmitLValue(const Expr *E) {
1303
2.11M
  ApplyDebugLocation DL(*this, E);
1304
2.11M
  switch (E->getStmtClass()) {
1305
0
  default: return EmitUnsupportedLValue(E, "l-value expression");
1306
1307
0
  case Expr::ObjCPropertyRefExprClass:
1308
0
    llvm_unreachable("cannot emit a property reference directly");
1309
1310
1
  case Expr::ObjCSelectorExprClass:
1311
1
    return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1312
6
  case Expr::ObjCIsaExprClass:
1313
6
    return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1314
142k
  case Expr::BinaryOperatorClass:
1315
142k
    return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1316
19.6k
  case Expr::CompoundAssignOperatorClass: {
1317
19.6k
    QualType Ty = E->getType();
1318
19.6k
    if (const AtomicType *AT = Ty->getAs<AtomicType>())
1319
8
      Ty = AT->getValueType();
1320
19.6k
    if (!Ty->isAnyComplexType())
1321
19.6k
      return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1322
64
    return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1323
19.6k
  }
1324
17.0k
  case Expr::CallExprClass:
1325
42.2k
  case Expr::CXXMemberCallExprClass:
1326
47.7k
  case Expr::CXXOperatorCallExprClass:
1327
47.7k
  case Expr::UserDefinedLiteralClass:
1328
47.7k
    return EmitCallExprLValue(cast<CallExpr>(E));
1329
0
  case Expr::CXXRewrittenBinaryOperatorClass:
1330
0
    return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
1331
10
  case Expr::VAArgExprClass:
1332
10
    return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1333
1.42M
  case Expr::DeclRefExprClass:
1334
1.42M
    return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1335
2
  case Expr::ConstantExprClass: {
1336
2
    const ConstantExpr *CE = cast<ConstantExpr>(E);
1337
2
    if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1338
2
      QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
1339
2
                             ->getCallReturnType(getContext())
1340
2
                             ->getPointeeType();
1341
2
      return MakeNaturalAlignAddrLValue(Result, RetType);
1342
2
    }
1343
0
    return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
1344
2
  }
1345
3.44k
  case Expr::ParenExprClass:
1346
3.44k
    return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1347
0
  case Expr::GenericSelectionExprClass:
1348
0
    return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1349
563
  case Expr::PredefinedExprClass:
1350
563
    return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1351
83.6k
  case Expr::StringLiteralClass:
1352
83.6k
    return EmitStringLiteralLValue(cast<StringLiteral>(E));
1353
17
  case Expr::ObjCEncodeExprClass:
1354
17
    return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1355
15
  case Expr::PseudoObjectExprClass:
1356
15
    return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1357
6
  case Expr::InitListExprClass:
1358
6
    return EmitInitListLValue(cast<InitListExpr>(E));
1359
1
  case Expr::CXXTemporaryObjectExprClass:
1360
1
  case Expr::CXXConstructExprClass:
1361
1
    return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1362
3
  case Expr::CXXBindTemporaryExprClass:
1363
3
    return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1364
23
  case Expr::CXXUuidofExprClass:
1365
23
    return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1366
4
  case Expr::LambdaExprClass:
1367
4
    return EmitAggExprToLValue(E);
1368
1369
1.41k
  case Expr::ExprWithCleanupsClass: {
1370
1.41k
    const auto *cleanups = cast<ExprWithCleanups>(E);
1371
1.41k
    RunCleanupsScope Scope(*this);
1372
1.41k
    LValue LV = EmitLValue(cleanups->getSubExpr());
1373
1.41k
    if (LV.isSimple()) {
1374
      // Defend against branches out of gnu statement expressions surrounded by
1375
      // cleanups.
1376
1.41k
      Address Addr = LV.getAddress(*this);
1377
1.41k
      llvm::Value *V = Addr.getPointer();
1378
1.41k
      Scope.ForceCleanup({&V});
1379
1.41k
      return LValue::MakeAddr(Addr.withPointer(V), LV.getType(), getContext(),
1380
1.41k
                              LV.getBaseInfo(), LV.getTBAAInfo());
1381
1.41k
    }
1382
    // FIXME: Is it possible to create an ExprWithCleanups that produces a
1383
    // bitfield lvalue or some other non-simple lvalue?
1384
0
    return LV;
1385
1.41k
  }
1386
1387
82
  case Expr::CXXDefaultArgExprClass: {
1388
82
    auto *DAE = cast<CXXDefaultArgExpr>(E);
1389
82
    CXXDefaultArgExprScope Scope(*this, DAE);
1390
82
    return EmitLValue(DAE->getExpr());
1391
1.41k
  }
1392
14
  case Expr::CXXDefaultInitExprClass: {
1393
14
    auto *DIE = cast<CXXDefaultInitExpr>(E);
1394
14
    CXXDefaultInitExprScope Scope(*this, DIE);
1395
14
    return EmitLValue(DIE->getExpr());
1396
1.41k
  }
1397
392
  case Expr::CXXTypeidExprClass:
1398
392
    return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1399
1400
20
  case Expr::ObjCMessageExprClass:
1401
20
    return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1402
1.51k
  case Expr::ObjCIvarRefExprClass:
1403
1.51k
    return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1404
1
  case Expr::StmtExprClass:
1405
1
    return EmitStmtExprLValue(cast<StmtExpr>(E));
1406
71.3k
  case Expr::UnaryOperatorClass:
1407
71.3k
    return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1408
68.6k
  case Expr::ArraySubscriptExprClass:
1409
68.6k
    return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1410
34
  case Expr::MatrixSubscriptExprClass:
1411
34
    return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
1412
1.68k
  case Expr::OMPArraySectionExprClass:
1413
1.68k
    return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1414
294
  case Expr::ExtVectorElementExprClass:
1415
294
    return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1416
189k
  case Expr::MemberExprClass:
1417
189k
    return EmitMemberExpr(cast<MemberExpr>(E));
1418
1.22k
  case Expr::CompoundLiteralExprClass:
1419
1.22k
    return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1420
525
  case Expr::ConditionalOperatorClass:
1421
525
    return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1422
6
  case Expr::BinaryConditionalOperatorClass:
1423
6
    return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1424
2
  case Expr::ChooseExprClass:
1425
2
    return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1426
1.08k
  case Expr::OpaqueValueExprClass:
1427
1.08k
    return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1428
8
  case Expr::SubstNonTypeTemplateParmExprClass:
1429
8
    return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1430
31.9k
  case Expr::ImplicitCastExprClass:
1431
32.0k
  case Expr::CStyleCastExprClass:
1432
32.0k
  case Expr::CXXFunctionalCastExprClass:
1433
38.7k
  case Expr::CXXStaticCastExprClass:
1434
38.7k
  case Expr::CXXDynamicCastExprClass:
1435
38.7k
  case Expr::CXXReinterpretCastExprClass:
1436
38.9k
  case Expr::CXXConstCastExprClass:
1437
38.9k
  case Expr::CXXAddrspaceCastExprClass:
1438
38.9k
  case Expr::ObjCBridgedCastExprClass:
1439
38.9k
    return EmitCastLValue(cast<CastExpr>(E));
1440
1441
15.8k
  case Expr::MaterializeTemporaryExprClass:
1442
15.8k
    return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1443
1444
4
  case Expr::CoawaitExprClass:
1445
4
    return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1446
2
  case Expr::CoyieldExprClass:
1447
2
    return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1448
2.11M
  }
1449
2.11M
}
1450
1451
/// Given an object of the given canonical type, can we safely copy a
1452
/// value out of it based on its initializer?
1453
565k
static bool isConstantEmittableObjectType(QualType type) {
1454
565k
  assert(type.isCanonical());
1455
0
  assert(!type->isReferenceType());
1456
1457
  // Must be const-qualified but non-volatile.
1458
0
  Qualifiers qs = type.getLocalQualifiers();
1459
565k
  if (!qs.hasConst() || 
qs.hasVolatile()39.1k
)
return false526k
;
1460
1461
  // Otherwise, all object types satisfy this except C++ classes with
1462
  // mutable subobjects or non-trivial copy/destroy behavior.
1463
39.1k
  if (const auto *RT = dyn_cast<RecordType>(type))
1464
0
    if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1465
0
      if (RD->hasMutableFields() || !RD->isTrivial())
1466
0
        return false;
1467
1468
39.1k
  return true;
1469
39.1k
}
1470
1471
/// Can we constant-emit a load of a reference to a variable of the
1472
/// given type?  This is different from predicates like
1473
/// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1474
/// in situations that don't necessarily satisfy the language's rules
1475
/// for this (e.g. C++'s ODR-use rules).  For example, we want to able
1476
/// to do this with const float variables even if those variables
1477
/// aren't marked 'constexpr'.
1478
enum ConstantEmissionKind {
1479
  CEK_None,
1480
  CEK_AsReferenceOnly,
1481
  CEK_AsValueOrReference,
1482
  CEK_AsValueOnly
1483
};
1484
565k
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1485
565k
  type = type.getCanonicalType();
1486
565k
  if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1487
2.24k
    if (isConstantEmittableObjectType(ref->getPointeeType()))
1488
50
      return CEK_AsValueOrReference;
1489
2.19k
    return CEK_AsReferenceOnly;
1490
2.24k
  }
1491
563k
  if (isConstantEmittableObjectType(type))
1492
39.1k
    return CEK_AsValueOnly;
1493
524k
  return CEK_None;
1494
563k
}
1495
1496
/// Try to emit a reference to the given value without producing it as
1497
/// an l-value.  This is just an optimization, but it avoids us needing
1498
/// to emit global copies of variables if they're named without triggering
1499
/// a formal use in a context where we can't emit a direct reference to them,
1500
/// for instance if a block or lambda or a member of a local class uses a
1501
/// const int variable or constexpr variable from an enclosing function.
1502
CodeGenFunction::ConstantEmission
1503
935k
CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1504
935k
  ValueDecl *value = refExpr->getDecl();
1505
1506
  // The value needs to be an enum constant or a constant variable.
1507
935k
  ConstantEmissionKind CEK;
1508
935k
  if (isa<ParmVarDecl>(value)) {
1509
367k
    CEK = CEK_None;
1510
568k
  } else if (auto *var = dyn_cast<VarDecl>(value)) {
1511
565k
    CEK = checkVarTypeForConstantEmission(var->getType());
1512
565k
  } else 
if (2.45k
isa<EnumConstantDecl>(value)2.45k
) {
1513
2.29k
    CEK = CEK_AsValueOnly;
1514
2.29k
  } else {
1515
155
    CEK = CEK_None;
1516
155
  }
1517
935k
  if (CEK == CEK_None) 
return ConstantEmission()892k
;
1518
1519
43.6k
  Expr::EvalResult result;
1520
43.6k
  bool resultIsReference;
1521
43.6k
  QualType resultType;
1522
1523
  // It's best to evaluate all the way as an r-value if that's permitted.
1524
43.6k
  if (CEK != CEK_AsReferenceOnly &&
1525
43.6k
      
refExpr->EvaluateAsRValue(result, getContext())41.4k
) {
1526
6.90k
    resultIsReference = false;
1527
6.90k
    resultType = refExpr->getType();
1528
1529
  // Otherwise, try to evaluate as an l-value.
1530
36.7k
  } else if (CEK != CEK_AsValueOnly &&
1531
36.7k
             
refExpr->EvaluateAsLValue(result, getContext())2.24k
) {
1532
61
    resultIsReference = true;
1533
61
    resultType = value->getType();
1534
1535
  // Failure.
1536
36.6k
  } else {
1537
36.6k
    return ConstantEmission();
1538
36.6k
  }
1539
1540
  // In any case, if the initializer has side-effects, abandon ship.
1541
6.96k
  if (result.HasSideEffects)
1542
0
    return ConstantEmission();
1543
1544
  // In CUDA/HIP device compilation, a lambda may capture a reference variable
1545
  // referencing a global host variable by copy. In this case the lambda should
1546
  // make a copy of the value of the global host variable. The DRE of the
1547
  // captured reference variable cannot be emitted as load from the host
1548
  // global variable as compile time constant, since the host variable is not
1549
  // accessible on device. The DRE of the captured reference variable has to be
1550
  // loaded from captures.
1551
6.96k
  if (CGM.getLangOpts().CUDAIsDevice && 
result.Val.isLValue()24
&&
1552
6.96k
      
refExpr->refersToEnclosingVariableOrCapture()5
) {
1553
3
    auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1554
3
    if (MD && MD->getParent()->isLambda() &&
1555
3
        MD->getOverloadedOperator() == OO_Call) {
1556
3
      const APValue::LValueBase &base = result.Val.getLValueBase();
1557
3
      if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1558
3
        if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1559
3
          if (!VD->hasAttr<CUDADeviceAttr>()) {
1560
1
            return ConstantEmission();
1561
1
          }
1562
3
        }
1563
3
      }
1564
3
    }
1565
3
  }
1566
1567
  // Emit as a constant.
1568
6.96k
  auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1569
6.96k
                                               result.Val, resultType);
1570
1571
  // Make sure we emit a debug reference to the global variable.
1572
  // This should probably fire even for
1573
6.96k
  if (isa<VarDecl>(value)) {
1574
4.66k
    if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1575
4.52k
      EmitDeclRefExprDbgValue(refExpr, result.Val);
1576
4.66k
  } else {
1577
2.29k
    assert(isa<EnumConstantDecl>(value));
1578
0
    EmitDeclRefExprDbgValue(refExpr, result.Val);
1579
2.29k
  }
1580
1581
  // If we emitted a reference constant, we need to dereference that.
1582
6.96k
  if (resultIsReference)
1583
60
    return ConstantEmission::forReference(C);
1584
1585
6.90k
  return ConstantEmission::forValue(C);
1586
6.96k
}
1587
1588
static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1589
303k
                                                        const MemberExpr *ME) {
1590
303k
  if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1591
    // Try to emit static variable member expressions as DREs.
1592
57
    return DeclRefExpr::Create(
1593
57
        CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1594
57
        /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1595
57
        ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
1596
57
  }
1597
303k
  return nullptr;
1598
303k
}
1599
1600
CodeGenFunction::ConstantEmission
1601
113k
CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1602
113k
  if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1603
28
    return tryEmitAsConstant(DRE);
1604
113k
  return ConstantEmission();
1605
113k
}
1606
1607
llvm::Value *CodeGenFunction::emitScalarConstant(
1608
6.95k
    const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1609
6.95k
  assert(Constant && "not a constant");
1610
6.95k
  if (Constant.isReference())
1611
57
    return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1612
57
                            E->getExprLoc())
1613
57
        .getScalarVal();
1614
6.89k
  return Constant.getValue();
1615
6.95k
}
1616
1617
llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1618
1.21M
                                               SourceLocation Loc) {
1619
1.21M
  return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
1620
1.21M
                          lvalue.getType(), Loc, lvalue.getBaseInfo(),
1621
1.21M
                          lvalue.getTBAAInfo(), lvalue.isNontemporal());
1622
1.21M
}
1623
1624
2.31M
static bool hasBooleanRepresentation(QualType Ty) {
1625
2.31M
  if (Ty->isBooleanType())
1626
8.26k
    return true;
1627
1628
2.30M
  if (const EnumType *ET = Ty->getAs<EnumType>())
1629
2.23k
    return ET->getDecl()->getIntegerType()->isBooleanType();
1630
1631
2.30M
  if (const AtomicType *AT = Ty->getAs<AtomicType>())
1632
113
    return hasBooleanRepresentation(AT->getValueType());
1633
1634
2.30M
  return false;
1635
2.30M
}
1636
1637
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1638
                            llvm::APInt &Min, llvm::APInt &End,
1639
94.5k
                            bool StrictEnums, bool IsBool) {
1640
94.5k
  const EnumType *ET = Ty->getAs<EnumType>();
1641
94.5k
  bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && 
StrictEnums36.8k
&&
1642
94.5k
                                
ET50
&&
!ET->getDecl()->isFixed()23
;
1643
94.5k
  if (!IsBool && 
!IsRegularCPlusPlusEnum94.2k
)
1644
94.2k
    return false;
1645
1646
306
  if (IsBool) {
1647
285
    Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1648
285
    End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1649
285
  } else {
1650
21
    const EnumDecl *ED = ET->getDecl();
1651
21
    llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1652
21
    unsigned Bitwidth = LTy->getScalarSizeInBits();
1653
21
    unsigned NumNegativeBits = ED->getNumNegativeBits();
1654
21
    unsigned NumPositiveBits = ED->getNumPositiveBits();
1655
1656
21
    if (NumNegativeBits) {
1657
9
      unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1658
9
      assert(NumBits <= Bitwidth);
1659
0
      End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1660
9
      Min = -End;
1661
12
    } else {
1662
12
      assert(NumPositiveBits <= Bitwidth);
1663
0
      End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1664
12
      Min = llvm::APInt::getZero(Bitwidth);
1665
12
    }
1666
21
  }
1667
0
  return true;
1668
94.5k
}
1669
1670
94.5k
llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1671
94.5k
  llvm::APInt Min, End;
1672
94.5k
  if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1673
94.5k
                       hasBooleanRepresentation(Ty)))
1674
94.2k
    return nullptr;
1675
1676
283
  llvm::MDBuilder MDHelper(getLLVMContext());
1677
283
  return MDHelper.createRange(Min, End);
1678
94.5k
}
1679
1680
bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1681
1.22M
                                           SourceLocation Loc) {
1682
1.22M
  bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1683
1.22M
  bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1684
1.22M
  if (!HasBoolCheck && 
!HasEnumCheck1.22M
)
1685
1.22M
    return false;
1686
1687
234
  bool IsBool = hasBooleanRepresentation(Ty) ||
1688
234
                
NSAPI(CGM.getContext()).isObjCBOOLType(Ty)225
;
1689
234
  bool NeedsBoolCheck = HasBoolCheck && 
IsBool188
;
1690
234
  bool NeedsEnumCheck = HasEnumCheck && 
Ty->getAs<EnumType>()127
;
1691
234
  if (!NeedsBoolCheck && 
!NeedsEnumCheck215
)
1692
208
    return false;
1693
1694
  // Single-bit booleans don't need to be checked. Special-case this to avoid
1695
  // a bit width mismatch when handling bitfield values. This is handled by
1696
  // EmitFromMemory for the non-bitfield case.
1697
26
  if (IsBool &&
1698
26
      
cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 119
)
1699
3
    return false;
1700
1701
23
  llvm::APInt Min, End;
1702
23
  if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1703
0
    return true;
1704
1705
23
  auto &Ctx = getLLVMContext();
1706
23
  SanitizerScope SanScope(this);
1707
23
  llvm::Value *Check;
1708
23
  --End;
1709
23
  if (!Min) {
1710
21
    Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1711
21
  } else {
1712
2
    llvm::Value *Upper =
1713
2
        Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1714
2
    llvm::Value *Lower =
1715
2
        Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1716
2
    Check = Builder.CreateAnd(Upper, Lower);
1717
2
  }
1718
23
  llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1719
23
                                  EmitCheckTypeDescriptor(Ty)};
1720
23
  SanitizerMask Kind =
1721
23
      NeedsEnumCheck ? 
SanitizerKind::Enum7
:
SanitizerKind::Bool16
;
1722
23
  EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1723
23
            StaticArgs, EmitCheckValue(Value));
1724
23
  return true;
1725
23
}
1726
1727
llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1728
                                               QualType Ty,
1729
                                               SourceLocation Loc,
1730
                                               LValueBaseInfo BaseInfo,
1731
                                               TBAAAccessInfo TBAAInfo,
1732
1.21M
                                               bool isNontemporal) {
1733
1.21M
  if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1734
    // Boolean vectors use `iN` as storage type.
1735
90.6k
    if (ClangVecTy->isExtVectorBoolType()) {
1736
0
      llvm::Type *ValTy = ConvertType(Ty);
1737
0
      unsigned ValNumElems =
1738
0
          cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1739
      // Load the `iP` storage object (P is the padded vector size).
1740
0
      auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
1741
0
      const auto *RawIntTy = RawIntV->getType();
1742
0
      assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
1743
      // Bitcast iP --> <P x i1>.
1744
0
      auto *PaddedVecTy = llvm::FixedVectorType::get(
1745
0
          Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1746
0
      llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
1747
      // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1748
0
      V = emitBoolVecConversion(V, ValNumElems, "extractvec");
1749
1750
0
      return EmitFromMemory(V, Ty);
1751
0
    }
1752
1753
    // Handle vectors of size 3 like size 4 for better performance.
1754
90.6k
    const llvm::Type *EltTy = Addr.getElementType();
1755
90.6k
    const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
1756
1757
90.6k
    if (!CGM.getCodeGenOpts().PreserveVec3Type && 
VTy->getNumElements() == 390.6k
) {
1758
1759
      // Bitcast to vec4 type.
1760
54
      llvm::VectorType *vec4Ty =
1761
54
          llvm::FixedVectorType::get(VTy->getElementType(), 4);
1762
54
      Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1763
      // Now load value.
1764
54
      llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1765
1766
      // Shuffle vector to get vec3.
1767
54
      V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec");
1768
54
      return EmitFromMemory(V, Ty);
1769
54
    }
1770
90.6k
  }
1771
1772
  // Atomic operations have to be done on integral types.
1773
1.21M
  LValue AtomicLValue =
1774
1.21M
      LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1775
1.21M
  if (Ty->isAtomicType() || 
LValueIsSuitableForInlineAtomic(AtomicLValue)1.21M
) {
1776
60
    return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1777
60
  }
1778
1779
1.21M
  llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1780
1.21M
  if (isNontemporal) {
1781
173
    llvm::MDNode *Node = llvm::MDNode::get(
1782
173
        Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1783
173
    Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1784
173
  }
1785
1786
1.21M
  CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1787
1788
1.21M
  if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1789
    // In order to prevent the optimizer from throwing away the check, don't
1790
    // attach range metadata to the load.
1791
1.21M
  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1792
94.5k
    if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1793
280
      Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1794
1795
1.21M
  return EmitFromMemory(Load, Ty);
1796
1.21M
}
1797
1798
990k
llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1799
  // Bool has a different representation in memory than in registers.
1800
990k
  if (hasBooleanRepresentation(Ty)) {
1801
    // This should really always be an i1, but sometimes it's already
1802
    // an i8, and it's awkward to track those cases down.
1803
4.53k
    if (Value->getType()->isIntegerTy(1))
1804
4.49k
      return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1805
47
    assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1806
47
           "wrong value rep of bool");
1807
47
  }
1808
1809
985k
  return Value;
1810
990k
}
1811
1812
1.22M
llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1813
  // Bool has a different representation in memory than in registers.
1814
1.22M
  if (hasBooleanRepresentation(Ty)) {
1815
3.42k
    assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1816
3.42k
           "wrong value rep of bool");
1817
0
    return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1818
3.42k
  }
1819
1.22M
  if (Ty->isExtVectorBoolType()) {
1820
0
    const auto *RawIntTy = Value->getType();
1821
    // Bitcast iP --> <P x i1>.
1822
0
    auto *PaddedVecTy = llvm::FixedVectorType::get(
1823
0
        Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1824
0
    auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
1825
    // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1826
0
    llvm::Type *ValTy = ConvertType(Ty);
1827
0
    unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1828
0
    return emitBoolVecConversion(V, ValNumElems, "extractvec");
1829
0
  }
1830
1831
1.22M
  return Value;
1832
1.22M
}
1833
1834
// Convert the pointer of \p Addr to a pointer to a vector (the value type of
1835
// MatrixType), if it points to a array (the memory type of MatrixType).
1836
static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
1837
1.01k
                                         bool IsVector = true) {
1838
1.01k
  auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
1839
1.01k
  if (ArrayTy && 
IsVector279
) {
1840
279
    auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1841
279
                                                ArrayTy->getNumElements());
1842
1843
279
    return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
1844
279
  }
1845
737
  auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
1846
737
  if (VectorTy && !IsVector) {
1847
0
    auto *ArrayTy = llvm::ArrayType::get(
1848
0
        VectorTy->getElementType(),
1849
0
        cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
1850
1851
0
    return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
1852
0
  }
1853
1854
737
  return Addr;
1855
737
}
1856
1857
// Emit a store of a matrix LValue. This may require casting the original
1858
// pointer to memory address (ArrayType) to a pointer to the value type
1859
// (VectorType).
1860
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
1861
597
                                    bool isInit, CodeGenFunction &CGF) {
1862
597
  Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
1863
597
                                           value->getType()->isVectorTy());
1864
597
  CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
1865
597
                        lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
1866
597
                        lvalue.isNontemporal());
1867
597
}
1868
1869
void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1870
                                        bool Volatile, QualType Ty,
1871
                                        LValueBaseInfo BaseInfo,
1872
                                        TBAAAccessInfo TBAAInfo,
1873
989k
                                        bool isInit, bool isNontemporal) {
1874
989k
  llvm::Type *SrcTy = Value->getType();
1875
989k
  if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1876
87.0k
    auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy);
1877
87.0k
    if (VecTy && 
ClangVecTy->isExtVectorBoolType()87.0k
) {
1878
11
      auto *MemIntTy = cast<llvm::IntegerType>(Addr.getElementType());
1879
      // Expand to the memory bit width.
1880
11
      unsigned MemNumElems = MemIntTy->getPrimitiveSizeInBits();
1881
      // <N x i1> --> <P x i1>.
1882
11
      Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
1883
      // <P x i1> --> iP.
1884
11
      Value = Builder.CreateBitCast(Value, MemIntTy);
1885
87.0k
    } else if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1886
      // Handle vec3 special.
1887
87.0k
      if (VecTy && 
cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 387.0k
) {
1888
        // Our source is a vec3, do a shuffle vector to make it a vec4.
1889
172
        Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
1890
172
                                            "extractVec");
1891
172
        SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
1892
172
      }
1893
87.0k
      if (Addr.getElementType() != SrcTy) {
1894
174
        Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1895
174
      }
1896
87.0k
    }
1897
87.0k
  }
1898
1899
989k
  Value = EmitToMemory(Value, Ty);
1900
1901
989k
  LValue AtomicLValue =
1902
989k
      LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1903
989k
  if (Ty->isAtomicType() ||
1904
989k
      
(989k
!isInit989k
&&
LValueIsSuitableForInlineAtomic(AtomicLValue)263k
)) {
1905
65
    EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1906
65
    return;
1907
65
  }
1908
1909
989k
  llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1910
989k
  if (isNontemporal) {
1911
242
    llvm::MDNode *Node =
1912
242
        llvm::MDNode::get(Store->getContext(),
1913
242
                          llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1914
242
    Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1915
242
  }
1916
1917
989k
  CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1918
989k
}
1919
1920
void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1921
987k
                                        bool isInit) {
1922
987k
  if (lvalue.getType()->isConstantMatrixType()) {
1923
597
    EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
1924
597
    return;
1925
597
  }
1926
1927
987k
  EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
1928
987k
                    lvalue.getType(), lvalue.getBaseInfo(),
1929
987k
                    lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1930
987k
}
1931
1932
// Emit a load of a LValue of matrix type. This may require casting the pointer
1933
// to memory address (ArrayType) to a pointer to the value type (VectorType).
1934
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
1935
385
                                     CodeGenFunction &CGF) {
1936
385
  assert(LV.getType()->isConstantMatrixType());
1937
0
  Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
1938
385
  LV.setAddress(Addr);
1939
385
  return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
1940
385
}
1941
1942
/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1943
/// method emits the address of the lvalue, then loads the result as an rvalue,
1944
/// returning the rvalue.
1945
1.14M
RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1946
1.14M
  if (LV.isObjCWeak()) {
1947
    // load of a __weak object.
1948
39
    Address AddrWeakObj = LV.getAddress(*this);
1949
39
    return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1950
39
                                                             AddrWeakObj));
1951
39
  }
1952
1.14M
  if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1953
    // In MRC mode, we do a load+autorelease.
1954
151
    if (!getLangOpts().ObjCAutoRefCount) {
1955
15
      return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
1956
15
    }
1957
1958
    // In ARC mode, we load retained and then consume the value.
1959
136
    llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
1960
136
    Object = EmitObjCConsumeObject(LV.getType(), Object);
1961
136
    return RValue::get(Object);
1962
151
  }
1963
1964
1.14M
  if (LV.isSimple()) {
1965
1.13M
    assert(!LV.getType()->isFunctionType());
1966
1967
1.13M
    if (LV.getType()->isConstantMatrixType())
1968
385
      return EmitLoadOfMatrixLValue(LV, Loc, *this);
1969
1970
    // Everything needs a load.
1971
1.13M
    return RValue::get(EmitLoadOfScalar(LV, Loc));
1972
1.13M
  }
1973
1974
6.58k
  if (LV.isVectorElt()) {
1975
65
    llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1976
65
                                              LV.isVolatileQualified());
1977
65
    return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1978
65
                                                    "vecext"));
1979
65
  }
1980
1981
  // If this is a reference to a subset of the elements of a vector, either
1982
  // shuffle the input or extract/insert them as appropriate.
1983
6.52k
  if (LV.isExtVectorElt()) {
1984
252
    return EmitLoadOfExtVectorElementLValue(LV);
1985
252
  }
1986
1987
  // Global Register variables always invoke intrinsics
1988
6.26k
  if (LV.isGlobalReg())
1989
30
    return EmitLoadOfGlobalRegLValue(LV);
1990
1991
6.23k
  if (LV.isMatrixElt()) {
1992
4
    llvm::Value *Idx = LV.getMatrixIdx();
1993
4
    if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
1994
2
      const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
1995
2
      llvm::MatrixBuilder MB(Builder);
1996
2
      MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
1997
2
    }
1998
4
    llvm::LoadInst *Load =
1999
4
        Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2000
4
    return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
2001
4
  }
2002
2003
6.23k
  assert(LV.isBitField() && "Unknown LValue type!");
2004
0
  return EmitLoadOfBitfieldLValue(LV, Loc);
2005
6.23k
}
2006
2007
RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
2008
6.25k
                                                 SourceLocation Loc) {
2009
6.25k
  const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2010
2011
  // Get the output type.
2012
6.25k
  llvm::Type *ResLTy = ConvertType(LV.getType());
2013
2014
6.25k
  Address Ptr = LV.getBitFieldAddress();
2015
6.25k
  llvm::Value *Val =
2016
6.25k
      Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2017
2018
6.25k
  bool UseVolatile = LV.isVolatileQualified() &&
2019
6.25k
                     
Info.VolatileStorageSize != 0237
&&
isAAPCS(CGM.getTarget())57
;
2020
6.25k
  const unsigned Offset = UseVolatile ? 
Info.VolatileOffset57
:
Info.Offset6.19k
;
2021
6.25k
  const unsigned StorageSize =
2022
6.25k
      UseVolatile ? 
Info.VolatileStorageSize57
:
Info.StorageSize6.19k
;
2023
6.25k
  if (Info.IsSigned) {
2024
690
    assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2025
0
    unsigned HighBits = StorageSize - Offset - Info.Size;
2026
690
    if (HighBits)
2027
443
      Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2028
690
    if (Offset + HighBits)
2029
580
      Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2030
5.56k
  } else {
2031
5.56k
    if (Offset)
2032
2.81k
      Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2033
5.56k
    if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2034
5.30k
      Val = Builder.CreateAnd(
2035
5.30k
          Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2036
5.56k
  }
2037
0
  Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2038
6.25k
  EmitScalarRangeCheck(Val, LV.getType(), Loc);
2039
6.25k
  return RValue::get(Val);
2040
6.25k
}
2041
2042
// If this is a reference to a subset of the elements of a vector, create an
2043
// appropriate shufflevector.
2044
254
RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
2045
254
  llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2046
254
                                        LV.isVolatileQualified());
2047
2048
254
  const llvm::Constant *Elts = LV.getExtVectorElts();
2049
2050
  // If the result of the expression is a non-vector type, we must be extracting
2051
  // a single element.  Just codegen as an extractelement.
2052
254
  const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2053
254
  if (!ExprVT) {
2054
211
    unsigned InIdx = getAccessedFieldNo(0, Elts);
2055
211
    llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2056
211
    return RValue::get(Builder.CreateExtractElement(Vec, Elt));
2057
211
  }
2058
2059
  // Always use shuffle vector to try to retain the original program structure
2060
43
  unsigned NumResultElts = ExprVT->getNumElements();
2061
2062
43
  SmallVector<int, 4> Mask;
2063
169
  for (unsigned i = 0; i != NumResultElts; 
++i126
)
2064
126
    Mask.push_back(getAccessedFieldNo(i, Elts));
2065
2066
43
  Vec = Builder.CreateShuffleVector(Vec, Mask);
2067
43
  return RValue::get(Vec);
2068
254
}
2069
2070
/// Generates lvalue for partial ext_vector access.
2071
1
Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
2072
1
  Address VectorAddress = LV.getExtVectorAddress();
2073
1
  QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2074
1
  llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2075
2076
1
  Address CastToPointerElement =
2077
1
    Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
2078
1
                                 "conv.ptr.element");
2079
2080
1
  const llvm::Constant *Elts = LV.getExtVectorElts();
2081
1
  unsigned ix = getAccessedFieldNo(0, Elts);
2082
2083
1
  Address VectorBasePtrPlusIx =
2084
1
    Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2085
1
                                   "vector.elt");
2086
2087
1
  return VectorBasePtrPlusIx;
2088
1
}
2089
2090
/// Load of global gamed gegisters are always calls to intrinsics.
2091
30
RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
2092
30
  assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2093
30
         "Bad type for register variable");
2094
0
  llvm::MDNode *RegName = cast<llvm::MDNode>(
2095
30
      cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2096
2097
  // We accept integer and pointer types only
2098
30
  llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2099
30
  llvm::Type *Ty = OrigTy;
2100
30
  if (OrigTy->isPointerTy())
2101
3
    Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2102
30
  llvm::Type *Types[] = { Ty };
2103
2104
30
  llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2105
30
  llvm::Value *Call = Builder.CreateCall(
2106
30
      F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2107
30
  if (OrigTy->isPointerTy())
2108
3
    Call = Builder.CreateIntToPtr(Call, OrigTy);
2109
30
  return RValue::get(Call);
2110
30
}
2111
2112
/// EmitStoreThroughLValue - Store the specified rvalue into the specified
2113
/// lvalue, where both are guaranteed to the have the same type, and that type
2114
/// is 'Ty'.
2115
void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2116
457k
                                             bool isInit) {
2117
457k
  if (!Dst.isSimple()) {
2118
868
    if (Dst.isVectorElt()) {
2119
      // Read/modify/write the vector, inserting the new element.
2120
168
      llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2121
168
                                            Dst.isVolatileQualified());
2122
168
      auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2123
168
      if (IRStoreTy) {
2124
0
        auto *IRVecTy = llvm::FixedVectorType::get(
2125
0
            Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2126
0
        Vec = Builder.CreateBitCast(Vec, IRVecTy);
2127
        // iN --> <N x i1>.
2128
0
      }
2129
168
      Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2130
168
                                        Dst.getVectorIdx(), "vecins");
2131
168
      if (IRStoreTy) {
2132
        // <N x i1> --> <iN>.
2133
0
        Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2134
0
      }
2135
168
      Builder.CreateStore(Vec, Dst.getVectorAddress(),
2136
168
                          Dst.isVolatileQualified());
2137
168
      return;
2138
168
    }
2139
2140
    // If this is an update of extended vector elements, insert them as
2141
    // appropriate.
2142
700
    if (Dst.isExtVectorElt())
2143
33
      return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2144
2145
667
    if (Dst.isGlobalReg())
2146
26
      return EmitStoreThroughGlobalRegLValue(Src, Dst);
2147
2148
641
    if (Dst.isMatrixElt()) {
2149
34
      llvm::Value *Idx = Dst.getMatrixIdx();
2150
34
      if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2151
17
        const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2152
17
        llvm::MatrixBuilder MB(Builder);
2153
17
        MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2154
17
      }
2155
34
      llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2156
34
      llvm::Value *Vec =
2157
34
          Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
2158
34
      Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2159
34
                          Dst.isVolatileQualified());
2160
34
      return;
2161
34
    }
2162
2163
607
    assert(Dst.isBitField() && "Unknown LValue type");
2164
0
    return EmitStoreThroughBitfieldLValue(Src, Dst);
2165
641
  }
2166
2167
  // There's special magic for assigning into an ARC-qualified l-value.
2168
457k
  if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2169
79
    switch (Lifetime) {
2170
0
    case Qualifiers::OCL_None:
2171
0
      llvm_unreachable("present but none");
2172
2173
49
    case Qualifiers::OCL_ExplicitNone:
2174
      // nothing special
2175
49
      break;
2176
2177
19
    case Qualifiers::OCL_Strong:
2178
19
      if (isInit) {
2179
3
        Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2180
3
        break;
2181
3
      }
2182
16
      EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2183
16
      return;
2184
2185
11
    case Qualifiers::OCL_Weak:
2186
11
      if (isInit)
2187
        // Initialize and then skip the primitive store.
2188
3
        EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
2189
8
      else
2190
8
        EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2191
8
                         /*ignore*/ true);
2192
11
      return;
2193
2194
0
    case Qualifiers::OCL_Autoreleasing:
2195
0
      Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2196
0
                                                     Src.getScalarVal()));
2197
      // fall into the normal path
2198
0
      break;
2199
79
    }
2200
79
  }
2201
2202
456k
  if (Dst.isObjCWeak() && 
!Dst.isNonGC()32
) {
2203
    // load of a __weak object.
2204
26
    Address LvalueDst = Dst.getAddress(*this);
2205
26
    llvm::Value *src = Src.getScalarVal();
2206
26
     CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2207
26
    return;
2208
26
  }
2209
2210
456k
  if (Dst.isObjCStrong() && 
!Dst.isNonGC()248
) {
2211
    // load of a __strong object.
2212
216
    Address LvalueDst = Dst.getAddress(*this);
2213
216
    llvm::Value *src = Src.getScalarVal();
2214
216
    if (Dst.isObjCIvar()) {
2215
54
      assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2216
0
      llvm::Type *ResultType = IntPtrTy;
2217
54
      Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2218
54
      llvm::Value *RHS = dst.getPointer();
2219
54
      RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2220
54
      llvm::Value *LHS =
2221
54
        Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2222
54
                               "sub.ptr.lhs.cast");
2223
54
      llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2224
54
      CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
2225
54
                                              BytesBetween);
2226
162
    } else if (Dst.isGlobalObjCRef()) {
2227
81
      CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2228
81
                                                Dst.isThreadLocalRef());
2229
81
    }
2230
81
    else
2231
81
      CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2232
0
    return;
2233
216
  }
2234
2235
456k
  assert(Src.isScalar() && "Can't emit an agg store with this method");
2236
0
  EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2237
456k
}
2238
2239
void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2240
1.32k
                                                     llvm::Value **Result) {
2241
1.32k
  const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2242
1.32k
  llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
2243
1.32k
  Address Ptr = Dst.getBitFieldAddress();
2244
2245
  // Get the source value, truncated to the width of the bit-field.
2246
1.32k
  llvm::Value *SrcVal = Src.getScalarVal();
2247
2248
  // Cast the source to the storage type and shift it into place.
2249
1.32k
  SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2250
1.32k
                                 /*isSigned=*/false);
2251
1.32k
  llvm::Value *MaskedVal = SrcVal;
2252
2253
1.32k
  const bool UseVolatile =
2254
1.32k
      CGM.getCodeGenOpts().AAPCSBitfieldWidth && 
Dst.isVolatileQualified()1.18k
&&
2255
1.32k
      
Info.VolatileStorageSize != 0109
&&
isAAPCS(CGM.getTarget())57
;
2256
1.32k
  const unsigned StorageSize =
2257
1.32k
      UseVolatile ? 
Info.VolatileStorageSize57
:
Info.StorageSize1.27k
;
2258
1.32k
  const unsigned Offset = UseVolatile ? 
Info.VolatileOffset57
:
Info.Offset1.27k
;
2259
  // See if there are other bits in the bitfield's storage we'll need to load
2260
  // and mask together with source before storing.
2261
1.32k
  if (StorageSize != Info.Size) {
2262
1.19k
    assert(StorageSize > Info.Size && "Invalid bitfield size.");
2263
0
    llvm::Value *Val =
2264
1.19k
        Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2265
2266
    // Mask the source value as needed.
2267
1.19k
    if (!hasBooleanRepresentation(Dst.getType()))
2268
1.17k
      SrcVal = Builder.CreateAnd(
2269
1.17k
          SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2270
1.17k
          "bf.value");
2271
1.19k
    MaskedVal = SrcVal;
2272
1.19k
    if (Offset)
2273
670
      SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2274
2275
    // Mask out the original value.
2276
1.19k
    Val = Builder.CreateAnd(
2277
1.19k
        Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2278
1.19k
        "bf.clear");
2279
2280
    // Or together the unchanged values and the source value.
2281
1.19k
    SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2282
1.19k
  } else {
2283
130
    assert(Offset == 0);
2284
    // According to the AACPS:
2285
    // When a volatile bit-field is written, and its container does not overlap
2286
    // with any non-bit-field member, its container must be read exactly once
2287
    // and written exactly once using the access width appropriate to the type
2288
    // of the container. The two accesses are not atomic.
2289
130
    if (Dst.isVolatileQualified() && 
isAAPCS(CGM.getTarget())72
&&
2290
130
        
CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad72
)
2291
36
      Builder.CreateLoad(Ptr, true, "bf.load");
2292
130
  }
2293
2294
  // Write the new value back out.
2295
0
  Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2296
2297
  // Return the new value of the bit-field, if requested.
2298
1.32k
  if (Result) {
2299
720
    llvm::Value *ResultVal = MaskedVal;
2300
2301
    // Sign extend the value if needed.
2302
720
    if (Info.IsSigned) {
2303
475
      assert(Info.Size <= StorageSize);
2304
0
      unsigned HighBits = StorageSize - Info.Size;
2305
475
      if (HighBits) {
2306
389
        ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2307
389
        ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2308
389
      }
2309
475
    }
2310
2311
0
    ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2312
720
                                      "bf.result.cast");
2313
720
    *Result = EmitFromMemory(ResultVal, Dst.getType());
2314
720
  }
2315
1.32k
}
2316
2317
void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2318
33
                                                               LValue Dst) {
2319
  // This access turns into a read/modify/write of the vector.  Load the input
2320
  // value now.
2321
33
  llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2322
33
                                        Dst.isVolatileQualified());
2323
33
  const llvm::Constant *Elts = Dst.getExtVectorElts();
2324
2325
33
  llvm::Value *SrcVal = Src.getScalarVal();
2326
2327
33
  if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2328
8
    unsigned NumSrcElts = VTy->getNumElements();
2329
8
    unsigned NumDstElts =
2330
8
        cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
2331
8
    if (NumDstElts == NumSrcElts) {
2332
      // Use shuffle vector is the src and destination are the same number of
2333
      // elements and restore the vector mask since it is on the side it will be
2334
      // stored.
2335
2
      SmallVector<int, 4> Mask(NumDstElts);
2336
6
      for (unsigned i = 0; i != NumSrcElts; 
++i4
)
2337
4
        Mask[getAccessedFieldNo(i, Elts)] = i;
2338
2339
2
      Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2340
6
    } else if (NumDstElts > NumSrcElts) {
2341
      // Extended the source vector to the same length and then shuffle it
2342
      // into the destination.
2343
      // FIXME: since we're shuffling with undef, can we just use the indices
2344
      //        into that?  This could be simpler.
2345
6
      SmallVector<int, 4> ExtMask;
2346
32
      for (unsigned i = 0; i != NumSrcElts; 
++i26
)
2347
26
        ExtMask.push_back(i);
2348
6
      ExtMask.resize(NumDstElts, -1);
2349
6
      llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2350
      // build identity
2351
6
      SmallVector<int, 4> Mask;
2352
52
      for (unsigned i = 0; i != NumDstElts; 
++i46
)
2353
46
        Mask.push_back(i);
2354
2355
      // When the vector size is odd and .odd or .hi is used, the last element
2356
      // of the Elts constant array will be one past the size of the vector.
2357
      // Ignore the last element here, if it is greater than the mask size.
2358
6
      if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2359
2
        NumSrcElts--;
2360
2361
      // modify when what gets shuffled in
2362
30
      for (unsigned i = 0; i != NumSrcElts; 
++i24
)
2363
24
        Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2364
6
      Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2365
6
    } else {
2366
      // We should never shorten the vector
2367
0
      llvm_unreachable("unexpected shorten vector length");
2368
0
    }
2369
25
  } else {
2370
    // If the Src is a scalar (not a vector) it must be updating one element.
2371
25
    unsigned InIdx = getAccessedFieldNo(0, Elts);
2372
25
    llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2373
25
    Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2374
25
  }
2375
2376
33
  Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2377
33
                      Dst.isVolatileQualified());
2378
33
}
2379
2380
/// Store of global named registers are always calls to intrinsics.
2381
26
void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2382
26
  assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2383
26
         "Bad type for register variable");
2384
0
  llvm::MDNode *RegName = cast<llvm::MDNode>(
2385
26
      cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2386
26
  assert(RegName && "Register LValue is not metadata");
2387
2388
  // We accept integer and pointer types only
2389
0
  llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2390
26
  llvm::Type *Ty = OrigTy;
2391
26
  if (OrigTy->isPointerTy())
2392
3
    Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2393
26
  llvm::Type *Types[] = { Ty };
2394
2395
26
  llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2396
26
  llvm::Value *Value = Src.getScalarVal();
2397
26
  if (OrigTy->isPointerTy())
2398
3
    Value = Builder.CreatePtrToInt(Value, Ty);
2399
26
  Builder.CreateCall(
2400
26
      F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2401
26
}
2402
2403
// setObjCGCLValueClass - sets class of the lvalue for the purpose of
2404
// generating write-barries API. It is currently a global, ivar,
2405
// or neither.
2406
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2407
                                 LValue &LV,
2408
1.49M
                                 bool IsMemberAccess=false) {
2409
1.49M
  if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2410
1.49M
    return;
2411
2412
1.71k
  if (isa<ObjCIvarRefExpr>(E)) {
2413
252
    QualType ExpTy = E->getType();
2414
252
    if (IsMemberAccess && 
ExpTy->isPointerType()62
) {
2415
      // If ivar is a structure pointer, assigning to field of
2416
      // this struct follows gcc's behavior and makes it a non-ivar
2417
      // writer-barrier conservatively.
2418
14
      ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2419
14
      if (ExpTy->isRecordType()) {
2420
6
        LV.setObjCIvar(false);
2421
6
        return;
2422
6
      }
2423
14
    }
2424
246
    LV.setObjCIvar(true);
2425
246
    auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2426
246
    LV.setBaseIvarExp(Exp->getBase());
2427
246
    LV.setObjCArray(E->getType()->isArrayType());
2428
246
    return;
2429
252
  }
2430
2431
1.46k
  if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2432
892
    if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2433
892
      if (VD->hasGlobalStorage()) {
2434
284
        LV.setGlobalObjCRef(true);
2435
284
        LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2436
284
      }
2437
892
    }
2438
892
    LV.setObjCArray(E->getType()->isArrayType());
2439
892
    return;
2440
892
  }
2441
2442
573
  if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2443
20
    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2444
20
    return;
2445
20
  }
2446
2447
553
  if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2448
26
    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2449
26
    if (LV.isObjCIvar()) {
2450
      // If cast is to a structure pointer, follow gcc's behavior and make it
2451
      // a non-ivar write-barrier.
2452
12
      QualType ExpTy = E->getType();
2453
12
      if (ExpTy->isPointerType())
2454
10
        ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2455
12
      if (ExpTy->isRecordType())
2456
8
        LV.setObjCIvar(false);
2457
12
    }
2458
26
    return;
2459
26
  }
2460
2461
527
  if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2462
0
    setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2463
0
    return;
2464
0
  }
2465
2466
527
  if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2467
173
    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2468
173
    return;
2469
173
  }
2470
2471
354
  if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2472
14
    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2473
14
    return;
2474
14
  }
2475
2476
340
  if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2477
0
    setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2478
0
    return;
2479
0
  }
2480
2481
340
  if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2482
139
    setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2483
139
    if (LV.isObjCIvar() && 
!LV.isObjCArray()72
)
2484
      // Using array syntax to assigning to what an ivar points to is not
2485
      // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2486
38
      LV.setObjCIvar(false);
2487
101
    else if (LV.isGlobalObjCRef() && 
!LV.isObjCArray()50
)
2488
      // Using array syntax to assigning to what global points to is not
2489
      // same as assigning to the global itself. {id *G;} G[i] = 0;
2490
4
      LV.setGlobalObjCRef(false);
2491
139
    return;
2492
139
  }
2493
2494
201
  if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2495
188
    setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2496
    // We don't know if member is an 'ivar', but this flag is looked at
2497
    // only in the context of LV.isObjCIvar().
2498
188
    LV.setObjCArray(E->getType()->isArrayType());
2499
188
    return;
2500
188
  }
2501
201
}
2502
2503
static llvm::Value *
2504
EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2505
                                llvm::Value *V, llvm::Type *IRType,
2506
61.1k
                                StringRef Name = StringRef()) {
2507
61.1k
  unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2508
61.1k
  return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2509
61.1k
}
2510
2511
static LValue EmitThreadPrivateVarDeclLValue(
2512
    CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2513
241
    llvm::Type *RealVarTy, SourceLocation Loc) {
2514
241
  if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
2515
0
    Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
2516
0
        CGF, VD, Addr, Loc);
2517
241
  else
2518
241
    Addr =
2519
241
        CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2520
2521
241
  Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2522
241
  return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2523
241
}
2524
2525
static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2526
104
                                           const VarDecl *VD, QualType T) {
2527
104
  llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2528
104
      OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2529
  // Return an invalid address if variable is MT_To and unified
2530
  // memory is not enabled. For all other cases: MT_Link and
2531
  // MT_To with unified memory, return a valid address.
2532
104
  if (!Res || 
(85
*Res == OMPDeclareTargetDeclAttr::MT_To85
&&
2533
85
               
!CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()77
))
2534
94
    return Address::invalid();
2535
10
  assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2536
10
          (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2537
10
           CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2538
10
         "Expected link clause OR to clause with unified memory enabled.");
2539
0
  QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2540
10
  Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2541
10
  return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2542
104
}
2543
2544
Address
2545
CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2546
                                     LValueBaseInfo *PointeeBaseInfo,
2547
80.3k
                                     TBAAAccessInfo *PointeeTBAAInfo) {
2548
80.3k
  llvm::LoadInst *Load =
2549
80.3k
      Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
2550
80.3k
  CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2551
2552
80.3k
  QualType PointeeType = RefLVal.getType()->getPointeeType();
2553
80.3k
  CharUnits Align = CGM.getNaturalTypeAlignment(
2554
80.3k
      PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
2555
80.3k
      /* forPointeeType= */ true);
2556
80.3k
  return Address(Load, ConvertTypeForMem(PointeeType), Align);
2557
80.3k
}
2558
2559
59.5k
LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2560
59.5k
  LValueBaseInfo PointeeBaseInfo;
2561
59.5k
  TBAAAccessInfo PointeeTBAAInfo;
2562
59.5k
  Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2563
59.5k
                                            &PointeeTBAAInfo);
2564
59.5k
  return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2565
59.5k
                        PointeeBaseInfo, PointeeTBAAInfo);
2566
59.5k
}
2567
2568
Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2569
                                           const PointerType *PtrTy,
2570
                                           LValueBaseInfo *BaseInfo,
2571
18.0k
                                           TBAAAccessInfo *TBAAInfo) {
2572
18.0k
  llvm::Value *Addr = Builder.CreateLoad(Ptr);
2573
18.0k
  return Address(Addr, ConvertTypeForMem(PtrTy->getPointeeType()),
2574
18.0k
                 CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), BaseInfo,
2575
18.0k
                                             TBAAInfo,
2576
18.0k
                                             /*forPointeeType=*/true));
2577
18.0k
}
2578
2579
LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2580
16.6k
                                                const PointerType *PtrTy) {
2581
16.6k
  LValueBaseInfo BaseInfo;
2582
16.6k
  TBAAAccessInfo TBAAInfo;
2583
16.6k
  Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2584
16.6k
  return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2585
16.6k
}
2586
2587
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2588
61.3k
                                      const Expr *E, const VarDecl *VD) {
2589
61.3k
  QualType T = E->getType();
2590
2591
  // If it's thread_local, emit a call to its wrapper function instead.
2592
61.3k
  if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2593
61.3k
      
CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD)235
)
2594
174
    return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2595
  // Check if the variable is marked as declare target with link clause in
2596
  // device codegen.
2597
61.2k
  if (CGF.getLangOpts().OpenMPIsDevice) {
2598
104
    Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2599
104
    if (Addr.isValid())
2600
10
      return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2601
104
  }
2602
2603
61.1k
  llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2604
61.1k
  llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2605
61.1k
  V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2606
61.1k
  CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2607
61.1k
  Address Addr(V, RealVarTy, Alignment);
2608
  // Emit reference to the private copy of the variable if it is an OpenMP
2609
  // threadprivate variable.
2610
61.1k
  if (CGF.getLangOpts().OpenMP && 
!CGF.getLangOpts().OpenMPSimd26.7k
&&
2611
61.1k
      
VD->hasAttr<OMPThreadPrivateDeclAttr>()12.2k
) {
2612
131
    return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2613
131
                                          E->getExprLoc());
2614
131
  }
2615
61.0k
  LValue LV = VD->getType()->isReferenceType() ?
2616
8.45k
      CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2617
8.45k
                                    AlignmentSource::Decl) :
2618
61.0k
      
CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl)52.6k
;
2619
61.0k
  setObjCGCLValueClass(CGF.getContext(), E, LV);
2620
61.0k
  return LV;
2621
61.1k
}
2622
2623
static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2624
170k
                                               GlobalDecl GD) {
2625
170k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2626
170k
  if (FD->hasAttr<WeakRefAttr>()) {
2627
11
    ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2628
11
    return aliasee.getPointer();
2629
11
  }
2630
2631
170k
  llvm::Constant *V = CGM.GetAddrOfFunction(GD);
2632
170k
  if (!FD->hasPrototype()) {
2633
536
    if (const FunctionProtoType *Proto =
2634
536
            FD->getType()->getAs<FunctionProtoType>()) {
2635
      // Ugly case: for a K&R-style definition, the type of the definition
2636
      // isn't the same as the type of a use.  Correct for this with a
2637
      // bitcast.
2638
13
      QualType NoProtoType =
2639
13
          CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2640
13
      NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2641
13
      V = llvm::ConstantExpr::getBitCast(V,
2642
13
                                      CGM.getTypes().ConvertType(NoProtoType));
2643
13
    }
2644
536
  }
2645
170k
  return V;
2646
170k
}
2647
2648
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
2649
16.5k
                                     GlobalDecl GD) {
2650
16.5k
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2651
16.5k
  llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
2652
16.5k
  CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2653
16.5k
  return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2654
16.5k
                            AlignmentSource::Decl);
2655
16.5k
}
2656
2657
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2658
4.98k
                                      llvm::Value *ThisValue) {
2659
4.98k
  QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2660
4.98k
  LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2661
4.98k
  return CGF.EmitLValueForField(LV, FD);
2662
4.98k
}
2663
2664
/// Named Registers are named metadata pointing to the register name
2665
/// which will be read from/written to as an argument to the intrinsic
2666
/// @llvm.read/write_register.
2667
/// So far, only the name is being passed down, but other options such as
2668
/// register type, allocation type or even optimization options could be
2669
/// passed down via the metadata node.
2670
50
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2671
50
  SmallString<64> Name("llvm.named.register.");
2672
50
  AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2673
50
  assert(Asm->getLabel().size() < 64-Name.size() &&
2674
50
      "Register name too big");
2675
0
  Name.append(Asm->getLabel());
2676
50
  llvm::NamedMDNode *M =
2677
50
    CGM.getModule().getOrInsertNamedMetadata(Name);
2678
50
  if (M->getNumOperands() == 0) {
2679
23
    llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2680
23
                                              Asm->getLabel());
2681
23
    llvm::Metadata *Ops[] = {Str};
2682
23
    M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2683
23
  }
2684
2685
50
  CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2686
2687
50
  llvm::Value *Ptr =
2688
50
    llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2689
50
  return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
2690
50
}
2691
2692
/// Determine whether we can emit a reference to \p VD from the current
2693
/// context, despite not necessarily having seen an odr-use of the variable in
2694
/// this context.
2695
static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2696
                                               const DeclRefExpr *E,
2697
                                               const VarDecl *VD,
2698
20
                                               bool IsConstant) {
2699
  // For a variable declared in an enclosing scope, do not emit a spurious
2700
  // reference even if we have a capture, as that will emit an unwarranted
2701
  // reference to our capture state, and will likely generate worse code than
2702
  // emitting a local copy.
2703
20
  if (E->refersToEnclosingVariableOrCapture())
2704
0
    return false;
2705
2706
  // For a local declaration declared in this function, we can always reference
2707
  // it even if we don't have an odr-use.
2708
20
  if (VD->hasLocalStorage()) {
2709
8
    return VD->getDeclContext() ==
2710
8
           dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2711
8
  }
2712
2713
  // For a global declaration, we can emit a reference to it if we know
2714
  // for sure that we are able to emit a definition of it.
2715
12
  VD = VD->getDefinition(CGF.getContext());
2716
12
  if (!VD)
2717
1
    return false;
2718
2719
  // Don't emit a spurious reference if it might be to a variable that only
2720
  // exists on a different device / target.
2721
  // FIXME: This is unnecessarily broad. Check whether this would actually be a
2722
  // cross-target reference.
2723
11
  if (CGF.getLangOpts().OpenMP || 
CGF.getLangOpts().CUDA8
||
2724
11
      
CGF.getLangOpts().OpenCL2
) {
2725
9
    return false;
2726
9
  }
2727
2728
  // We can emit a spurious reference only if the linkage implies that we'll
2729
  // be emitting a non-interposable symbol that will be retained until link
2730
  // time.
2731
2
  switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
2732
0
  case llvm::GlobalValue::ExternalLinkage:
2733
1
  case llvm::GlobalValue::LinkOnceODRLinkage:
2734
1
  case llvm::GlobalValue::WeakODRLinkage:
2735
2
  case llvm::GlobalValue::InternalLinkage:
2736
2
  case llvm::GlobalValue::PrivateLinkage:
2737
2
    return true;
2738
0
  default:
2739
0
    return false;
2740
2
  }
2741
2
}
2742
2743
1.42M
LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2744
1.42M
  const NamedDecl *ND = E->getDecl();
2745
1.42M
  QualType T = E->getType();
2746
2747
1.42M
  assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2748
1.42M
         "should not emit an unevaluated operand");
2749
2750
1.42M
  if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2751
    // Global Named registers access via intrinsics only
2752
1.40M
    if (VD->getStorageClass() == SC_Register &&
2753
1.40M
        
VD->hasAttr<AsmLabelAttr>()714
&&
!VD->isLocalVarDecl()137
)
2754
50
      return EmitGlobalNamedRegister(VD, CGM);
2755
2756
    // If this DeclRefExpr does not constitute an odr-use of the variable,
2757
    // we're not permitted to emit a reference to it in general, and it might
2758
    // not be captured if capture would be necessary for a use. Emit the
2759
    // constant value directly instead.
2760
1.40M
    if (E->isNonOdrUse() == NOUR_Constant &&
2761
1.40M
        
(111
VD->getType()->isReferenceType()111
||
2762
111
         
!canEmitSpuriousReferenceToVariable(*this, E, VD, true)20
)) {
2763
107
      VD->getAnyInitializer(VD);
2764
107
      llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2765
107
          E->getLocation(), *VD->evaluateValue(), VD->getType());
2766
107
      assert(Val && "failed to emit constant expression");
2767
2768
0
      Address Addr = Address::invalid();
2769
107
      if (!VD->getType()->isReferenceType()) {
2770
        // Spill the constant value to a global.
2771
16
        Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2772
16
                                           getContext().getDeclAlign(VD));
2773
16
        llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2774
16
        auto *PTy = llvm::PointerType::get(
2775
16
            VarTy, getContext().getTargetAddressSpace(VD->getType()));
2776
16
        Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
2777
91
      } else {
2778
        // Should we be using the alignment of the constant pointer we emitted?
2779
91
        CharUnits Alignment =
2780
91
            CGM.getNaturalTypeAlignment(E->getType(),
2781
91
                                        /* BaseInfo= */ nullptr,
2782
91
                                        /* TBAAInfo= */ nullptr,
2783
91
                                        /* forPointeeType= */ true);
2784
91
        Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
2785
91
      }
2786
107
      return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2787
107
    }
2788
2789
    // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2790
2791
    // Check for captured variables.
2792
1.40M
    if (E->refersToEnclosingVariableOrCapture()) {
2793
106k
      VD = VD->getCanonicalDecl();
2794
106k
      if (auto *FD = LambdaCaptureFields.lookup(VD))
2795
3.91k
        return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2796
102k
      if (CapturedStmtInfo) {
2797
97.4k
        auto I = LocalDeclMap.find(VD);
2798
97.4k
        if (I != LocalDeclMap.end()) {
2799
96.4k
          LValue CapLVal;
2800
96.4k
          if (VD->getType()->isReferenceType())
2801
4.17k
            CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2802
4.17k
                                                AlignmentSource::Decl);
2803
92.2k
          else
2804
92.2k
            CapLVal = MakeAddrLValue(I->second, T);
2805
          // Mark lvalue as nontemporal if the variable is marked as nontemporal
2806
          // in simd context.
2807
96.4k
          if (getLangOpts().OpenMP &&
2808
96.4k
              CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2809
182
            CapLVal.setNontemporal(/*Value=*/true);
2810
96.4k
          return CapLVal;
2811
96.4k
        }
2812
1.06k
        LValue CapLVal =
2813
1.06k
            EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2814
1.06k
                                    CapturedStmtInfo->getContextValue());
2815
1.06k
        Address LValueAddress = CapLVal.getAddress(*this);
2816
1.06k
        CapLVal = MakeAddrLValue(
2817
1.06k
            Address(LValueAddress.getPointer(), LValueAddress.getElementType(),
2818
1.06k
                    getContext().getDeclAlign(VD)),
2819
1.06k
            CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2820
1.06k
            CapLVal.getTBAAInfo());
2821
        // Mark lvalue as nontemporal if the variable is marked as nontemporal
2822
        // in simd context.
2823
1.06k
        if (getLangOpts().OpenMP &&
2824
1.06k
            
CGM.getOpenMPRuntime().isNontemporalDecl(VD)1.01k
)
2825
0
          CapLVal.setNontemporal(/*Value=*/true);
2826
1.06k
        return CapLVal;
2827
97.4k
      }
2828
2829
5.23k
      assert(isa<BlockDecl>(CurCodeDecl));
2830
0
      Address addr = GetAddrOfBlockDecl(VD);
2831
5.23k
      return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2832
102k
    }
2833
1.40M
  }
2834
2835
  // FIXME: We should be able to assert this for FunctionDecls as well!
2836
  // FIXME: We should be able to assert this for all DeclRefExprs, not just
2837
  // those with a valid source location.
2838
1.31M
  assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
2839
1.31M
          !E->getLocation().isValid()) &&
2840
1.31M
         "Should not use decl without marking it used!");
2841
2842
1.31M
  if (ND->hasAttr<WeakRefAttr>()) {
2843
20
    const auto *VD = cast<ValueDecl>(ND);
2844
20
    ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2845
20
    return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2846
20
  }
2847
2848
1.31M
  if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2849
    // Check if this is a global variable.
2850
1.30M
    if (VD->hasLinkage() || 
VD->isStaticDataMember()1.24M
)
2851
61.3k
      return EmitGlobalVarDeclLValue(*this, E, VD);
2852
2853
1.24M
    Address addr = Address::invalid();
2854
2855
    // The variable should generally be present in the local decl map.
2856
1.24M
    auto iter = LocalDeclMap.find(VD);
2857
1.24M
    if (iter != LocalDeclMap.end()) {
2858
1.23M
      addr = iter->second;
2859
2860
    // Otherwise, it might be static local we haven't emitted yet for
2861
    // some reason; most likely, because it's in an outer function.
2862
1.23M
    } else 
if (595
VD->isStaticLocal()595
) {
2863
595
      llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
2864
595
          *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
2865
595
      addr = Address(
2866
595
          var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
2867
2868
    // No other cases for now.
2869
595
    } else {
2870
0
      llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2871
0
    }
2872
2873
2874
    // Check for OpenMP threadprivate variables.
2875
1.24M
    if (getLangOpts().OpenMP && 
!getLangOpts().OpenMPSimd386k
&&
2876
1.24M
        
VD->hasAttr<OMPThreadPrivateDeclAttr>()255k
) {
2877
110
      return EmitThreadPrivateVarDeclLValue(
2878
110
          *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2879
110
          E->getExprLoc());
2880
110
    }
2881
2882
    // Drill into block byref variables.
2883
1.23M
    bool isBlockByref = VD->isEscapingByref();
2884
1.23M
    if (isBlockByref) {
2885
40
      addr = emitBlockByrefAddress(addr, VD);
2886
40
    }
2887
2888
    // Drill into reference types.
2889
1.23M
    LValue LV = VD->getType()->isReferenceType() ?
2890
46.8k
        EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2891
1.23M
        
MakeAddrLValue(addr, T, AlignmentSource::Decl)1.19M
;
2892
2893
1.23M
    bool isLocalStorage = VD->hasLocalStorage();
2894
2895
1.23M
    bool NonGCable = isLocalStorage &&
2896
1.23M
                     
!VD->getType()->isReferenceType()1.23M
&&
2897
1.23M
                     
!isBlockByref1.18M
;
2898
1.23M
    if (NonGCable) {
2899
1.18M
      LV.getQuals().removeObjCGCAttr();
2900
1.18M
      LV.setNonGC(true);
2901
1.18M
    }
2902
2903
1.23M
    bool isImpreciseLifetime =
2904
1.23M
      (isLocalStorage && 
!VD->hasAttr<ObjCPreciseLifetimeAttr>()1.23M
);
2905
1.23M
    if (isImpreciseLifetime)
2906
1.23M
      LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2907
1.23M
    setObjCGCLValueClass(getContext(), E, LV);
2908
1.23M
    return LV;
2909
1.24M
  }
2910
2911
16.6k
  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2912
16.5k
    LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2913
2914
    // Emit debuginfo for the function declaration if the target wants to.
2915
16.5k
    if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2916
3
      if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2917
3
        auto *Fn =
2918
3
            cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2919
3
        if (!Fn->getSubprogram())
2920
2
          DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2921
3
      }
2922
3
    }
2923
2924
16.5k
    return LV;
2925
16.5k
  }
2926
2927
  // FIXME: While we're emitting a binding from an enclosing scope, all other
2928
  // DeclRefExprs we see should be implicitly treated as if they also refer to
2929
  // an enclosing scope.
2930
172
  if (const auto *BD = dyn_cast<BindingDecl>(ND))
2931
165
    return EmitLValue(BD->getBinding());
2932
2933
  // We can form DeclRefExprs naming GUID declarations when reconstituting
2934
  // non-type template parameters into expressions.
2935
7
  if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
2936
5
    return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
2937
5
                          AlignmentSource::Decl);
2938
2939
2
  if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2940
2
    return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2941
2
                          AlignmentSource::Decl);
2942
2943
0
  llvm_unreachable("Unhandled DeclRefExpr");
2944
0
}
2945
2946
71.3k
LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2947
  // __extension__ doesn't affect lvalue-ness.
2948
71.3k
  if (E->getOpcode() == UO_Extension)
2949
0
    return EmitLValue(E->getSubExpr());
2950
2951
71.3k
  QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2952
71.3k
  switch (E->getOpcode()) {
2953
0
  default: llvm_unreachable("Unknown unary operator lvalue!");
2954
54.4k
  case UO_Deref: {
2955
54.4k
    QualType T = E->getSubExpr()->getType()->getPointeeType();
2956
54.4k
    assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2957
2958
0
    LValueBaseInfo BaseInfo;
2959
54.4k
    TBAAAccessInfo TBAAInfo;
2960
54.4k
    Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2961
54.4k
                                            &TBAAInfo);
2962
54.4k
    LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2963
54.4k
    LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2964
2965
    // We should not generate __weak write barrier on indirect reference
2966
    // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2967
    // But, we continue to generate __strong write barrier on indirect write
2968
    // into a pointer to object.
2969
54.4k
    if (getLangOpts().ObjC &&
2970
54.4k
        
getLangOpts().getGC() != LangOptions::NonGC24.1k
&&
2971
54.4k
        
LV.isObjCWeak()44
)
2972
10
      LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2973
54.4k
    return LV;
2974
0
  }
2975
69
  case UO_Real:
2976
147
  case UO_Imag: {
2977
147
    LValue LV = EmitLValue(E->getSubExpr());
2978
147
    assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2979
2980
    // __real is valid on scalars.  This is a faster way of testing that.
2981
    // __imag can only produce an rvalue on scalars.
2982
147
    if (E->getOpcode() == UO_Real &&
2983
147
        
!LV.getAddress(*this).getElementType()->isStructTy()69
) {
2984
4
      assert(E->getSubExpr()->getType()->isArithmeticType());
2985
0
      return LV;
2986
4
    }
2987
2988
143
    QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2989
2990
143
    Address Component =
2991
143
        (E->getOpcode() == UO_Real
2992
143
             ? 
emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())65
2993
143
             : 
emitAddrOfImagComponent(LV.getAddress(*this), LV.getType())78
);
2994
143
    LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2995
143
                                   CGM.getTBAAInfoForSubobject(LV, T));
2996
143
    ElemLV.getQuals().addQualifiers(LV.getQuals());
2997
143
    return ElemLV;
2998
147
  }
2999
16.0k
  case UO_PreInc:
3000
16.7k
  case UO_PreDec: {
3001
16.7k
    LValue LV = EmitLValue(E->getSubExpr());
3002
16.7k
    bool isInc = E->getOpcode() == UO_PreInc;
3003
3004
16.7k
    if (E->getType()->isAnyComplexType())
3005
0
      EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3006
16.7k
    else
3007
16.7k
      EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3008
16.7k
    return LV;
3009
16.0k
  }
3010
71.3k
  }
3011
71.3k
}
3012
3013
83.6k
LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
3014
83.6k
  return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
3015
83.6k
                        E->getType(), AlignmentSource::Decl);
3016
83.6k
}
3017
3018
17
LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
3019
17
  return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
3020
17
                        E->getType(), AlignmentSource::Decl);
3021
17
}
3022
3023
563
LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
3024
563
  auto SL = E->getFunctionName();
3025
563
  assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3026
0
  StringRef FnName = CurFn->getName();
3027
563
  if (FnName.startswith("\01"))
3028
84
    FnName = FnName.substr(1);
3029
563
  StringRef NameItems[] = {
3030
563
      PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
3031
563
  std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3032
563
  if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3033
28
    std::string Name = std::string(SL->getString());
3034
28
    if (!Name.empty()) {
3035
26
      unsigned Discriminator =
3036
26
          CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3037
26
      if (Discriminator)
3038
13
        Name += "_" + Twine(Discriminator + 1).str();
3039
26
      auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
3040
26
      return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3041
26
    } else {
3042
2
      auto C =
3043
2
          CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
3044
2
      return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3045
2
    }
3046
28
  }
3047
535
  auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3048
535
  return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3049
563
}
3050
3051
/// Emit a type description suitable for use by a runtime sanitizer library. The
3052
/// format of a type descriptor is
3053
///
3054
/// \code
3055
///   { i16 TypeKind, i16 TypeInfo }
3056
/// \endcode
3057
///
3058
/// followed by an array of i8 containing the type name. TypeKind is 0 for an
3059
/// integer, 1 for a floating point value, and -1 for anything else.
3060
2.68k
llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
3061
  // Only emit each type's descriptor once.
3062
2.68k
  if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3063
2.13k
    return C;
3064
3065
545
  uint16_t TypeKind = -1;
3066
545
  uint16_t TypeInfo = 0;
3067
3068
545
  if (T->isIntegerType()) {
3069
268
    TypeKind = 0;
3070
268
    TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3071
268
               (T->isSignedIntegerType() ? 
1138
:
0130
);
3072
277
  } else if (T->isFloatingType()) {
3073
10
    TypeKind = 1;
3074
10
    TypeInfo = getContext().getTypeSize(T);
3075
10
  }
3076
3077
  // Format the type name as if for a diagnostic, including quotes and
3078
  // optionally an 'aka'.
3079
545
  SmallString<32> Buffer;
3080
545
  CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
3081
545
                                    (intptr_t)T.getAsOpaquePtr(),
3082
545
                                    StringRef(), StringRef(), None, Buffer,
3083
545
                                    None);
3084
3085
545
  llvm::Constant *Components[] = {
3086
545
    Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3087
545
    llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3088
545
  };
3089
545
  llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3090
3091
545
  auto *GV = new llvm::GlobalVariable(
3092
545
      CGM.getModule(), Descriptor->getType(),
3093
545
      /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3094
545
  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3095
545
  CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3096
3097
  // Remember the descriptor for this type.
3098
545
  CGM.setTypeDescriptorInMap(T, GV);
3099
3100
545
  return GV;
3101
2.68k
}
3102
3103
2.68k
llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3104
2.68k
  llvm::Type *TargetTy = IntPtrTy;
3105
3106
2.68k
  if (V->getType() == TargetTy)
3107
643
    return V;
3108
3109
  // Floating-point types which fit into intptr_t are bitcast to integers
3110
  // and then passed directly (after zero-extension, if necessary).
3111
2.03k
  if (V->getType()->isFloatingPointTy()) {
3112
12
    unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedSize();
3113
12
    if (Bits <= TargetTy->getIntegerBitWidth())
3114
11
      V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3115
11
                                                         Bits));
3116
12
  }
3117
3118
  // Integers which fit in intptr_t are zero-extended and passed directly.
3119
2.03k
  if (V->getType()->isIntegerTy() &&
3120
2.03k
      
V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth()1.66k
)
3121
1.65k
    return Builder.CreateZExt(V, TargetTy);
3122
3123
  // Pointers are passed directly, everything else is passed by address.
3124
379
  if (!V->getType()->isPointerTy()) {
3125
3
    Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
3126
3
    Builder.CreateStore(V, Ptr);
3127
3
    V = Ptr.getPointer();
3128
3
  }
3129
379
  return Builder.CreatePtrToInt(V, TargetTy);
3130
2.03k
}
3131
3132
/// Emit a representation of a SourceLocation for passing to a handler
3133
/// in a sanitizer runtime library. The format for this data is:
3134
/// \code
3135
///   struct SourceLocation {
3136
///     const char *Filename;
3137
///     int32_t Line, Column;
3138
///   };
3139
/// \endcode
3140
/// For an invalid SourceLocation, the Filename pointer is null.
3141
2.00k
llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3142
2.00k
  llvm::Constant *Filename;
3143
2.00k
  int Line, Column;
3144
3145
2.00k
  PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3146
2.00k
  if (PLoc.isValid()) {
3147
1.98k
    StringRef FilenameString = PLoc.getFilename();
3148
3149
1.98k
    int PathComponentsToStrip =
3150
1.98k
        CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3151
1.98k
    if (PathComponentsToStrip < 0) {
3152
3
      assert(PathComponentsToStrip != INT_MIN);
3153
0
      int PathComponentsToKeep = -PathComponentsToStrip;
3154
3
      auto I = llvm::sys::path::rbegin(FilenameString);
3155
3
      auto E = llvm::sys::path::rend(FilenameString);
3156
15
      while (I != E && 
--PathComponentsToKeep14
)
3157
12
        ++I;
3158
3159
3
      FilenameString = FilenameString.substr(I - E);
3160
1.98k
    } else if (PathComponentsToStrip > 0) {
3161
2
      auto I = llvm::sys::path::begin(FilenameString);
3162
2
      auto E = llvm::sys::path::end(FilenameString);
3163
15
      while (I != E && 
PathComponentsToStrip--14
)
3164
13
        ++I;
3165
3166
2
      if (I != E)
3167
1
        FilenameString =
3168
1
            FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3169
1
      else
3170
1
        FilenameString = llvm::sys::path::filename(FilenameString);
3171
2
    }
3172
3173
0
    auto FilenameGV =
3174
1.98k
        CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3175
1.98k
    CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3176
1.98k
                          cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
3177
1.98k
    Filename = FilenameGV.getPointer();
3178
1.98k
    Line = PLoc.getLine();
3179
1.98k
    Column = PLoc.getColumn();
3180
1.98k
  } else {
3181
24
    Filename = llvm::Constant::getNullValue(Int8PtrTy);
3182
24
    Line = Column = 0;
3183
24
  }
3184
3185
0
  llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3186
2.00k
                            Builder.getInt32(Column)};
3187
3188
2.00k
  return llvm::ConstantStruct::getAnon(Data);
3189
2.00k
}
3190
3191
namespace {
3192
/// Specify under what conditions this check can be recovered
3193
enum class CheckRecoverableKind {
3194
  /// Always terminate program execution if this check fails.
3195
  Unrecoverable,
3196
  /// Check supports recovering, runtime has both fatal (noreturn) and
3197
  /// non-fatal handlers for this check.
3198
  Recoverable,
3199
  /// Runtime conditionally aborts, always need to support recovery.
3200
  AlwaysRecoverable
3201
};
3202
}
3203
3204
1.79k
static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3205
1.79k
  assert(Kind.countPopulation() == 1);
3206
1.79k
  if (Kind == SanitizerKind::Function || 
Kind == SanitizerKind::Vptr1.78k
)
3207
57
    return CheckRecoverableKind::AlwaysRecoverable;
3208
1.73k
  else if (Kind == SanitizerKind::Return || 
Kind == SanitizerKind::Unreachable1.73k
)
3209
19
    return CheckRecoverableKind::Unrecoverable;
3210
1.72k
  else
3211
1.72k
    return CheckRecoverableKind::Recoverable;
3212
1.79k
}
3213
3214
namespace {
3215
struct SanitizerHandlerInfo {
3216
  char const *const Name;
3217
  unsigned Version;
3218
};
3219
}
3220
3221
const SanitizerHandlerInfo SanitizerHandlers[] = {
3222
#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3223
    LIST_SANITIZER_CHECKS
3224
#undef SANITIZER_CHECK
3225
};
3226
3227
static void emitCheckHandlerCall(CodeGenFunction &CGF,
3228
                                 llvm::FunctionType *FnType,
3229
                                 ArrayRef<llvm::Value *> FnArgs,
3230
                                 SanitizerHandler CheckHandler,
3231
                                 CheckRecoverableKind RecoverKind, bool IsFatal,
3232
1.53k
                                 llvm::BasicBlock *ContBB) {
3233
1.53k
  assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3234
0
  Optional<ApplyDebugLocation> DL;
3235
1.53k
  if (!CGF.Builder.getCurrentDebugLocation()) {
3236
    // Ensure that the call has at least an artificial debug location.
3237
1.52k
    DL.emplace(CGF, SourceLocation());
3238
1.52k
  }
3239
1.53k
  bool NeedsAbortSuffix =
3240
1.53k
      IsFatal && 
RecoverKind != CheckRecoverableKind::Unrecoverable831
;
3241
1.53k
  bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3242
1.53k
  const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3243
1.53k
  const StringRef CheckName = CheckInfo.Name;
3244
1.53k
  std::string FnName = "__ubsan_handle_" + CheckName.str();
3245
1.53k
  if (CheckInfo.Version && 
!MinimalRuntime373
)
3246
373
    FnName += "_v" + llvm::utostr(CheckInfo.Version);
3247
1.53k
  if (MinimalRuntime)
3248
3
    FnName += "_minimal";
3249
1.53k
  if (NeedsAbortSuffix)
3250
812
    FnName += "_abort";
3251
1.53k
  bool MayReturn =
3252
1.53k
      !IsFatal || 
RecoverKind == CheckRecoverableKind::AlwaysRecoverable831
;
3253
3254
1.53k
  llvm::AttrBuilder B(CGF.getLLVMContext());
3255
1.53k
  if (!MayReturn) {
3256
807
    B.addAttribute(llvm::Attribute::NoReturn)
3257
807
        .addAttribute(llvm::Attribute::NoUnwind);
3258
807
  }
3259
1.53k
  B.addUWTableAttr(llvm::UWTableKind::Default);
3260
3261
1.53k
  llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3262
1.53k
      FnType, FnName,
3263
1.53k
      llvm::AttributeList::get(CGF.getLLVMContext(),
3264
1.53k
                               llvm::AttributeList::FunctionIndex, B),
3265
1.53k
      /*Local=*/true);
3266
1.53k
  llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3267
1.53k
  if (!MayReturn) {
3268
807
    HandlerCall->setDoesNotReturn();
3269
807
    CGF.Builder.CreateUnreachable();
3270
807
  } else {
3271
726
    CGF.Builder.CreateBr(ContBB);
3272
726
  }
3273
1.53k
}
3274
3275
void CodeGenFunction::EmitCheck(
3276
    ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3277
    SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3278
1.91k
    ArrayRef<llvm::Value *> DynamicArgs) {
3279
1.91k
  assert(IsSanitizerScope);
3280
0
  assert(Checked.size() > 0);
3281
0
  assert(CheckHandler >= 0 &&
3282
1.91k
         size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
3283
0
  const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3284
3285
1.91k
  llvm::Value *FatalCond = nullptr;
3286
1.91k
  llvm::Value *RecoverableCond = nullptr;
3287
1.91k
  llvm::Value *TrapCond = nullptr;
3288
4.15k
  for (int i = 0, n = Checked.size(); i < n; 
++i2.23k
) {
3289
2.23k
    llvm::Value *Check = Checked[i].first;
3290
    // -fsanitize-trap= overrides -fsanitize-recover=.
3291
2.23k
    llvm::Value *&Cond =
3292
2.23k
        CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3293
2.23k
            ? 
TrapCond443
3294
2.23k
            : 
CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)1.79k
3295
1.79k
                  ? 
RecoverableCond847
3296
1.79k
                  : 
FatalCond948
;
3297
2.23k
    Cond = Cond ? 
Builder.CreateAnd(Cond, Check)319
:
Check1.91k
;
3298
2.23k
  }
3299
3300
1.91k
  if (TrapCond)
3301
386
    EmitTrapCheck(TrapCond, CheckHandler);
3302
1.91k
  if (!FatalCond && 
!RecoverableCond1.08k
)
3303
385
    return;
3304
3305
1.53k
  llvm::Value *JointCond;
3306
1.53k
  if (FatalCond && 
RecoverableCond831
)
3307
0
    JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3308
1.53k
  else
3309
1.53k
    JointCond = FatalCond ? 
FatalCond831
:
RecoverableCond702
;
3310
1.53k
  assert(JointCond);
3311
3312
0
  CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3313
1.53k
  assert(SanOpts.has(Checked[0].second));
3314
0
#ifndef NDEBUG
3315
1.79k
  for (int i = 1, n = Checked.size(); i < n; 
++i263
) {
3316
263
    assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3317
263
           "All recoverable kinds in a single check must be same!");
3318
0
    assert(SanOpts.has(Checked[i].second));
3319
263
  }
3320
1.53k
#endif
3321
3322
1.53k
  llvm::BasicBlock *Cont = createBasicBlock("cont");
3323
1.53k
  llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3324
1.53k
  llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3325
  // Give hint that we very much don't expect to execute the handler
3326
  // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3327
1.53k
  llvm::MDBuilder MDHelper(getLLVMContext());
3328
1.53k
  llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3329
1.53k
  Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3330
1.53k
  EmitBlock(Handlers);
3331
3332
  // Handler functions take an i8* pointing to the (handler-specific) static
3333
  // information block, followed by a sequence of intptr_t arguments
3334
  // representing operand values.
3335
1.53k
  SmallVector<llvm::Value *, 4> Args;
3336
1.53k
  SmallVector<llvm::Type *, 4> ArgTypes;
3337
1.53k
  if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3338
1.53k
    Args.reserve(DynamicArgs.size() + 1);
3339
1.53k
    ArgTypes.reserve(DynamicArgs.size() + 1);
3340
3341
    // Emit handler arguments and create handler function type.
3342
1.53k
    if (!StaticArgs.empty()) {
3343
1.51k
      llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3344
1.51k
      auto *InfoPtr =
3345
1.51k
          new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3346
1.51k
                                   llvm::GlobalVariable::PrivateLinkage, Info);
3347
1.51k
      InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3348
1.51k
      CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3349
1.51k
      Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
3350
1.51k
      ArgTypes.push_back(Int8PtrTy);
3351
1.51k
    }
3352
3353
4.09k
    for (size_t i = 0, n = DynamicArgs.size(); i != n; 
++i2.56k
) {
3354
2.56k
      Args.push_back(EmitCheckValue(DynamicArgs[i]));
3355
2.56k
      ArgTypes.push_back(IntPtrTy);
3356
2.56k
    }
3357
1.53k
  }
3358
3359
1.53k
  llvm::FunctionType *FnType =
3360
1.53k
    llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3361
3362
1.53k
  if (!FatalCond || 
!RecoverableCond831
) {
3363
    // Simple case: we need to generate a single handler call, either
3364
    // fatal, or non-fatal.
3365
1.53k
    emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3366
1.53k
                         (FatalCond != nullptr), Cont);
3367
1.53k
  } else {
3368
    // Emit two handler calls: first one for set of unrecoverable checks,
3369
    // another one for recoverable.
3370
0
    llvm::BasicBlock *NonFatalHandlerBB =
3371
0
        createBasicBlock("non_fatal." + CheckName);
3372
0
    llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3373
0
    Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3374
0
    EmitBlock(FatalHandlerBB);
3375
0
    emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3376
0
                         NonFatalHandlerBB);
3377
0
    EmitBlock(NonFatalHandlerBB);
3378
0
    emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3379
0
                         Cont);
3380
0
  }
3381
3382
1.53k
  EmitBlock(Cont);
3383
1.53k
}
3384
3385
void CodeGenFunction::EmitCfiSlowPathCheck(
3386
    SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3387
7
    llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3388
7
  llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3389
3390
7
  llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3391
7
  llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3392
3393
7
  llvm::MDBuilder MDHelper(getLLVMContext());
3394
7
  llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3395
7
  BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3396
3397
7
  EmitBlock(CheckBB);
3398
3399
7
  bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3400
3401
7
  llvm::CallInst *CheckCall;
3402
7
  llvm::FunctionCallee SlowPathFn;
3403
7
  if (WithDiag) {
3404
4
    llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3405
4
    auto *InfoPtr =
3406
4
        new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3407
4
                                 llvm::GlobalVariable::PrivateLinkage, Info);
3408
4
    InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3409
4
    CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3410
3411
4
    SlowPathFn = CGM.getModule().getOrInsertFunction(
3412
4
        "__cfi_slowpath_diag",
3413
4
        llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3414
4
                                false));
3415
4
    CheckCall = Builder.CreateCall(
3416
4
        SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
3417
4
  } else {
3418
3
    SlowPathFn = CGM.getModule().getOrInsertFunction(
3419
3
        "__cfi_slowpath",
3420
3
        llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3421
3
    CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3422
3
  }
3423
3424
7
  CGM.setDSOLocal(
3425
7
      cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3426
7
  CheckCall->setDoesNotThrow();
3427
3428
7
  EmitBlock(Cont);
3429
7
}
3430
3431
// Emit a stub for __cfi_check function so that the linker knows about this
3432
// symbol in LTO mode.
3433
14
void CodeGenFunction::EmitCfiCheckStub() {
3434
14
  llvm::Module *M = &CGM.getModule();
3435
14
  auto &Ctx = M->getContext();
3436
14
  llvm::Function *F = llvm::Function::Create(
3437
14
      llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3438
14
      llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3439
14
  CGM.setDSOLocal(F);
3440
14
  llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3441
  // FIXME: consider emitting an intrinsic call like
3442
  // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3443
  // which can be lowered in CrossDSOCFI pass to the actual contents of
3444
  // __cfi_check. This would allow inlining of __cfi_check calls.
3445
14
  llvm::CallInst::Create(
3446
14
      llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3447
14
  llvm::ReturnInst::Create(Ctx, nullptr, BB);
3448
14
}
3449
3450
// This function is basically a switch over the CFI failure kind, which is
3451
// extracted from CFICheckFailData (1st function argument). Each case is either
3452
// llvm.trap or a call to one of the two runtime handlers, based on
3453
// -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
3454
// failure kind) traps, but this should really never happen.  CFICheckFailData
3455
// can be nullptr if the calling module has -fsanitize-trap behavior for this
3456
// check kind; in this case __cfi_check_fail traps as well.
3457
14
void CodeGenFunction::EmitCfiCheckFail() {
3458
14
  SanitizerScope SanScope(this);
3459
14
  FunctionArgList Args;
3460
14
  ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3461
14
                            ImplicitParamDecl::Other);
3462
14
  ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3463
14
                            ImplicitParamDecl::Other);
3464
14
  Args.push_back(&ArgData);
3465
14
  Args.push_back(&ArgAddr);
3466
3467
14
  const CGFunctionInfo &FI =
3468
14
    CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3469
3470
14
  llvm::Function *F = llvm::Function::Create(
3471
14
      llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3472
14
      llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3473
3474
14
  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3475
14
  CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
3476
14
  F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3477
3478
14
  StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3479
14
                SourceLocation());
3480
3481
  // This function is not affected by NoSanitizeList. This function does
3482
  // not have a source location, but "src:*" would still apply. Revert any
3483
  // changes to SanOpts made in StartFunction.
3484
14
  SanOpts = CGM.getLangOpts().Sanitize;
3485
3486
14
  llvm::Value *Data =
3487
14
      EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3488
14
                       CGM.getContext().VoidPtrTy, ArgData.getLocation());
3489
14
  llvm::Value *Addr =
3490
14
      EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3491
14
                       CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3492
3493
  // Data == nullptr means the calling module has trap behaviour for this check.
3494
14
  llvm::Value *DataIsNotNullPtr =
3495
14
      Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3496
14
  EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
3497
3498
14
  llvm::StructType *SourceLocationTy =
3499
14
      llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3500
14
  llvm::StructType *CfiCheckFailDataTy =
3501
14
      llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3502
3503
14
  llvm::Value *V = Builder.CreateConstGEP2_32(
3504
14
      CfiCheckFailDataTy,
3505
14
      Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3506
14
      0);
3507
3508
14
  Address CheckKindAddr(V, Int8Ty, getIntAlign());
3509
14
  llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3510
3511
14
  llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3512
14
      CGM.getLLVMContext(),
3513
14
      llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3514
14
  llvm::Value *ValidVtable = Builder.CreateZExt(
3515
14
      Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3516
14
                         {Addr, AllVtables}),
3517
14
      IntPtrTy);
3518
3519
14
  const std::pair<int, SanitizerMask> CheckKinds[] = {
3520
14
      {CFITCK_VCall, SanitizerKind::CFIVCall},
3521
14
      {CFITCK_NVCall, SanitizerKind::CFINVCall},
3522
14
      {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3523
14
      {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3524
14
      {CFITCK_ICall, SanitizerKind::CFIICall}};
3525
3526
14
  SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3527
70
  for (auto CheckKindMaskPair : CheckKinds) {
3528
70
    int Kind = CheckKindMaskPair.first;
3529
70
    SanitizerMask Mask = CheckKindMaskPair.second;
3530
70
    llvm::Value *Cond =
3531
70
        Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3532
70
    if (CGM.getLangOpts().Sanitize.has(Mask))
3533
17
      EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3534
17
                {Data, Addr, ValidVtable});
3535
53
    else
3536
53
      EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
3537
70
  }
3538
3539
14
  FinishFunction();
3540
  // The only reference to this function will be created during LTO link.
3541
  // Make sure it survives until then.
3542
14
  CGM.addUsedGlobal(F);
3543
14
}
3544
3545
2.36k
void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3546
2.36k
  if (SanOpts.has(SanitizerKind::Unreachable)) {
3547
18
    SanitizerScope SanScope(this);
3548
18
    EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3549
18
                             SanitizerKind::Unreachable),
3550
18
              SanitizerHandler::BuiltinUnreachable,
3551
18
              EmitCheckSourceLocation(Loc), None);
3552
18
  }
3553
2.36k
  Builder.CreateUnreachable();
3554
2.36k
}
3555
3556
void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3557
496
                                    SanitizerHandler CheckHandlerID) {
3558
496
  llvm::BasicBlock *Cont = createBasicBlock("cont");
3559
3560
  // If we're optimizing, collapse all calls to trap down to just one per
3561
  // check-type per function to save on code size.
3562
496
  if (TrapBBs.size() <= CheckHandlerID)
3563
427
    TrapBBs.resize(CheckHandlerID + 1);
3564
496
  llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3565
3566
496
  if (!CGM.getCodeGenOpts().OptimizationLevel || 
!TrapBB39
) {
3567
468
    TrapBB = createBasicBlock("trap");
3568
468
    Builder.CreateCondBr(Checked, Cont, TrapBB);
3569
468
    EmitBlock(TrapBB);
3570
3571
468
    llvm::CallInst *TrapCall =
3572
468
        Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3573
468
                           llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3574
3575
468
    if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3576
1
      auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3577
1
                                    CGM.getCodeGenOpts().TrapFuncName);
3578
1
      TrapCall->addFnAttr(A);
3579
1
    }
3580
468
    TrapCall->setDoesNotReturn();
3581
468
    TrapCall->setDoesNotThrow();
3582
468
    Builder.CreateUnreachable();
3583
468
  } else {
3584
28
    auto Call = TrapBB->begin();
3585
28
    assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3586
3587
0
    Call->applyMergedLocation(Call->getDebugLoc(),
3588
28
                              Builder.getCurrentDebugLocation());
3589
28
    Builder.CreateCondBr(Checked, Cont, TrapBB);
3590
28
  }
3591
3592
0
  EmitBlock(Cont);
3593
496
}
3594
3595
255
llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3596
255
  llvm::CallInst *TrapCall =
3597
255
      Builder.CreateCall(CGM.getIntrinsic(IntrID));
3598
3599
255
  if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3600
2
    auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3601
2
                                  CGM.getCodeGenOpts().TrapFuncName);
3602
2
    TrapCall->addFnAttr(A);
3603
2
  }
3604
3605
255
  return TrapCall;
3606
255
}
3607
3608
Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3609
                                                 LValueBaseInfo *BaseInfo,
3610
91.6k
                                                 TBAAAccessInfo *TBAAInfo) {
3611
91.6k
  assert(E->getType()->isArrayType() &&
3612
91.6k
         "Array to pointer decay must have array source type!");
3613
3614
  // Expressions of array type can't be bitfields or vector elements.
3615
0
  LValue LV = EmitLValue(E);
3616
91.6k
  Address Addr = LV.getAddress(*this);
3617
3618
  // If the array type was an incomplete type, we need to make sure
3619
  // the decay ends up being the right type.
3620
91.6k
  llvm::Type *NewTy = ConvertType(E->getType());
3621
91.6k
  Addr = Builder.CreateElementBitCast(Addr, NewTy);
3622
3623
  // Note that VLA pointers are always decayed, so we don't need to do
3624
  // anything here.
3625
91.6k
  if (!E->getType()->isVariableArrayType()) {
3626
87.0k
    assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3627
87.0k
           "Expected pointer to array");
3628
0
    Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3629
87.0k
  }
3630
3631
  // The result of this decay conversion points to an array element within the
3632
  // base lvalue. However, since TBAA currently does not support representing
3633
  // accesses to elements of member arrays, we conservatively represent accesses
3634
  // to the pointee object as if it had no any base lvalue specified.
3635
  // TODO: Support TBAA for member arrays.
3636
0
  QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3637
91.6k
  if (BaseInfo) 
*BaseInfo = LV.getBaseInfo()4.69k
;
3638
91.6k
  if (TBAAInfo) 
*TBAAInfo = CGM.getTBAAAccessInfo(EltType)4.69k
;
3639
3640
91.6k
  return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3641
91.6k
}
3642
3643
/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3644
/// array to pointer, return the array subexpression.
3645
70.6k
static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3646
  // If this isn't just an array->pointer decay, bail out.
3647
70.6k
  const auto *CE = dyn_cast<CastExpr>(E);
3648
70.6k
  if (!CE || 
CE->getCastKind() != CK_ArrayToPointerDecay70.0k
)
3649
48.6k
    return nullptr;
3650
3651
  // If this is a decay from variable width array, bail out.
3652
21.9k
  const Expr *SubExpr = CE->getSubExpr();
3653
21.9k
  if (SubExpr->getType()->isVariableArrayType())
3654
2.76k
    return nullptr;
3655
3656
19.2k
  return SubExpr;
3657
21.9k
}
3658
3659
static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3660
                                          llvm::Type *elemType,
3661
                                          llvm::Value *ptr,
3662
                                          ArrayRef<llvm::Value*> indices,
3663
                                          bool inbounds,
3664
                                          bool signedIndices,
3665
                                          SourceLocation loc,
3666
72.3k
                                    const llvm::Twine &name = "arrayidx") {
3667
72.3k
  if (inbounds) {
3668
72.3k
    return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
3669
72.3k
                                      CodeGenFunction::NotSubtraction, loc,
3670
72.3k
                                      name);
3671
72.3k
  } else {
3672
5
    return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
3673
5
  }
3674
72.3k
}
3675
3676
static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3677
                                      llvm::Value *idx,
3678
72.3k
                                      CharUnits eltSize) {
3679
  // If we have a constant index, we can use the exact offset of the
3680
  // element we're accessing.
3681
72.3k
  if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3682
21.0k
    CharUnits offset = constantIdx->getZExtValue() * eltSize;
3683
21.0k
    return arrayAlign.alignmentAtOffset(offset);
3684
3685
  // Otherwise, use the worst-case alignment for any element.
3686
51.2k
  } else {
3687
51.2k
    return arrayAlign.alignmentOfArrayElement(eltSize);
3688
51.2k
  }
3689
72.3k
}
3690
3691
static QualType getFixedSizeElementType(const ASTContext &ctx,
3692
56
                                        const VariableArrayType *vla) {
3693
56
  QualType eltType;
3694
56
  do {
3695
56
    eltType = vla->getElementType();
3696
56
  } while ((vla = ctx.getAsVariableArrayType(eltType)));
3697
56
  return eltType;
3698
56
}
3699
3700
/// Given an array base, check whether its member access belongs to a record
3701
/// with preserve_access_index attribute or not.
3702
21.0k
static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3703
21.0k
  if (!ArrayBase || 
!CGF.getDebugInfo()19.0k
)
3704
14.1k
    return false;
3705
3706
  // Only support base as either a MemberExpr or DeclRefExpr.
3707
  // DeclRefExpr to cover cases like:
3708
  //    struct s { int a; int b[10]; };
3709
  //    struct s *p;
3710
  //    p[1].a
3711
  // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3712
  // p->b[5] is a MemberExpr example.
3713
6.95k
  const Expr *E = ArrayBase->IgnoreImpCasts();
3714
6.95k
  if (const auto *ME = dyn_cast<MemberExpr>(E))
3715
337
    return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3716
3717
6.62k
  if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3718
6.34k
    const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3719
6.34k
    if (!VarDef)
3720
0
      return false;
3721
3722
6.34k
    const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3723
6.34k
    if (!PtrT)
3724
3.23k
      return false;
3725
3726
3.10k
    const auto *PointeeT = PtrT->getPointeeType()
3727
3.10k
                             ->getUnqualifiedDesugaredType();
3728
3.10k
    if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3729
22
      return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3730
3.08k
    return false;
3731
3.10k
  }
3732
3733
282
  return false;
3734
6.62k
}
3735
3736
static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3737
                                     ArrayRef<llvm::Value *> indices,
3738
                                     QualType eltType, bool inbounds,
3739
                                     bool signedIndices, SourceLocation loc,
3740
                                     QualType *arrayType = nullptr,
3741
                                     const Expr *Base = nullptr,
3742
72.3k
                                     const llvm::Twine &name = "arrayidx") {
3743
  // All the indices except that last must be zero.
3744
72.3k
#ifndef NDEBUG
3745
72.3k
  for (auto idx : indices.drop_back())
3746
19.2k
    assert(isa<llvm::ConstantInt>(idx) &&
3747
72.3k
           cast<llvm::ConstantInt>(idx)->isZero());
3748
72.3k
#endif
3749
3750
  // Determine the element size of the statically-sized base.  This is
3751
  // the thing that the indices are expressed in terms of.
3752
72.3k
  if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3753
56
    eltType = getFixedSizeElementType(CGF.getContext(), vla);
3754
56
  }
3755
3756
  // We can use that to compute the best alignment of the element.
3757
72.3k
  CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3758
72.3k
  CharUnits eltAlign =
3759
72.3k
    getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3760
3761
72.3k
  llvm::Value *eltPtr;
3762
72.3k
  auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3763
72.3k
  if (!LastIndex ||
3764
72.3k
      
(21.0k
!CGF.IsInPreservedAIRegion21.0k
&&
!IsPreserveAIArrayBase(CGF, Base)21.0k
)) {
3765
72.3k
    eltPtr = emitArraySubscriptGEP(
3766
72.3k
        CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3767
72.3k
        signedIndices, loc, name);
3768
72.3k
  } else {
3769
    // Remember the original array subscript for bpf target
3770
11
    unsigned idx = LastIndex->getZExtValue();
3771
11
    llvm::DIType *DbgInfo = nullptr;
3772
11
    if (arrayType)
3773
11
      DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3774
11
    eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3775
11
                                                        addr.getPointer(),
3776
11
                                                        indices.size() - 1,
3777
11
                                                        idx, DbgInfo);
3778
11
  }
3779
3780
72.3k
  return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
3781
72.3k
}
3782
3783
LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3784
70.1k
                                               bool Accessed) {
3785
  // The index must always be an integer, which is not an aggregate.  Emit it
3786
  // in lexical order (this complexity is, sadly, required by C++17).
3787
70.1k
  llvm::Value *IdxPre =
3788
70.1k
      (E->getLHS() == E->getIdx()) ? 
EmitScalarExpr(E->getIdx())21
:
nullptr70.1k
;
3789
70.1k
  bool SignedIndices = false;
3790
70.1k
  auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3791
70.1k
    auto *Idx = IdxPre;
3792
70.1k
    if (E->getLHS() != E->getIdx()) {
3793
70.1k
      assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3794
0
      Idx = EmitScalarExpr(E->getIdx());
3795
70.1k
    }
3796
3797
0
    QualType IdxTy = E->getIdx()->getType();
3798
70.1k
    bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3799
70.1k
    SignedIndices |= IdxSigned;
3800
3801
70.1k
    if (SanOpts.has(SanitizerKind::ArrayBounds))
3802
55
      EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3803
3804
    // Extend or truncate the index type to 32 or 64-bits.
3805
70.1k
    if (Promote && 
Idx->getType() != IntPtrTy69.9k
)
3806
60.8k
      Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3807
3808
70.1k
    return Idx;
3809
70.1k
  };
3810
70.1k
  IdxPre = nullptr;
3811
3812
  // If the base is a vector type, then we are forming a vector element lvalue
3813
  // with this subscript.
3814
70.1k
  if (E->getBase()->getType()->isVectorType() &&
3815
70.1k
      
!isa<ExtVectorElementExpr>(E->getBase())172
) {
3816
    // Emit the vector as an lvalue to get its address.
3817
171
    LValue LHS = EmitLValue(E->getBase());
3818
171
    auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3819
171
    assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3820
0
    return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3821
171
                                 E->getBase()->getType(), LHS.getBaseInfo(),
3822
171
                                 TBAAAccessInfo());
3823
171
  }
3824
3825
  // All the other cases basically behave like simple offsetting.
3826
3827
  // Handle the extvector case we ignored above.
3828
69.9k
  if (isa<ExtVectorElementExpr>(E->getBase())) {
3829
1
    LValue LV = EmitLValue(E->getBase());
3830
1
    auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3831
1
    Address Addr = EmitExtVectorElementLValue(LV);
3832
3833
1
    QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3834
1
    Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3835
1
                                 SignedIndices, E->getExprLoc());
3836
1
    return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3837
1
                          CGM.getTBAAInfoForSubobject(LV, EltType));
3838
1
  }
3839
3840
69.9k
  LValueBaseInfo EltBaseInfo;
3841
69.9k
  TBAAAccessInfo EltTBAAInfo;
3842
69.9k
  Address Addr = Address::invalid();
3843
69.9k
  if (const VariableArrayType *vla =
3844
69.9k
           getContext().getAsVariableArrayType(E->getType())) {
3845
    // The base must be a pointer, which is not an aggregate.  Emit
3846
    // it.  It needs to be emitted first in case it's what captures
3847
    // the VLA bounds.
3848
1.58k
    Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3849
1.58k
    auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3850
3851
    // The element count here is the total number of non-VLA elements.
3852
1.58k
    llvm::Value *numElements = getVLASize(vla).NumElts;
3853
3854
    // Effectively, the multiply by the VLA size is part of the GEP.
3855
    // GEP indexes are signed, and scaling an index isn't permitted to
3856
    // signed-overflow, so we use the same semantics for our explicit
3857
    // multiply.  We suppress this if overflow is not undefined behavior.
3858
1.58k
    if (getLangOpts().isSignedOverflowDefined()) {
3859
0
      Idx = Builder.CreateMul(Idx, numElements);
3860
1.58k
    } else {
3861
1.58k
      Idx = Builder.CreateNSWMul(Idx, numElements);
3862
1.58k
    }
3863
3864
1.58k
    Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3865
1.58k
                                 !getLangOpts().isSignedOverflowDefined(),
3866
1.58k
                                 SignedIndices, E->getExprLoc());
3867
3868
68.3k
  } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3869
    // Indexing over an interface, as in "NSString *P; P[4];"
3870
3871
    // Emit the base pointer.
3872
5
    Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3873
5
    auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3874
3875
5
    CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3876
5
    llvm::Value *InterfaceSizeVal =
3877
5
        llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3878
3879
5
    llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3880
3881
    // We don't necessarily build correct LLVM struct types for ObjC
3882
    // interfaces, so we can't rely on GEP to do this scaling
3883
    // correctly, so we need to cast to i8*.  FIXME: is this actually
3884
    // true?  A lot of other things in the fragile ABI would break...
3885
5
    llvm::Type *OrigBaseElemTy = Addr.getElementType();
3886
5
    Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3887
3888
    // Do the GEP.
3889
5
    CharUnits EltAlign =
3890
5
      getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3891
5
    llvm::Value *EltPtr =
3892
5
        emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
3893
5
                              ScaledIdx, false, SignedIndices, E->getExprLoc());
3894
5
    Addr = Address(EltPtr, Addr.getElementType(), EltAlign);
3895
3896
    // Cast back.
3897
5
    Addr = Builder.CreateElementBitCast(Addr, OrigBaseElemTy);
3898
68.3k
  } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3899
    // If this is A[i] where A is an array, the frontend will have decayed the
3900
    // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3901
    // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3902
    // "gep x, i" here.  Emit one "gep A, 0, i".
3903
18.4k
    assert(Array->getType()->isArrayType() &&
3904
18.4k
           "Array to pointer decay must have array source type!");
3905
0
    LValue ArrayLV;
3906
    // For simple multidimensional array indexing, set the 'accessed' flag for
3907
    // better bounds-checking of the base expression.
3908
18.4k
    if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3909
1.32k
      ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3910
17.0k
    else
3911
17.0k
      ArrayLV = EmitLValue(Array);
3912
18.4k
    auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3913
3914
    // Propagate the alignment from the array itself to the result.
3915
18.4k
    QualType arrayType = Array->getType();
3916
18.4k
    Addr = emitArraySubscriptGEP(
3917
18.4k
        *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3918
18.4k
        E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3919
18.4k
        E->getExprLoc(), &arrayType, E->getBase());
3920
18.4k
    EltBaseInfo = ArrayLV.getBaseInfo();
3921
18.4k
    EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3922
49.9k
  } else {
3923
    // The base must be a pointer; emit it with an estimate of its alignment.
3924
49.9k
    Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3925
49.9k
    auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3926
49.9k
    QualType ptrType = E->getBase()->getType();
3927
49.9k
    Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3928
49.9k
                                 !getLangOpts().isSignedOverflowDefined(),
3929
49.9k
                                 SignedIndices, E->getExprLoc(), &ptrType,
3930
49.9k
                                 E->getBase());
3931
49.9k
  }
3932
3933
0
  LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3934
3935
69.9k
  if (getLangOpts().ObjC &&
3936
69.9k
      
getLangOpts().getGC() != LangOptions::NonGC42.9k
) {
3937
127
    LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3938
127
    setObjCGCLValueClass(getContext(), E, LV);
3939
127
  }
3940
69.9k
  return LV;
3941
69.9k
}
3942
3943
34
LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
3944
34
  assert(
3945
34
      !E->isIncomplete() &&
3946
34
      "incomplete matrix subscript expressions should be rejected during Sema");
3947
0
  LValue Base = EmitLValue(E->getBase());
3948
34
  llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
3949
34
  llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
3950
34
  llvm::Value *NumRows = Builder.getIntN(
3951
34
      RowIdx->getType()->getScalarSizeInBits(),
3952
34
      E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
3953
34
  llvm::Value *FinalIdx =
3954
34
      Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
3955
34
  return LValue::MakeMatrixElt(
3956
34
      MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
3957
34
      E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
3958
34
}
3959
3960
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3961
                                       LValueBaseInfo &BaseInfo,
3962
                                       TBAAAccessInfo &TBAAInfo,
3963
                                       QualType BaseTy, QualType ElTy,
3964
1.56k
                                       bool IsLowerBound) {
3965
1.56k
  LValue BaseLVal;
3966
1.56k
  if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3967
394
    BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3968
394
    if (BaseTy->isArrayType()) {
3969
154
      Address Addr = BaseLVal.getAddress(CGF);
3970
154
      BaseInfo = BaseLVal.getBaseInfo();
3971
3972
      // If the array type was an incomplete type, we need to make sure
3973
      // the decay ends up being the right type.
3974
154
      llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3975
154
      Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3976
3977
      // Note that VLA pointers are always decayed, so we don't need to do
3978
      // anything here.
3979
154
      if (!BaseTy->isVariableArrayType()) {
3980
84
        assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3981
84
               "Expected pointer to array");
3982
0
        Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3983
84
      }
3984
3985
0
      return CGF.Builder.CreateElementBitCast(Addr,
3986
154
                                              CGF.ConvertTypeForMem(ElTy));
3987
154
    }
3988
240
    LValueBaseInfo TypeBaseInfo;
3989
240
    TBAAAccessInfo TypeTBAAInfo;
3990
240
    CharUnits Align =
3991
240
        CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
3992
240
    BaseInfo.mergeForCast(TypeBaseInfo);
3993
240
    TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3994
240
    return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)),
3995
240
                   CGF.ConvertTypeForMem(ElTy), Align);
3996
394
  }
3997
1.16k
  return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3998
1.56k
}
3999
4000
LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
4001
2.39k
                                                bool IsLowerBound) {
4002
2.39k
  QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
4003
2.39k
  QualType ResultExprTy;
4004
2.39k
  if (auto *AT = getContext().getAsArrayType(BaseTy))
4005
1.33k
    ResultExprTy = AT->getElementType();
4006
1.06k
  else
4007
1.06k
    ResultExprTy = BaseTy->getPointeeType();
4008
2.39k
  llvm::Value *Idx = nullptr;
4009
2.39k
  if (IsLowerBound || 
E->getColonLocFirst().isInvalid()435
) {
4010
    // Requesting lower bound or upper bound, but without provided length and
4011
    // without ':' symbol for the default length -> length = 1.
4012
    // Idx = LowerBound ?: 0;
4013
1.98k
    if (auto *LowerBound = E->getLowerBound()) {
4014
927
      Idx = Builder.CreateIntCast(
4015
927
          EmitScalarExpr(LowerBound), IntPtrTy,
4016
927
          LowerBound->getType()->hasSignedIntegerRepresentation());
4017
927
    } else
4018
1.05k
      Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
4019
1.98k
  } else {
4020
    // Try to emit length or lower bound as constant. If this is possible, 1
4021
    // is subtracted from constant length or lower bound. Otherwise, emit LLVM
4022
    // IR (LB + Len) - 1.
4023
417
    auto &C = CGM.getContext();
4024
417
    auto *Length = E->getLength();
4025
417
    llvm::APSInt ConstLength;
4026
417
    if (Length) {
4027
      // Idx = LowerBound + Length - 1;
4028
381
      if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4029
198
        ConstLength = CL->zextOrTrunc(PointerWidthInBits);
4030
198
        Length = nullptr;
4031
198
      }
4032
381
      auto *LowerBound = E->getLowerBound();
4033
381
      llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4034
381
      if (LowerBound) {
4035
238
        if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) {
4036
238
          ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
4037
238
          LowerBound = nullptr;
4038
238
        }
4039
238
      }
4040
381
      if (!Length)
4041
198
        --ConstLength;
4042
183
      else if (!LowerBound)
4043
183
        --ConstLowerBound;
4044
4045
381
      if (Length || 
LowerBound198
) {
4046
183
        auto *LowerBoundVal =
4047
183
            LowerBound
4048
183
                ? Builder.CreateIntCast(
4049
0
                      EmitScalarExpr(LowerBound), IntPtrTy,
4050
0
                      LowerBound->getType()->hasSignedIntegerRepresentation())
4051
183
                : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
4052
183
        auto *LengthVal =
4053
183
            Length
4054
183
                ? Builder.CreateIntCast(
4055
183
                      EmitScalarExpr(Length), IntPtrTy,
4056
183
                      Length->getType()->hasSignedIntegerRepresentation())
4057
183
                : 
llvm::ConstantInt::get(IntPtrTy, ConstLength)0
;
4058
183
        Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
4059
183
                                /*HasNUW=*/false,
4060
183
                                !getLangOpts().isSignedOverflowDefined());
4061
183
        if (Length && LowerBound) {
4062
0
          Idx = Builder.CreateSub(
4063
0
              Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
4064
0
              /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4065
0
        }
4066
183
      } else
4067
198
        Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
4068
381
    } else {
4069
      // Idx = ArraySize - 1;
4070
36
      QualType ArrayTy = BaseTy->isPointerType()
4071
36
                             ? 
E->getBase()->IgnoreParenImpCasts()->getType()0
4072
36
                             : BaseTy;
4073
36
      if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
4074
30
        Length = VAT->getSizeExpr();
4075
30
        if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4076
21
          ConstLength = *L;
4077
21
          Length = nullptr;
4078
21
        }
4079
30
      } else {
4080
6
        auto *CAT = C.getAsConstantArrayType(ArrayTy);
4081
6
        ConstLength = CAT->getSize();
4082
6
      }
4083
36
      if (Length) {
4084
9
        auto *LengthVal = Builder.CreateIntCast(
4085
9
            EmitScalarExpr(Length), IntPtrTy,
4086
9
            Length->getType()->hasSignedIntegerRepresentation());
4087
9
        Idx = Builder.CreateSub(
4088
9
            LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
4089
9
            /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4090
27
      } else {
4091
27
        ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
4092
27
        --ConstLength;
4093
27
        Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
4094
27
      }
4095
36
    }
4096
417
  }
4097
2.39k
  assert(Idx);
4098
4099
0
  Address EltPtr = Address::invalid();
4100
2.39k
  LValueBaseInfo BaseInfo;
4101
2.39k
  TBAAAccessInfo TBAAInfo;
4102
2.39k
  if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
4103
    // The base must be a pointer, which is not an aggregate.  Emit
4104
    // it.  It needs to be emitted first in case it's what captures
4105
    // the VLA bounds.
4106
132
    Address Base =
4107
132
        emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
4108
132
                                BaseTy, VLA->getElementType(), IsLowerBound);
4109
    // The element count here is the total number of non-VLA elements.
4110
132
    llvm::Value *NumElements = getVLASize(VLA).NumElts;
4111
4112
    // Effectively, the multiply by the VLA size is part of the GEP.
4113
    // GEP indexes are signed, and scaling an index isn't permitted to
4114
    // signed-overflow, so we use the same semantics for our explicit
4115
    // multiply.  We suppress this if overflow is not undefined behavior.
4116
132
    if (getLangOpts().isSignedOverflowDefined())
4117
0
      Idx = Builder.CreateMul(Idx, NumElements);
4118
132
    else
4119
132
      Idx = Builder.CreateNSWMul(Idx, NumElements);
4120
132
    EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
4121
132
                                   !getLangOpts().isSignedOverflowDefined(),
4122
132
                                   /*signedIndices=*/false, E->getExprLoc());
4123
2.26k
  } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4124
    // If this is A[i] where A is an array, the frontend will have decayed the
4125
    // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
4126
    // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4127
    // "gep x, i" here.  Emit one "gep A, 0, i".
4128
835
    assert(Array->getType()->isArrayType() &&
4129
835
           "Array to pointer decay must have array source type!");
4130
0
    LValue ArrayLV;
4131
    // For simple multidimensional array indexing, set the 'accessed' flag for
4132
    // better bounds-checking of the base expression.
4133
835
    if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4134
96
      ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4135
739
    else
4136
739
      ArrayLV = EmitLValue(Array);
4137
4138
    // Propagate the alignment from the array itself to the result.
4139
835
    EltPtr = emitArraySubscriptGEP(
4140
835
        *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
4141
835
        ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
4142
835
        /*signedIndices=*/false, E->getExprLoc());
4143
835
    BaseInfo = ArrayLV.getBaseInfo();
4144
835
    TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
4145
1.43k
  } else {
4146
1.43k
    Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
4147
1.43k
                                           TBAAInfo, BaseTy, ResultExprTy,
4148
1.43k
                                           IsLowerBound);
4149
1.43k
    EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
4150
1.43k
                                   !getLangOpts().isSignedOverflowDefined(),
4151
1.43k
                                   /*signedIndices=*/false, E->getExprLoc());
4152
1.43k
  }
4153
4154
0
  return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
4155
2.39k
}
4156
4157
LValue CodeGenFunction::
4158
294
EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
4159
  // Emit the base vector as an l-value.
4160
294
  LValue Base;
4161
4162
  // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4163
294
  if (E->isArrow()) {
4164
    // If it is a pointer to a vector, emit the address and form an lvalue with
4165
    // it.
4166
1
    LValueBaseInfo BaseInfo;
4167
1
    TBAAAccessInfo TBAAInfo;
4168
1
    Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4169
1
    const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4170
1
    Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4171
1
    Base.getQuals().removeObjCGCAttr();
4172
293
  } else if (E->getBase()->isGLValue()) {
4173
    // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4174
    // emit the base as an lvalue.
4175
283
    assert(E->getBase()->getType()->isVectorType());
4176
0
    Base = EmitLValue(E->getBase());
4177
283
  } else {
4178
    // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4179
10
    assert(E->getBase()->getType()->isVectorType() &&
4180
10
           "Result must be a vector");
4181
0
    llvm::Value *Vec = EmitScalarExpr(E->getBase());
4182
4183
    // Store the vector to memory (because LValue wants an address).
4184
10
    Address VecMem = CreateMemTemp(E->getBase()->getType());
4185
10
    Builder.CreateStore(Vec, VecMem);
4186
10
    Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4187
10
                          AlignmentSource::Decl);
4188
10
  }
4189
4190
0
  QualType type =
4191
294
    E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4192
4193
  // Encode the element access list into a vector of unsigned indices.
4194
294
  SmallVector<uint32_t, 4> Indices;
4195
294
  E->getEncodedElementAccess(Indices);
4196
4197
294
  if (Base.isSimple()) {
4198
282
    llvm::Constant *CV =
4199
282
        llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4200
282
    return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
4201
282
                                    Base.getBaseInfo(), TBAAAccessInfo());
4202
282
  }
4203
12
  assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4204
4205
0
  llvm::Constant *BaseElts = Base.getExtVectorElts();
4206
12
  SmallVector<llvm::Constant *, 4> CElts;
4207
4208
24
  for (unsigned i = 0, e = Indices.size(); i != e; 
++i12
)
4209
12
    CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4210
12
  llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4211
12
  return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4212
12
                                  Base.getBaseInfo(), TBAAAccessInfo());
4213
294
}
4214
4215
189k
LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
4216
189k
  if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
4217
29
    EmitIgnoredExpr(E->getBase());
4218
29
    return EmitDeclRefLValue(DRE);
4219
29
  }
4220
4221
189k
  Expr *BaseExpr = E->getBase();
4222
  // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
4223
189k
  LValue BaseLV;
4224
189k
  if (E->isArrow()) {
4225
122k
    LValueBaseInfo BaseInfo;
4226
122k
    TBAAAccessInfo TBAAInfo;
4227
122k
    Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4228
122k
    QualType PtrTy = BaseExpr->getType()->getPointeeType();
4229
122k
    SanitizerSet SkippedChecks;
4230
122k
    bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4231
122k
    if (IsBaseCXXThis)
4232
44.5k
      SkippedChecks.set(SanitizerKind::Alignment, true);
4233
122k
    if (IsBaseCXXThis || 
isa<DeclRefExpr>(BaseExpr)77.4k
)
4234
44.5k
      SkippedChecks.set(SanitizerKind::Null, true);
4235
122k
    EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
4236
122k
                  /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4237
122k
    BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4238
122k
  } else
4239
67.1k
    BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4240
4241
189k
  NamedDecl *ND = E->getMemberDecl();
4242
189k
  if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4243
189k
    LValue LV = EmitLValueForField(BaseLV, Field);
4244
189k
    setObjCGCLValueClass(getContext(), E, LV);
4245
189k
    if (getLangOpts().OpenMP) {
4246
      // If the member was explicitly marked as nontemporal, mark it as
4247
      // nontemporal. If the base lvalue is marked as nontemporal, mark access
4248
      // to children as nontemporal too.
4249
8.79k
      if ((IsWrappedCXXThis(BaseExpr) &&
4250
8.79k
           
CGM.getOpenMPRuntime().isNontemporalDecl(Field)4.54k
) ||
4251
8.79k
          
BaseLV.isNontemporal()8.73k
)
4252
64
        LV.setNontemporal(/*Value=*/true);
4253
8.79k
    }
4254
189k
    return LV;
4255
189k
  }
4256
4257
0
  if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4258
0
    return EmitFunctionDeclLValue(*this, E, FD);
4259
4260
0
  llvm_unreachable("Unhandled member declaration!");
4261
0
}
4262
4263
/// Given that we are currently emitting a lambda, emit an l-value for
4264
/// one of its members.
4265
104
LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4266
104
  if (CurCodeDecl) {
4267
103
    assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
4268
0
    assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4269
103
  }
4270
0
  QualType LambdaTagType =
4271
104
    getContext().getTagDeclType(Field->getParent());
4272
104
  LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
4273
104
  return EmitLValueForField(LambdaLV, Field);
4274
104
}
4275
4276
/// Get the field index in the debug info. The debug info structure/union
4277
/// will ignore the unnamed bitfields.
4278
unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4279
20
                                             unsigned FieldIndex) {
4280
20
  unsigned I = 0, Skipped = 0;
4281
4282
41
  for (auto F : Rec->getDefinition()->fields()) {
4283
41
    if (I == FieldIndex)
4284
20
      break;
4285
21
    if (F->isUnnamedBitfield())
4286
2
      Skipped++;
4287
21
    I++;
4288
21
  }
4289
4290
20
  return FieldIndex - Skipped;
4291
20
}
4292
4293
/// Get the address of a zero-sized field within a record. The resulting
4294
/// address doesn't necessarily have the right type.
4295
static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4296
24
                                       const FieldDecl *Field) {
4297
24
  CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4298
24
      CGF.getContext().getFieldOffset(Field));
4299
24
  if (Offset.isZero())
4300
22
    return Base;
4301
2
  Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
4302
2
  return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4303
24
}
4304
4305
/// Drill down to the storage of a field without walking into
4306
/// reference types.
4307
///
4308
/// The resulting address doesn't necessarily have the right type.
4309
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4310
224k
                                      const FieldDecl *field) {
4311
224k
  if (field->isZeroSize(CGF.getContext()))
4312
24
    return emitAddrOfZeroSizeField(CGF, base, field);
4313
4314
224k
  const RecordDecl *rec = field->getParent();
4315
4316
224k
  unsigned idx =
4317
224k
    CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4318
4319
224k
  return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4320
224k
}
4321
4322
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
4323
11
                                        Address addr, const FieldDecl *field) {
4324
11
  const RecordDecl *rec = field->getParent();
4325
11
  llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4326
11
      base.getType(), rec->getLocation());
4327
4328
11
  unsigned idx =
4329
11
      CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4330
4331
11
  return CGF.Builder.CreatePreserveStructAccessIndex(
4332
11
      addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4333
11
}
4334
4335
16
static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4336
16
  const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4337
16
  if (!RD)
4338
3
    return false;
4339
4340
13
  if (RD->isDynamicClass())
4341
6
    return true;
4342
4343
7
  for (const auto &Base : RD->bases())
4344
2
    if (hasAnyVptr(Base.getType(), Context))
4345
2
      return true;
4346
4347
5
  for (const FieldDecl *Field : RD->fields())
4348
4
    if (hasAnyVptr(Field->getType(), Context))
4349
3
      return true;
4350
4351
2
  return false;
4352
5
}
4353
4354
LValue CodeGenFunction::EmitLValueForField(LValue base,
4355
232k
                                           const FieldDecl *field) {
4356
232k
  LValueBaseInfo BaseInfo = base.getBaseInfo();
4357
4358
232k
  if (field->isBitField()) {
4359
7.16k
    const CGRecordLayout &RL =
4360
7.16k
        CGM.getTypes().getCGRecordLayout(field->getParent());
4361
7.16k
    const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4362
7.16k
    const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4363
7.16k
                             
CGM.getCodeGenOpts().AAPCSBitfieldWidth481
&&
4364
7.16k
                             
Info.VolatileStorageSize != 0277
&&
4365
7.16k
                             field->getType()
4366
171
                                 .withCVRQualifiers(base.getVRQualifiers())
4367
171
                                 .isVolatileQualified();
4368
7.16k
    Address Addr = base.getAddress(*this);
4369
7.16k
    unsigned Idx = RL.getLLVMFieldNo(field);
4370
7.16k
    const RecordDecl *rec = field->getParent();
4371
7.16k
    if (!UseVolatile) {
4372
7.08k
      if (!IsInPreservedAIRegion &&
4373
7.08k
          (!getDebugInfo() || 
!rec->hasAttr<BPFPreserveAccessIndexAttr>()5.79k
)) {
4374
7.08k
        if (Idx != 0)
4375
          // For structs, we GEP to the field that the record layout suggests.
4376
518
          Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4377
7.08k
      } else {
4378
0
        llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4379
0
            getContext().getRecordType(rec), rec->getLocation());
4380
0
        Addr = Builder.CreatePreserveStructAccessIndex(
4381
0
            Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4382
0
            DbgInfo);
4383
0
      }
4384
7.08k
    }
4385
7.16k
    const unsigned SS =
4386
7.16k
        UseVolatile ? 
Info.VolatileStorageSize78
:
Info.StorageSize7.08k
;
4387
    // Get the access type.
4388
7.16k
    llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4389
7.16k
    if (Addr.getElementType() != FieldIntTy)
4390
6.76k
      Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4391
7.16k
    if (UseVolatile) {
4392
78
      const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4393
78
      if (VolatileOffset)
4394
28
        Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4395
78
    }
4396
4397
7.16k
    QualType fieldType =
4398
7.16k
        field->getType().withCVRQualifiers(base.getVRQualifiers());
4399
    // TODO: Support TBAA for bit fields.
4400
7.16k
    LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4401
7.16k
    return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4402
7.16k
                                TBAAAccessInfo());
4403
7.16k
  }
4404
4405
  // Fields of may-alias structures are may-alias themselves.
4406
  // FIXME: this should get propagated down through anonymous structs
4407
  // and unions.
4408
225k
  QualType FieldType = field->getType();
4409
225k
  const RecordDecl *rec = field->getParent();
4410
225k
  AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4411
225k
  LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4412
225k
  TBAAAccessInfo FieldTBAAInfo;
4413
225k
  if (base.getTBAAInfo().isMayAlias() ||
4414
225k
          
rec->hasAttr<MayAliasAttr>()224k
||
FieldType->isVectorType()223k
) {
4415
1.84k
    FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4416
223k
  } else if (rec->isUnion()) {
4417
    // TODO: Support TBAA for unions.
4418
5.46k
    FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4419
218k
  } else {
4420
    // If no base type been assigned for the base access, then try to generate
4421
    // one for this base lvalue.
4422
218k
    FieldTBAAInfo = base.getTBAAInfo();
4423
218k
    if (!FieldTBAAInfo.BaseType) {
4424
218k
        FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4425
218k
        assert(!FieldTBAAInfo.Offset &&
4426
218k
               "Nonzero offset for an access with no base type!");
4427
218k
    }
4428
4429
    // Adjust offset to be relative to the base type.
4430
0
    const ASTRecordLayout &Layout =
4431
218k
        getContext().getASTRecordLayout(field->getParent());
4432
218k
    unsigned CharWidth = getContext().getCharWidth();
4433
218k
    if (FieldTBAAInfo.BaseType)
4434
1.51k
      FieldTBAAInfo.Offset +=
4435
1.51k
          Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4436
4437
    // Update the final access type and size.
4438
218k
    FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4439
218k
    FieldTBAAInfo.Size =
4440
218k
        getContext().getTypeSizeInChars(FieldType).getQuantity();
4441
218k
  }
4442
4443
0
  Address addr = base.getAddress(*this);
4444
225k
  if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4445
219k
    if (CGM.getCodeGenOpts().StrictVTablePointers &&
4446
219k
        
ClassDef->isDynamicClass()18
) {
4447
      // Getting to any field of dynamic object requires stripping dynamic
4448
      // information provided by invariant.group.  This is because accessing
4449
      // fields may leak the real address of dynamic object, which could result
4450
      // in miscompilation when leaked pointer would be compared.
4451
5
      auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4452
5
      addr = Address(stripped, addr.getElementType(), addr.getAlignment());
4453
5
    }
4454
219k
  }
4455
4456
225k
  unsigned RecordCVR = base.getVRQualifiers();
4457
225k
  if (rec->isUnion()) {
4458
    // For unions, there is no pointer adjustment.
4459
5.47k
    if (CGM.getCodeGenOpts().StrictVTablePointers &&
4460
5.47k
        
hasAnyVptr(FieldType, getContext())10
)
4461
      // Because unions can easily skip invariant.barriers, we need to add
4462
      // a barrier every time CXXRecord field with vptr is referenced.
4463
6
      addr = Builder.CreateLaunderInvariantGroup(addr);
4464
4465
5.47k
    if (IsInPreservedAIRegion ||
4466
5.47k
        
(5.46k
getDebugInfo()5.46k
&&
rec->hasAttr<BPFPreserveAccessIndexAttr>()4.15k
)) {
4467
      // Remember the original union field index
4468
9
      llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
4469
9
          rec->getLocation());
4470
9
      addr = Address(
4471
9
          Builder.CreatePreserveUnionAccessIndex(
4472
9
              addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
4473
9
          addr.getElementType(), addr.getAlignment());
4474
9
    }
4475
4476
5.47k
    if (FieldType->isReferenceType())
4477
3
      addr = Builder.CreateElementBitCast(
4478
3
          addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4479
220k
  } else {
4480
220k
    if (!IsInPreservedAIRegion &&
4481
220k
        
(220k
!getDebugInfo()220k
||
!rec->hasAttr<BPFPreserveAccessIndexAttr>()163k
))
4482
      // For structs, we GEP to the field that the record layout suggests.
4483
220k
      addr = emitAddrOfFieldStorage(*this, addr, field);
4484
11
    else
4485
      // Remember the original struct field index
4486
11
      addr = emitPreserveStructAccess(*this, base, addr, field);
4487
220k
  }
4488
4489
  // If this is a reference field, load the reference right now.
4490
225k
  if (FieldType->isReferenceType()) {
4491
5.72k
    LValue RefLVal =
4492
5.72k
        MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4493
5.72k
    if (RecordCVR & Qualifiers::Volatile)
4494
0
      RefLVal.getQuals().addVolatile();
4495
5.72k
    addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
4496
4497
    // Qualifiers on the struct don't apply to the referencee.
4498
5.72k
    RecordCVR = 0;
4499
5.72k
    FieldType = FieldType->getPointeeType();
4500
5.72k
  }
4501
4502
  // Make sure that the address is pointing to the right type.  This is critical
4503
  // for both unions and structs.  A union needs a bitcast, a struct element
4504
  // will need a bitcast if the LLVM type laid out doesn't match the desired
4505
  // type.
4506
225k
  addr = Builder.CreateElementBitCast(
4507
225k
      addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4508
4509
225k
  if (field->hasAttr<AnnotateAttr>())
4510
5
    addr = EmitFieldAnnotations(field, addr);
4511
4512
225k
  LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4513
225k
  LV.getQuals().addCVRQualifiers(RecordCVR);
4514
4515
  // __weak attribute on a field is ignored.
4516
225k
  if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4517
0
    LV.getQuals().removeObjCGCAttr();
4518
4519
225k
  return LV;
4520
232k
}
4521
4522
LValue
4523
CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
4524
25.1k
                                                  const FieldDecl *Field) {
4525
25.1k
  QualType FieldType = Field->getType();
4526
4527
25.1k
  if (!FieldType->isReferenceType())
4528
21.0k
    return EmitLValueForField(Base, Field);
4529
4530
4.10k
  Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
4531
4532
  // Make sure that the address is pointing to the right type.
4533
4.10k
  llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4534
4.10k
  V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
4535
4536
  // TODO: Generate TBAA information that describes this access as a structure
4537
  // member access and not just an access to an object of the field's type. This
4538
  // should be similar to what we do in EmitLValueForField().
4539
4.10k
  LValueBaseInfo BaseInfo = Base.getBaseInfo();
4540
4.10k
  AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4541
4.10k
  LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
4542
4.10k
  return MakeAddrLValue(V, FieldType, FieldBaseInfo,
4543
4.10k
                        CGM.getTBAAInfoForSubobject(Base, FieldType));
4544
25.1k
}
4545
4546
1.22k
LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
4547
1.22k
  if (E->isFileScope()) {
4548
3
    ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
4549
3
    return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
4550
3
  }
4551
1.22k
  if (E->getType()->isVariablyModifiedType())
4552
    // make sure to emit the VLA size.
4553
4
    EmitVariablyModifiedType(E->getType());
4554
4555
1.22k
  Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
4556
1.22k
  const Expr *InitExpr = E->getInitializer();
4557
1.22k
  LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
4558
4559
1.22k
  EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4560
1.22k
                   /*Init*/ true);
4561
4562
  // Block-scope compound literals are destroyed at the end of the enclosing
4563
  // scope in C.
4564
1.22k
  if (!getLangOpts().CPlusPlus)
4565
1.13k
    if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
4566
13
      pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
4567
13
                                  E->getType(), getDestroyer(DtorKind),
4568
13
                                  DtorKind & EHCleanup);
4569
4570
1.22k
  return Result;
4571
1.22k
}
4572
4573
6
LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4574
6
  if (!E->isGLValue())
4575
    // Initializing an aggregate temporary in C++11: T{...}.
4576
0
    return EmitAggExprToLValue(E);
4577
4578
  // An lvalue initializer list must be initializing a reference.
4579
6
  assert(E->isTransparent() && "non-transparent glvalue init list");
4580
0
  return EmitLValue(E->getInit(0));
4581
6
}
4582
4583
/// Emit the operand of a glvalue conditional operator. This is either a glvalue
4584
/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4585
/// LValue is returned and the current block has been terminated.
4586
static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4587
1.03k
                                                    const Expr *Operand) {
4588
1.03k
  if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4589
2
    CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4590
2
    return None;
4591
2
  }
4592
4593
1.03k
  return CGF.EmitLValue(Operand);
4594
1.03k
}
4595
4596
namespace {
4597
// Handle the case where the condition is a constant evaluatable simple integer,
4598
// which means we don't have to separately handle the true/false blocks.
4599
llvm::Optional<LValue> HandleConditionalOperatorLValueSimpleCase(
4600
526
    CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
4601
526
  const Expr *condExpr = E->getCond();
4602
526
  bool CondExprBool;
4603
526
  if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4604
4
    const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
4605
4
    if (!CondExprBool)
4606
1
      std::swap(Live, Dead);
4607
4608
4
    if (!CGF.ContainsLabel(Dead)) {
4609
      // If the true case is live, we need to track its region.
4610
4
      if (CondExprBool)
4611
3
        CGF.incrementProfileCounter(E);
4612
      // If a throw expression we emit it and return an undefined lvalue
4613
      // because it can't be used.
4614
4
      if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
4615
1
        CGF.EmitCXXThrowExpr(ThrowExpr);
4616
1
        llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
4617
1
        llvm::Type *Ty = llvm::PointerType::getUnqual(ElemTy);
4618
1
        return CGF.MakeAddrLValue(
4619
1
            Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
4620
1
            Dead->getType());
4621
1
      }
4622
3
      return CGF.EmitLValue(Live);
4623
4
    }
4624
4
  }
4625
522
  return llvm::None;
4626
526
}
4627
struct ConditionalInfo {
4628
  llvm::BasicBlock *lhsBlock, *rhsBlock;
4629
  Optional<LValue> LHS, RHS;
4630
};
4631
4632
// Create and generate the 3 blocks for a conditional operator.
4633
// Leaves the 'current block' in the continuation basic block.
4634
template<typename FuncTy>
4635
ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
4636
                                      const AbstractConditionalOperator *E,
4637
522
                                      const FuncTy &BranchGenFunc) {
4638
522
  ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
4639
522
                       CGF.createBasicBlock("cond.false"), llvm::None,
4640
522
                       llvm::None};
4641
522
  llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
4642
4643
522
  CodeGenFunction::ConditionalEvaluation eval(CGF);
4644
522
  CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
4645
522
                           CGF.getProfileCount(E));
4646
4647
  // Any temporaries created here are conditional.
4648
522
  CGF.EmitBlock(Info.lhsBlock);
4649
522
  CGF.incrementProfileCounter(E);
4650
522
  eval.begin(CGF);
4651
522
  Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
4652
522
  eval.end(CGF);
4653
522
  Info.lhsBlock = CGF.Builder.GetInsertBlock();
4654
4655
522
  if (Info.LHS)
4656
521
    CGF.Builder.CreateBr(endBlock);
4657
4658
  // Any temporaries created here are conditional.
4659
522
  CGF.EmitBlock(Info.rhsBlock);
4660
522
  eval.begin(CGF);
4661
522
  Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
4662
522
  eval.end(CGF);
4663
522
  Info.rhsBlock = CGF.Builder.GetInsertBlock();
4664
522
  CGF.EmitBlock(endBlock);
4665
4666
522
  return Info;
4667
522
}
CGExpr.cpp:(anonymous namespace)::ConditionalInfo (anonymous namespace)::EmitConditionalBlocks<clang::CodeGen::CodeGenFunction::EmitIgnoredConditionalOperator(clang::AbstractConditionalOperator const*)::$_1>(clang::CodeGen::CodeGenFunction&, clang::AbstractConditionalOperator const*, clang::CodeGen::CodeGenFunction::EmitIgnoredConditionalOperator(clang::AbstractConditionalOperator const*)::$_1 const&)
Line
Count
Source
4637
4
                                      const FuncTy &BranchGenFunc) {
4638
4
  ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
4639
4
                       CGF.createBasicBlock("cond.false"), llvm::None,
4640
4
                       llvm::None};
4641
4
  llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
4642
4643
4
  CodeGenFunction::ConditionalEvaluation eval(CGF);
4644
4
  CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
4645
4
                           CGF.getProfileCount(E));
4646
4647
  // Any temporaries created here are conditional.
4648
4
  CGF.EmitBlock(Info.lhsBlock);
4649
4
  CGF.incrementProfileCounter(E);
4650
4
  eval.begin(CGF);
4651
4
  Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
4652
4
  eval.end(CGF);
4653
4
  Info.lhsBlock = CGF.Builder.GetInsertBlock();
4654
4655
4
  if (Info.LHS)
4656
4
    CGF.Builder.CreateBr(endBlock);
4657
4658
  // Any temporaries created here are conditional.
4659
4
  CGF.EmitBlock(Info.rhsBlock);
4660
4
  eval.begin(CGF);
4661
4
  Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
4662
4
  eval.end(CGF);
4663
4
  Info.rhsBlock = CGF.Builder.GetInsertBlock();
4664
4
  CGF.EmitBlock(endBlock);
4665
4666
4
  return Info;
4667
4
}
CGExpr.cpp:(anonymous namespace)::ConditionalInfo (anonymous namespace)::EmitConditionalBlocks<clang::CodeGen::CodeGenFunction::EmitConditionalOperatorLValue(clang::AbstractConditionalOperator const*)::$_2>(clang::CodeGen::CodeGenFunction&, clang::AbstractConditionalOperator const*, clang::CodeGen::CodeGenFunction::EmitConditionalOperatorLValue(clang::AbstractConditionalOperator const*)::$_2 const&)
Line
Count
Source
4637
518
                                      const FuncTy &BranchGenFunc) {
4638
518
  ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
4639
518
                       CGF.createBasicBlock("cond.false"), llvm::None,
4640
518
                       llvm::None};
4641
518
  llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
4642
4643
518
  CodeGenFunction::ConditionalEvaluation eval(CGF);
4644
518
  CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
4645
518
                           CGF.getProfileCount(E));
4646
4647
  // Any temporaries created here are conditional.
4648
518
  CGF.EmitBlock(Info.lhsBlock);
4649
518
  CGF.incrementProfileCounter(E);
4650
518
  eval.begin(CGF);
4651
518
  Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
4652
518
  eval.end(CGF);
4653
518
  Info.lhsBlock = CGF.Builder.GetInsertBlock();
4654
4655
518
  if (Info.LHS)
4656
517
    CGF.Builder.CreateBr(endBlock);
4657
4658
  // Any temporaries created here are conditional.
4659
518
  CGF.EmitBlock(Info.rhsBlock);
4660
518
  eval.begin(CGF);
4661
518
  Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
4662
518
  eval.end(CGF);
4663
518
  Info.rhsBlock = CGF.Builder.GetInsertBlock();
4664
518
  CGF.EmitBlock(endBlock);
4665
4666
518
  return Info;
4667
518
}
4668
} // namespace
4669
4670
void CodeGenFunction::EmitIgnoredConditionalOperator(
4671
4
    const AbstractConditionalOperator *E) {
4672
4
  if (!E->isGLValue()) {
4673
    // ?: here should be an aggregate.
4674
0
    assert(hasAggregateEvaluationKind(E->getType()) &&
4675
0
           "Unexpected conditional operator!");
4676
0
    return (void)EmitAggExprToLValue(E);
4677
0
  }
4678
4679
4
  OpaqueValueMapping binding(*this, E);
4680
4
  if (HandleConditionalOperatorLValueSimpleCase(*this, E))
4681
0
    return;
4682
4683
8
  
EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) 4
{
4684
8
    CGF.EmitIgnoredExpr(E);
4685
8
    return LValue{};
4686
8
  });
4687
4
}
4688
LValue CodeGenFunction::EmitConditionalOperatorLValue(
4689
531
    const AbstractConditionalOperator *expr) {
4690
531
  if (!expr->isGLValue()) {
4691
    // ?: here should be an aggregate.
4692
9
    assert(hasAggregateEvaluationKind(expr->getType()) &&
4693
9
           "Unexpected conditional operator!");
4694
0
    return EmitAggExprToLValue(expr);
4695
9
  }
4696
4697
522
  OpaqueValueMapping binding(*this, expr);
4698
522
  if (llvm::Optional<LValue> Res =
4699
522
          HandleConditionalOperatorLValueSimpleCase(*this, expr))
4700
4
    return *Res;
4701
4702
518
  ConditionalInfo Info = EmitConditionalBlocks(
4703
1.03k
      *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
4704
1.03k
        return EmitLValueOrThrowExpression(CGF, E);
4705
1.03k
      });
4706
4707
518
  if ((Info.LHS && 
!Info.LHS->isSimple()517
) ||
4708
518
      (Info.RHS && 
!Info.RHS->isSimple()517
))
4709
0
    return EmitUnsupportedLValue(expr, "conditional operator");
4710
4711
518
  if (Info.LHS && 
Info.RHS517
) {
4712
516
    Address lhsAddr = Info.LHS->getAddress(*this);
4713
516
    Address rhsAddr = Info.RHS->getAddress(*this);
4714
516
    llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
4715
516
    phi->addIncoming(lhsAddr.getPointer(), Info.lhsBlock);
4716
516
    phi->addIncoming(rhsAddr.getPointer(), Info.rhsBlock);
4717
516
    Address result(phi, lhsAddr.getElementType(),
4718
516
                   std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
4719
516
    AlignmentSource alignSource =
4720
516
        std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
4721
516
                 Info.RHS->getBaseInfo().getAlignmentSource());
4722
516
    TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4723
516
        Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
4724
516
    return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4725
516
                          TBAAInfo);
4726
516
  } else {
4727
2
    assert((Info.LHS || Info.RHS) &&
4728
2
           "both operands of glvalue conditional are throw-expressions?");
4729
2
    return Info.LHS ? 
*Info.LHS1
:
*Info.RHS1
;
4730
2
  }
4731
518
}
4732
4733
/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4734
/// type. If the cast is to a reference, we can have the usual lvalue result,
4735
/// otherwise if a cast is needed by the code generator in an lvalue context,
4736
/// then it must mean that we need the address of an aggregate in order to
4737
/// access one of its members.  This can happen for all the reasons that casts
4738
/// are permitted with aggregate result, including noop aggregate casts, and
4739
/// cast from scalar to union.
4740
38.9k
LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4741
38.9k
  switch (E->getCastKind()) {
4742
0
  case CK_ToVoid:
4743
0
  case CK_BitCast:
4744
0
  case CK_LValueToRValueBitCast:
4745
0
  case CK_ArrayToPointerDecay:
4746
0
  case CK_FunctionToPointerDecay:
4747
0
  case CK_NullToMemberPointer:
4748
0
  case CK_NullToPointer:
4749
0
  case CK_IntegralToPointer:
4750
0
  case CK_PointerToIntegral:
4751
0
  case CK_PointerToBoolean:
4752
0
  case CK_VectorSplat:
4753
0
  case CK_IntegralCast:
4754
0
  case CK_BooleanToSignedIntegral:
4755
0
  case CK_IntegralToBoolean:
4756
0
  case CK_IntegralToFloating:
4757
0
  case CK_FloatingToIntegral:
4758
0
  case CK_FloatingToBoolean:
4759
0
  case CK_FloatingCast:
4760
0
  case CK_FloatingRealToComplex:
4761
0
  case CK_FloatingComplexToReal:
4762
0
  case CK_FloatingComplexToBoolean:
4763
0
  case CK_FloatingComplexCast:
4764
0
  case CK_FloatingComplexToIntegralComplex:
4765
0
  case CK_IntegralRealToComplex:
4766
0
  case CK_IntegralComplexToReal:
4767
0
  case CK_IntegralComplexToBoolean:
4768
0
  case CK_IntegralComplexCast:
4769
0
  case CK_IntegralComplexToFloatingComplex:
4770
0
  case CK_DerivedToBaseMemberPointer:
4771
0
  case CK_BaseToDerivedMemberPointer:
4772
0
  case CK_MemberPointerToBoolean:
4773
0
  case CK_ReinterpretMemberPointer:
4774
0
  case CK_AnyPointerToBlockPointerCast:
4775
0
  case CK_ARCProduceObject:
4776
0
  case CK_ARCConsumeObject:
4777
0
  case CK_ARCReclaimReturnedObject:
4778
0
  case CK_ARCExtendBlockObject:
4779
0
  case CK_CopyAndAutoreleaseBlockObject:
4780
0
  case CK_IntToOCLSampler:
4781
0
  case CK_FloatingToFixedPoint:
4782
0
  case CK_FixedPointToFloating:
4783
0
  case CK_FixedPointCast:
4784
0
  case CK_FixedPointToBoolean:
4785
0
  case CK_FixedPointToIntegral:
4786
0
  case CK_IntegralToFixedPoint:
4787
0
  case CK_MatrixCast:
4788
0
    return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4789
4790
0
  case CK_Dependent:
4791
0
    llvm_unreachable("dependent cast kind in IR gen!");
4792
4793
0
  case CK_BuiltinFnToFnPtr:
4794
0
    llvm_unreachable("builtin functions are handled elsewhere");
4795
4796
  // These are never l-values; just use the aggregate emission code.
4797
0
  case CK_NonAtomicToAtomic:
4798
1
  case CK_AtomicToNonAtomic:
4799
1
    return EmitAggExprToLValue(E);
4800
4801
13
  case CK_Dynamic: {
4802
13
    LValue LV = EmitLValue(E->getSubExpr());
4803
13
    Address V = LV.getAddress(*this);
4804
13
    const auto *DCE = cast<CXXDynamicCastExpr>(E);
4805
13
    return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4806
0
  }
4807
4808
0
  case CK_ConstructorConversion:
4809
15
  case CK_UserDefinedConversion:
4810
15
  case CK_CPointerToObjCPointerCast:
4811
15
  case CK_BlockPointerToObjCPointerCast:
4812
17
  case CK_LValueToRValue:
4813
17
    return EmitLValue(E->getSubExpr());
4814
4815
27.7k
  case CK_NoOp: {
4816
    // CK_NoOp can model a qualification conversion, which can remove an array
4817
    // bound and change the IR type.
4818
    // FIXME: Once pointee types are removed from IR, remove this.
4819
27.7k
    LValue LV = EmitLValue(E->getSubExpr());
4820
27.7k
    if (LV.isSimple()) {
4821
27.7k
      Address V = LV.getAddress(*this);
4822
27.7k
      if (V.isValid()) {
4823
27.7k
        llvm::Type *T = ConvertTypeForMem(E->getType());
4824
27.7k
        if (V.getElementType() != T)
4825
1
          LV.setAddress(Builder.CreateElementBitCast(V, T));
4826
27.7k
      }
4827
27.7k
    }
4828
27.7k
    return LV;
4829
15
  }
4830
4831
3.15k
  case CK_UncheckedDerivedToBase:
4832
10.9k
  case CK_DerivedToBase: {
4833
10.9k
    const auto *DerivedClassTy =
4834
10.9k
        E->getSubExpr()->getType()->castAs<RecordType>();
4835
10.9k
    auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4836
4837
10.9k
    LValue LV = EmitLValue(E->getSubExpr());
4838
10.9k
    Address This = LV.getAddress(*this);
4839
4840
    // Perform the derived-to-base conversion
4841
10.9k
    Address Base = GetAddressOfBaseClass(
4842
10.9k
        This, DerivedClassDecl, E->path_begin(), E->path_end(),
4843
10.9k
        /*NullCheckValue=*/false, E->getExprLoc());
4844
4845
    // TODO: Support accesses to members of base classes in TBAA. For now, we
4846
    // conservatively pretend that the complete object is of the base class
4847
    // type.
4848
10.9k
    return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4849
10.9k
                          CGM.getTBAAInfoForSubobject(LV, E->getType()));
4850
3.15k
  }
4851
3
  case CK_ToUnion:
4852
3
    return EmitAggExprToLValue(E);
4853
92
  case CK_BaseToDerived: {
4854
92
    const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
4855
92
    auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4856
4857
92
    LValue LV = EmitLValue(E->getSubExpr());
4858
4859
    // Perform the base-to-derived conversion
4860
92
    Address Derived = GetAddressOfDerivedClass(
4861
92
        LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4862
92
        /*NullCheckValue=*/false);
4863
4864
    // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4865
    // performed and the object is not of the derived type.
4866
92
    if (sanitizePerformTypeCheck())
4867
7
      EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4868
7
                    Derived.getPointer(), E->getType());
4869
4870
92
    if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4871
3
      EmitVTablePtrCheckForCast(E->getType(), Derived,
4872
3
                                /*MayBeNull=*/false, CFITCK_DerivedCast,
4873
3
                                E->getBeginLoc());
4874
4875
92
    return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4876
92
                          CGM.getTBAAInfoForSubobject(LV, E->getType()));
4877
3.15k
  }
4878
23
  case CK_LValueBitCast: {
4879
    // This must be a reinterpret_cast (or c-style equivalent).
4880
23
    const auto *CE = cast<ExplicitCastExpr>(E);
4881
4882
23
    CGM.EmitExplicitCastExprType(CE, this);
4883
23
    LValue LV = EmitLValue(E->getSubExpr());
4884
23
    Address V = Builder.CreateElementBitCast(
4885
23
        LV.getAddress(*this),
4886
23
        ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
4887
4888
23
    if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4889
4
      EmitVTablePtrCheckForCast(E->getType(), V,
4890
4
                                /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4891
4
                                E->getBeginLoc());
4892
4893
23
    return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4894
23
                          CGM.getTBAAInfoForSubobject(LV, E->getType()));
4895
3.15k
  }
4896
71
  case CK_AddressSpaceConversion: {
4897
71
    LValue LV = EmitLValue(E->getSubExpr());
4898
71
    QualType DestTy = getContext().getPointerType(E->getType());
4899
71
    llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4900
71
        *this, LV.getPointer(*this),
4901
71
        E->getSubExpr()->getType().getAddressSpace(),
4902
71
        E->getType().getAddressSpace(), ConvertType(DestTy));
4903
71
    return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()),
4904
71
                                  LV.getAddress(*this).getAlignment()),
4905
71
                          E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
4906
3.15k
  }
4907
5
  case CK_ObjCObjectLValueCast: {
4908
5
    LValue LV = EmitLValue(E->getSubExpr());
4909
5
    Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
4910
5
                                             ConvertType(E->getType()));
4911
5
    return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4912
5
                          CGM.getTBAAInfoForSubobject(LV, E->getType()));
4913
3.15k
  }
4914
0
  case CK_ZeroToOCLOpaqueType:
4915
0
    llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
4916
38.9k
  }
4917
4918
0
  llvm_unreachable("Unhandled lvalue cast kind?");
4919
0
}
4920
4921
1.08k
LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4922
1.08k
  assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4923
0
  return getOrCreateOpaqueLValueMapping(e);
4924
1.08k
}
4925
4926
LValue
4927
1.33k
CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4928
1.33k
  assert(OpaqueValueMapping::shouldBindAsLValue(e));
4929
4930
0
  llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4931
1.33k
      it = OpaqueLValues.find(e);
4932
4933
1.33k
  if (it != OpaqueLValues.end())
4934
1.20k
    return it->second;
4935
4936
122
  assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4937
0
  return EmitLValue(e->getSourceExpr());
4938
1.33k
}
4939
4940
RValue
4941
2.49k
CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4942
2.49k
  assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4943
4944
0
  llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4945
2.49k
      it = OpaqueRValues.find(e);
4946
4947
2.49k
  if (it != OpaqueRValues.end())
4948
1.92k
    return it->second;
4949
4950
570
  assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4951
0
  return EmitAnyExpr(e->getSourceExpr());
4952
2.49k
}
4953
4954
RValue CodeGenFunction::EmitRValueForField(LValue LV,
4955
                                           const FieldDecl *FD,
4956
48
                                           SourceLocation Loc) {
4957
48
  QualType FT = FD->getType();
4958
48
  LValue FieldLV = EmitLValueForField(LV, FD);
4959
48
  switch (getEvaluationKind(FT)) {
4960
1
  case TEK_Complex:
4961
1
    return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4962
0
  case TEK_Aggregate:
4963
0
    return FieldLV.asAggregateRValue(*this);
4964
47
  case TEK_Scalar:
4965
    // This routine is used to load fields one-by-one to perform a copy, so
4966
    // don't load reference fields.
4967
47
    if (FD->getType()->isReferenceType())
4968
1
      return RValue::get(FieldLV.getPointer(*this));
4969
    // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4970
    // primitive load.
4971
46
    if (FieldLV.isBitField())
4972
0
      return EmitLoadOfLValue(FieldLV, Loc);
4973
46
    return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
4974
48
  }
4975
0
  llvm_unreachable("bad evaluation kind");
4976
0
}
4977
4978
//===--------------------------------------------------------------------===//
4979
//                             Expression Emission
4980
//===--------------------------------------------------------------------===//
4981
4982
RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4983
338k
                                     ReturnValueSlot ReturnValue) {
4984
  // Builtins never have block type.
4985
338k
  if (E->getCallee()->getType()->isBlockPointerType())
4986
621
    return EmitBlockCallExpr(E, ReturnValue);
4987
4988
338k
  if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4989
67.9k
    return EmitCXXMemberCallExpr(CE, ReturnValue);
4990
4991
270k
  if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4992
63
    return EmitCUDAKernelCallExpr(CE, ReturnValue);
4993
4994
270k
  if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4995
13.6k
    if (const CXXMethodDecl *MD =
4996
13.6k
          dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4997
11.4k
      return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4998
4999
258k
  CGCallee callee = EmitCallee(E->getCallee());
5000
5001
258k
  if (callee.isBuiltin()) {
5002
96.1k
    return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
5003
96.1k
                           E, ReturnValue);
5004
96.1k
  }
5005
5006
162k
  if (callee.isPseudoDestructor()) {
5007
195
    return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
5008
195
  }
5009
5010
162k
  return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
5011
162k
}
5012
5013
/// Emit a CallExpr without considering whether it might be a subclass.
5014
RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
5015
63
                                           ReturnValueSlot ReturnValue) {
5016
63
  CGCallee Callee = EmitCallee(E->getCallee());
5017
63
  return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
5018
63
}
5019
5020