Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGExprAgg.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate 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 Aggregate Expr nodes as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGObjCRuntime.h"
15
#include "CodeGenFunction.h"
16
#include "CodeGenModule.h"
17
#include "ConstantEmitter.h"
18
#include "TargetInfo.h"
19
#include "clang/AST/ASTContext.h"
20
#include "clang/AST/Attr.h"
21
#include "clang/AST/DeclCXX.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/StmtVisitor.h"
24
#include "llvm/IR/Constants.h"
25
#include "llvm/IR/Function.h"
26
#include "llvm/IR/GlobalVariable.h"
27
#include "llvm/IR/IntrinsicInst.h"
28
#include "llvm/IR/Intrinsics.h"
29
using namespace clang;
30
using namespace CodeGen;
31
32
//===----------------------------------------------------------------------===//
33
//                        Aggregate Expression Emitter
34
//===----------------------------------------------------------------------===//
35
36
namespace  {
37
class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
38
  CodeGenFunction &CGF;
39
  CGBuilderTy &Builder;
40
  AggValueSlot Dest;
41
  bool IsResultUnused;
42
43
67.1k
  AggValueSlot EnsureSlot(QualType T) {
44
67.1k
    if (!Dest.isIgnored()) 
return Dest67.0k
;
45
68
    return CGF.CreateAggTemp(T, "agg.tmp.ensured");
46
68
  }
47
6.05k
  void EnsureDest(QualType T) {
48
6.05k
    if (!Dest.isIgnored()) 
return5.89k
;
49
159
    Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
50
159
  }
51
52
  // Calls `Fn` with a valid return value slot, potentially creating a temporary
53
  // to do so. If a temporary is created, an appropriate copy into `Dest` will
54
  // be emitted, as will lifetime markers.
55
  //
56
  // The given function should take a ReturnValueSlot, and return an RValue that
57
  // points to said slot.
58
  void withReturnValueSlot(const Expr *E,
59
                           llvm::function_ref<RValue(ReturnValueSlot)> Fn);
60
61
public:
62
  AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
63
    : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
64
77.7k
    IsResultUnused(IsResultUnused) { }
65
66
  //===--------------------------------------------------------------------===//
67
  //                               Utilities
68
  //===--------------------------------------------------------------------===//
69
70
  /// EmitAggLoadOfLValue - Given an expression with aggregate type that
71
  /// represents a value lvalue, this method emits the address of the lvalue,
72
  /// then loads the result into DestPtr.
73
  void EmitAggLoadOfLValue(const Expr *E);
74
75
  enum ExprValueKind {
76
    EVK_RValue,
77
    EVK_NonRValue
78
  };
79
80
  /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
81
  /// SrcIsRValue is true if source comes from an RValue.
82
  void EmitFinalDestCopy(QualType type, const LValue &src,
83
                         ExprValueKind SrcValueKind = EVK_NonRValue);
84
  void EmitFinalDestCopy(QualType type, RValue src);
85
  void EmitCopy(QualType type, const AggValueSlot &dest,
86
                const AggValueSlot &src);
87
88
  void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
89
90
  void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
91
                     QualType ArrayQTy, InitListExpr *E);
92
93
3.47k
  AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
94
3.47k
    if (CGF.getLangOpts().getGC() && 
TypeRequiresGCollection(T)24
)
95
20
      return AggValueSlot::NeedsGCBarriers;
96
3.45k
    return AggValueSlot::DoesNotNeedGCBarriers;
97
3.45k
  }
98
99
  bool TypeRequiresGCollection(QualType T);
100
101
  //===--------------------------------------------------------------------===//
102
  //                            Visitor Methods
103
  //===--------------------------------------------------------------------===//
104
105
116k
  void Visit(Expr *E) {
106
116k
    ApplyDebugLocation DL(CGF, E);
107
116k
    StmtVisitor<AggExprEmitter>::Visit(E);
108
116k
  }
109
110
0
  void VisitStmt(Stmt *S) {
111
0
    CGF.ErrorUnsupported(S, "aggregate expression");
112
0
  }
113
89
  void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
114
0
  void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
115
0
    Visit(GE->getResultExpr());
116
0
  }
117
5
  void VisitCoawaitExpr(CoawaitExpr *E) {
118
5
    CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
119
5
  }
120
0
  void VisitCoyieldExpr(CoyieldExpr *E) {
121
0
    CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
122
0
  }
123
0
  void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
124
639
  void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
125
0
  void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
126
0
    return Visit(E->getReplacement());
127
0
  }
128
129
9
  void VisitConstantExpr(ConstantExpr *E) {
130
9
    if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
131
8
      CGF.EmitAggregateStore(Result, Dest.getAddress(),
132
8
                             E->getType().isVolatileQualified());
133
8
      return;
134
8
    }
135
1
    return Visit(E->getSubExpr());
136
1
  }
137
138
  // l-values.
139
2.38k
  void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
140
7
  void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
141
94
  void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
142
63
  void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
143
  void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
144
6
  void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
145
6
    EmitAggLoadOfLValue(E);
146
6
  }
147
0
  void VisitPredefinedExpr(const PredefinedExpr *E) {
148
0
    EmitAggLoadOfLValue(E);
149
0
  }
150
151
  // Operators.
152
  void VisitCastExpr(CastExpr *E);
153
  void VisitCallExpr(const CallExpr *E);
154
  void VisitStmtExpr(const StmtExpr *E);
155
  void VisitBinaryOperator(const BinaryOperator *BO);
156
  void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
157
  void VisitBinAssign(const BinaryOperator *E);
158
  void VisitBinComma(const BinaryOperator *E);
159
  void VisitBinCmp(const BinaryOperator *E);
160
0
  void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
161
0
    Visit(E->getSemanticForm());
162
0
  }
163
164
  void VisitObjCMessageExpr(ObjCMessageExpr *E);
165
5
  void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
166
5
    EmitAggLoadOfLValue(E);
167
5
  }
168
169
  void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
170
  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
171
  void VisitChooseExpr(const ChooseExpr *CE);
172
  void VisitInitListExpr(InitListExpr *E);
173
  void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
174
                              llvm::Value *outerBegin = nullptr);
175
  void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
176
0
  void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
177
397
  void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
178
397
    CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
179
397
    Visit(DAE->getExpr());
180
397
  }
181
35
  void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
182
35
    CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
183
35
    Visit(DIE->getExpr());
184
35
  }
185
  void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
186
  void VisitCXXConstructExpr(const CXXConstructExpr *E);
187
  void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
188
  void VisitLambdaExpr(LambdaExpr *E);
189
  void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
190
  void VisitExprWithCleanups(ExprWithCleanups *E);
191
  void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
192
0
  void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
193
  void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
194
  void VisitOpaqueValueExpr(OpaqueValueExpr *E);
195
196
28
  void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
197
28
    if (E->isGLValue()) {
198
0
      LValue LV = CGF.EmitPseudoObjectLValue(E);
199
0
      return EmitFinalDestCopy(E->getType(), LV);
200
0
    }
201
28
202
28
    CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
203
28
  }
204
205
  void VisitVAArgExpr(VAArgExpr *E);
206
207
  void EmitInitializationToLValue(Expr *E, LValue Address);
208
  void EmitNullInitializationToLValue(LValue Address);
209
  //  case Expr::ChooseExprClass:
210
1
  void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
211
15
  void VisitAtomicExpr(AtomicExpr *E) {
212
15
    RValue Res = CGF.EmitAtomicExpr(E);
213
15
    EmitFinalDestCopy(E->getType(), Res);
214
15
  }
215
};
216
}  // end anonymous namespace.
217
218
//===----------------------------------------------------------------------===//
219
//                                Utilities
220
//===----------------------------------------------------------------------===//
221
222
/// EmitAggLoadOfLValue - Given an expression with aggregate type that
223
/// represents a value lvalue, this method emits the address of the lvalue,
224
/// then loads the result into DestPtr.
225
2.58k
void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
226
2.58k
  LValue LV = CGF.EmitLValue(E);
227
2.58k
228
  // If the type of the l-value is atomic, then do an atomic load.
229
2.58k
  if (LV.getType()->isAtomicType() || 
CGF.LValueIsSuitableForInlineAtomic(LV)2.57k
) {
230
11
    CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
231
11
    return;
232
11
  }
233
2.56k
234
2.56k
  EmitFinalDestCopy(E->getType(), LV);
235
2.56k
}
236
237
/// True if the given aggregate type requires special GC API calls.
238
24
bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
239
  // Only record types have members that might require garbage collection.
240
24
  const RecordType *RecordTy = T->getAs<RecordType>();
241
24
  if (!RecordTy) 
return false0
;
242
24
243
  // Don't mess with non-trivial C++ types.
244
24
  RecordDecl *Record = RecordTy->getDecl();
245
24
  if (isa<CXXRecordDecl>(Record) &&
246
5
      (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
247
5
       !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
248
0
    return false;
249
24
250
  // Check whether the type has an object member.
251
24
  return Record->hasObjectMember();
252
24
}
253
254
void AggExprEmitter::withReturnValueSlot(
255
6.61k
    const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
256
6.61k
  QualType RetTy = E->getType();
257
6.61k
  bool RequiresDestruction =
258
6.61k
      !Dest.isExternallyDestructed() &&
259
2.12k
      RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct;
260
6.61k
261
  // If it makes no observable difference, save a memcpy + temporary.
262
  //
263
  // We need to always provide our own temporary if destruction is required.
264
  // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
265
  // its lifetime before we have the chance to emit a proper destructor call.
266
6.61k
  bool UseTemp = Dest.isPotentiallyAliased() || 
Dest.requiresGCollection()6.43k
||
267
6.43k
                 (RequiresDestruction && 
!Dest.getAddress().isValid()12
);
268
6.61k
269
6.61k
  Address RetAddr = Address::invalid();
270
6.61k
  Address RetAllocaAddr = Address::invalid();
271
6.61k
272
6.61k
  EHScopeStack::stable_iterator LifetimeEndBlock;
273
6.61k
  llvm::Value *LifetimeSizePtr = nullptr;
274
6.61k
  llvm::IntrinsicInst *LifetimeStartInst = nullptr;
275
6.61k
  if (!UseTemp) {
276
6.42k
    RetAddr = Dest.getAddress();
277
194
  } else {
278
194
    RetAddr = CGF.CreateMemTemp(RetTy, "tmp", &RetAllocaAddr);
279
194
    uint64_t Size =
280
194
        CGF.CGM.getDataLayout().getTypeAllocSize(CGF.ConvertTypeForMem(RetTy));
281
194
    LifetimeSizePtr = CGF.EmitLifetimeStart(Size, RetAllocaAddr.getPointer());
282
194
    if (LifetimeSizePtr) {
283
12
      LifetimeStartInst =
284
12
          cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
285
12
      assert(LifetimeStartInst->getIntrinsicID() ==
286
12
                 llvm::Intrinsic::lifetime_start &&
287
12
             "Last insertion wasn't a lifetime.start?");
288
12
289
12
      CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
290
12
          NormalEHLifetimeMarker, RetAllocaAddr, LifetimeSizePtr);
291
12
      LifetimeEndBlock = CGF.EHStack.stable_begin();
292
12
    }
293
194
  }
294
6.61k
295
6.61k
  RValue Src =
296
6.61k
      EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
297
6.61k
                               Dest.isExternallyDestructed()));
298
6.61k
299
6.61k
  if (!UseTemp)
300
6.42k
    return;
301
194
302
194
  assert(Dest.getPointer() != Src.getAggregatePointer());
303
194
  EmitFinalDestCopy(E->getType(), Src);
304
194
305
194
  if (!RequiresDestruction && 
LifetimeStartInst182
) {
306
    // If there's no dtor to run, the copy was the last use of our temporary.
307
    // Since we're not guaranteed to be in an ExprWithCleanups, clean up
308
    // eagerly.
309
10
    CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
310
10
    CGF.EmitLifetimeEnd(LifetimeSizePtr, RetAllocaAddr.getPointer());
311
10
  }
312
194
}
313
314
/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
315
213
void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
316
213
  assert(src.isAggregate() && "value must be aggregate value!");
317
213
  LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
318
213
  EmitFinalDestCopy(type, srcLV, EVK_RValue);
319
213
}
320
321
/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
322
void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src,
323
3.57k
                                       ExprValueKind SrcValueKind) {
324
  // If Dest is ignored, then we're evaluating an aggregate expression
325
  // in a context that doesn't care about the result.  Note that loads
326
  // from volatile l-values force the existence of a non-ignored
327
  // destination.
328
3.57k
  if (Dest.isIgnored())
329
477
    return;
330
3.09k
331
  // Copy non-trivial C structs here.
332
3.09k
  LValue DstLV = CGF.MakeAddrLValue(
333
3.07k
      Dest.getAddress(), Dest.isVolatile() ? 
type.withVolatile()19
: type);
334
3.09k
335
3.09k
  if (SrcValueKind == EVK_RValue) {
336
201
    if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
337
8
      if (Dest.isPotentiallyAliased())
338
8
        CGF.callCStructMoveAssignmentOperator(DstLV, src);
339
0
      else
340
0
        CGF.callCStructMoveConstructor(DstLV, src);
341
8
      return;
342
8
    }
343
2.89k
  } else {
344
2.89k
    if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
345
60
      if (Dest.isPotentiallyAliased())
346
16
        CGF.callCStructCopyAssignmentOperator(DstLV, src);
347
44
      else
348
44
        CGF.callCStructCopyConstructor(DstLV, src);
349
60
      return;
350
60
    }
351
3.02k
  }
352
3.02k
353
3.02k
  AggValueSlot srcAgg = AggValueSlot::forLValue(
354
3.02k
      src, CGF, AggValueSlot::IsDestructed, needsGC(type),
355
3.02k
      AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
356
3.02k
  EmitCopy(type, Dest, srcAgg);
357
3.02k
}
358
359
/// Perform a copy from the source into the destination.
360
///
361
/// \param type - the type of the aggregate being copied; qualifiers are
362
///   ignored
363
void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
364
3.03k
                              const AggValueSlot &src) {
365
3.03k
  if (dest.requiresGCollection()) {
366
6
    CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
367
6
    llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
368
6
    CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
369
6
                                                      dest.getAddress(),
370
6
                                                      src.getAddress(),
371
6
                                                      size);
372
6
    return;
373
6
  }
374
3.02k
375
  // If the result of the assignment is used, copy the LHS there also.
376
  // It's volatile if either side is.  Use the minimum alignment of
377
  // the two sides.
378
3.02k
  LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
379
3.02k
  LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
380
3.02k
  CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
381
3.02k
                        dest.isVolatile() || 
src.isVolatile()3.00k
);
382
3.02k
}
383
384
/// Emit the initializer for a std::initializer_list initialized with a
385
/// real initializer list.
386
void
387
161
AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
388
  // Emit an array containing the elements.  The array is externally destructed
389
  // if the std::initializer_list object is.
390
161
  ASTContext &Ctx = CGF.getContext();
391
161
  LValue Array = CGF.EmitLValue(E->getSubExpr());
392
161
  assert(Array.isSimple() && "initializer_list array not a simple lvalue");
393
161
  Address ArrayPtr = Array.getAddress(CGF);
394
161
395
161
  const ConstantArrayType *ArrayType =
396
161
      Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
397
161
  assert(ArrayType && "std::initializer_list constructed from non-array");
398
161
399
  // FIXME: Perform the checks on the field types in SemaInit.
400
161
  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
401
161
  RecordDecl::field_iterator Field = Record->field_begin();
402
161
  if (Field == Record->field_end()) {
403
1
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
404
1
    return;
405
1
  }
406
160
407
  // Start pointer.
408
160
  if (!Field->getType()->isPointerType() ||
409
160
      !Ctx.hasSameType(Field->getType()->getPointeeType(),
410
0
                       ArrayType->getElementType())) {
411
0
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
412
0
    return;
413
0
  }
414
160
415
160
  AggValueSlot Dest = EnsureSlot(E->getType());
416
160
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
417
160
  LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
418
160
  llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
419
160
  llvm::Value *IdxStart[] = { Zero, Zero };
420
160
  llvm::Value *ArrayStart =
421
160
      Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart");
422
160
  CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
423
160
  ++Field;
424
160
425
160
  if (Field == Record->field_end()) {
426
0
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
427
0
    return;
428
0
  }
429
160
430
160
  llvm::Value *Size = Builder.getInt(ArrayType->getSize());
431
160
  LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
432
160
  if (Field->getType()->isPointerType() &&
433
7
      Ctx.hasSameType(Field->getType()->getPointeeType(),
434
7
                      ArrayType->getElementType())) {
435
    // End pointer.
436
7
    llvm::Value *IdxEnd[] = { Zero, Size };
437
7
    llvm::Value *ArrayEnd =
438
7
        Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend");
439
7
    CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
440
153
  } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
441
    // Length.
442
153
    CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
443
0
  } else {
444
0
    CGF.ErrorUnsupported(E, "weird std::initializer_list");
445
0
    return;
446
0
  }
447
160
}
448
449
/// Determine if E is a trivial array filler, that is, one that is
450
/// equivalent to zero-initialization.
451
1.60k
static bool isTrivialFiller(Expr *E) {
452
1.60k
  if (!E)
453
1.53k
    return true;
454
64
455
64
  if (isa<ImplicitValueInitExpr>(E))
456
33
    return true;
457
31
458
31
  if (auto *ILE = dyn_cast<InitListExpr>(E)) {
459
5
    if (ILE->getNumInits())
460
4
      return false;
461
1
    return isTrivialFiller(ILE->getArrayFiller());
462
1
  }
463
26
464
26
  if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
465
23
    return Cons->getConstructor()->isDefaultConstructor() &&
466
21
           Cons->getConstructor()->isTrivial();
467
3
468
  // FIXME: Are there other cases where we can avoid emitting an initializer?
469
3
  return false;
470
3
}
471
472
/// Emit initialization of an array from an initializer list.
473
void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
474
1.62k
                                   QualType ArrayQTy, InitListExpr *E) {
475
1.62k
  uint64_t NumInitElements = E->getNumInits();
476
1.62k
477
1.62k
  uint64_t NumArrayElements = AType->getNumElements();
478
1.62k
  assert(NumInitElements <= NumArrayElements);
479
1.62k
480
1.62k
  QualType elementType =
481
1.62k
      CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
482
1.62k
483
  // DestPtr is an array*.  Construct an elementType* by drilling
484
  // down a level.
485
1.62k
  llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
486
1.62k
  llvm::Value *indices[] = { zero, zero };
487
1.62k
  llvm::Value *begin =
488
1.62k
    Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin");
489
1.62k
490
1.62k
  CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
491
1.62k
  CharUnits elementAlign =
492
1.62k
    DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
493
1.62k
494
  // Consider initializing the array by copying from a global. For this to be
495
  // more efficient than per-element initialization, the size of the elements
496
  // with explicit initializers should be large enough.
497
1.62k
  if (NumInitElements * elementSize.getQuantity() > 16 &&
498
127
      elementType.isTriviallyCopyableType(CGF.getContext())) {
499
84
    CodeGen::CodeGenModule &CGM = CGF.CGM;
500
84
    ConstantEmitter Emitter(CGF);
501
84
    LangAS AS = ArrayQTy.getAddressSpace();
502
84
    if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) {
503
28
      auto GV = new llvm::GlobalVariable(
504
28
          CGM.getModule(), C->getType(),
505
28
          CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true),
506
28
          llvm::GlobalValue::PrivateLinkage, C, "constinit",
507
28
          /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
508
28
          CGM.getContext().getTargetAddressSpace(AS));
509
28
      Emitter.finalize(GV);
510
28
      CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
511
28
      GV->setAlignment(Align.getAsAlign());
512
28
      EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align));
513
28
      return;
514
28
    }
515
1.60k
  }
516
1.60k
517
  // Exception safety requires us to destroy all the
518
  // already-constructed members if an initializer throws.
519
  // For that, we'll need an EH cleanup.
520
1.60k
  QualType::DestructionKind dtorKind = elementType.isDestructedType();
521
1.60k
  Address endOfInit = Address::invalid();
522
1.60k
  EHScopeStack::stable_iterator cleanup;
523
1.60k
  llvm::Instruction *cleanupDominator = nullptr;
524
1.60k
  if (CGF.needsEHCleanup(dtorKind)) {
525
    // In principle we could tell the cleanup where we are more
526
    // directly, but the control flow can get so varied here that it
527
    // would actually be quite complex.  Therefore we go through an
528
    // alloca.
529
70
    endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
530
70
                                     "arrayinit.endOfInit");
531
70
    cleanupDominator = Builder.CreateStore(begin, endOfInit);
532
70
    CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
533
70
                                         elementAlign,
534
70
                                         CGF.getDestroyer(dtorKind));
535
70
    cleanup = CGF.EHStack.stable_begin();
536
70
537
  // Otherwise, remember that we didn't need a cleanup.
538
1.53k
  } else {
539
1.53k
    dtorKind = QualType::DK_none;
540
1.53k
  }
541
1.60k
542
1.60k
  llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
543
1.60k
544
  // The 'current element to initialize'.  The invariants on this
545
  // variable are complicated.  Essentially, after each iteration of
546
  // the loop, it points to the last initialized element, except
547
  // that it points to the beginning of the array before any
548
  // elements have been initialized.
549
1.60k
  llvm::Value *element = begin;
550
1.60k
551
  // Emit the explicit initializers.
552
4.88k
  for (uint64_t i = 0; i != NumInitElements; 
++i3.28k
) {
553
    // Advance to the next element.
554
3.28k
    if (i > 0) {
555
1.70k
      element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
556
1.70k
557
      // Tell the cleanup that it needs to destroy up to this
558
      // element.  TODO: some of these stores can be trivially
559
      // observed to be unnecessary.
560
1.70k
      if (endOfInit.isValid()) 
Builder.CreateStore(element, endOfInit)110
;
561
1.70k
    }
562
3.28k
563
3.28k
    LValue elementLV =
564
3.28k
      CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
565
3.28k
    EmitInitializationToLValue(E->getInit(i), elementLV);
566
3.28k
  }
567
1.60k
568
  // Check whether there's a non-trivial array-fill expression.
569
1.60k
  Expr *filler = E->getArrayFiller();
570
1.60k
  bool hasTrivialFiller = isTrivialFiller(filler);
571
1.60k
572
  // Any remaining elements need to be zero-initialized, possibly
573
  // using the filler expression.  We can skip this if the we're
574
  // emitting to zeroed memory.
575
1.60k
  if (NumInitElements != NumArrayElements &&
576
58
      !(Dest.isZeroed() && 
hasTrivialFiller27
&&
577
38
        
CGF.getTypes().isZeroInitializable(elementType)20
)) {
578
38
579
    // Use an actual loop.  This is basically
580
    //   do { *array++ = filler; } while (array != end);
581
38
582
    // Advance to the start of the rest of the array.
583
38
    if (NumInitElements) {
584
19
      element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
585
19
      if (endOfInit.isValid()) 
Builder.CreateStore(element, endOfInit)2
;
586
19
    }
587
38
588
    // Compute the end of the array.
589
38
    llvm::Value *end = Builder.CreateInBoundsGEP(begin,
590
38
                      llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
591
38
                                                 "arrayinit.end");
592
38
593
38
    llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
594
38
    llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
595
38
596
    // Jump into the body.
597
38
    CGF.EmitBlock(bodyBB);
598
38
    llvm::PHINode *currentElement =
599
38
      Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
600
38
    currentElement->addIncoming(element, entryBB);
601
38
602
    // Emit the actual filler expression.
603
38
    {
604
      // C++1z [class.temporary]p5:
605
      //   when a default constructor is called to initialize an element of
606
      //   an array with no corresponding initializer [...] the destruction of
607
      //   every temporary created in a default argument is sequenced before
608
      //   the construction of the next array element, if any
609
38
      CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
610
38
      LValue elementLV =
611
38
        CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType);
612
38
      if (filler)
613
38
        EmitInitializationToLValue(filler, elementLV);
614
0
      else
615
0
        EmitNullInitializationToLValue(elementLV);
616
38
    }
617
38
618
    // Move on to the next element.
619
38
    llvm::Value *nextElement =
620
38
      Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
621
38
622
    // Tell the EH cleanup that we finished with the last element.
623
38
    if (endOfInit.isValid()) 
Builder.CreateStore(nextElement, endOfInit)2
;
624
38
625
    // Leave the loop if we're done.
626
38
    llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
627
38
                                             "arrayinit.done");
628
38
    llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
629
38
    Builder.CreateCondBr(done, endBB, bodyBB);
630
38
    currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
631
38
632
38
    CGF.EmitBlock(endBB);
633
38
  }
634
1.60k
635
  // Leave the partial-array cleanup if we entered one.
636
1.60k
  if (dtorKind) 
CGF.DeactivateCleanupBlock(cleanup, cleanupDominator)70
;
637
1.60k
}
638
639
//===----------------------------------------------------------------------===//
640
//                            Visitor Methods
641
//===----------------------------------------------------------------------===//
642
643
12.1k
void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
644
12.1k
  Visit(E->getSubExpr());
645
12.1k
}
646
647
20
void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
648
  // If this is a unique OVE, just visit its source expression.
649
20
  if (e->isUnique())
650
7
    Visit(e->getSourceExpr());
651
13
  else
652
13
    EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
653
20
}
654
655
void
656
641
AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
657
641
  if (Dest.isPotentiallyAliased() &&
658
20
      E->getType().isPODType(CGF.getContext())) {
659
    // For a POD type, just emit a load of the lvalue + a copy, because our
660
    // compound literal might alias the destination.
661
20
    EmitAggLoadOfLValue(E);
662
20
    return;
663
20
  }
664
621
665
621
  AggValueSlot Slot = EnsureSlot(E->getType());
666
621
667
  // Block-scope compound literals are destroyed at the end of the enclosing
668
  // scope in C.
669
621
  bool Destruct =
670
621
      !CGF.getLangOpts().CPlusPlus && 
!Slot.isExternallyDestructed()321
;
671
621
  if (Destruct)
672
20
    Slot.setExternallyDestructed();
673
621
674
621
  CGF.EmitAggExpr(E->getInitializer(), Slot);
675
621
676
621
  if (Destruct)
677
20
    if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
678
0
      CGF.pushLifetimeExtendedDestroy(
679
0
          CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
680
0
          CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
681
621
}
682
683
/// Attempt to look through various unimportant expressions to find a
684
/// cast of the given kind.
685
11
static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
686
11
  op = op->IgnoreParenNoopCasts(ctx);
687
11
  if (auto castE = dyn_cast<CastExpr>(op)) {
688
0
    if (castE->getCastKind() == kind)
689
0
      return castE->getSubExpr();
690
11
  }
691
11
  return nullptr;
692
11
}
693
694
12.8k
void AggExprEmitter::VisitCastExpr(CastExpr *E) {
695
12.8k
  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
696
3.39k
    CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
697
12.8k
  switch (E->getCastKind()) {
698
0
  case CK_Dynamic: {
699
    // FIXME: Can this actually happen? We have no test coverage for it.
700
0
    assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
701
0
    LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
702
0
                                      CodeGenFunction::TCK_Load);
703
    // FIXME: Do we also need to handle property references here?
704
0
    if (LV.isSimple())
705
0
      CGF.EmitDynamicCast(LV.getAddress(CGF), cast<CXXDynamicCastExpr>(E));
706
0
    else
707
0
      CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
708
0
709
0
    if (!Dest.isIgnored())
710
0
      CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
711
0
    break;
712
0
  }
713
0
714
7
  case CK_ToUnion: {
715
    // Evaluate even if the destination is ignored.
716
7
    if (Dest.isIgnored()) {
717
1
      CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
718
1
                      /*ignoreResult=*/true);
719
1
      break;
720
1
    }
721
6
722
    // GCC union extension
723
6
    QualType Ty = E->getSubExpr()->getType();
724
6
    Address CastPtr =
725
6
      Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
726
6
    EmitInitializationToLValue(E->getSubExpr(),
727
6
                               CGF.MakeAddrLValue(CastPtr, Ty));
728
6
    break;
729
6
  }
730
6
731
4
  case CK_LValueToRValueBitCast: {
732
4
    if (Dest.isIgnored()) {
733
0
      CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
734
0
                      /*ignoreResult=*/true);
735
0
      break;
736
0
    }
737
4
738
4
    LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
739
4
    Address SourceAddress =
740
4
        Builder.CreateElementBitCast(SourceLV.getAddress(CGF), CGF.Int8Ty);
741
4
    Address DestAddress =
742
4
        Builder.CreateElementBitCast(Dest.getAddress(), CGF.Int8Ty);
743
4
    llvm::Value *SizeVal = llvm::ConstantInt::get(
744
4
        CGF.SizeTy,
745
4
        CGF.getContext().getTypeSizeInChars(E->getType()).getQuantity());
746
4
    Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
747
4
    break;
748
4
  }
749
4
750
0
  case CK_DerivedToBase:
751
0
  case CK_BaseToDerived:
752
0
  case CK_UncheckedDerivedToBase: {
753
0
    llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
754
0
                "should have been unpacked before we got here");
755
0
  }
756
0
757
25
  case CK_NonAtomicToAtomic:
758
25
  case CK_AtomicToNonAtomic: {
759
25
    bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
760
25
761
    // Determine the atomic and value types.
762
25
    QualType atomicType = E->getSubExpr()->getType();
763
25
    QualType valueType = E->getType();
764
25
    if (isToAtomic) 
std::swap(atomicType, valueType)17
;
765
25
766
25
    assert(atomicType->isAtomicType());
767
25
    assert(CGF.getContext().hasSameUnqualifiedType(valueType,
768
25
                          atomicType->castAs<AtomicType>()->getValueType()));
769
25
770
    // Just recurse normally if we're ignoring the result or the
771
    // atomic type doesn't change representation.
772
25
    if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
773
14
      return Visit(E->getSubExpr());
774
14
    }
775
11
776
11
    CastKind peepholeTarget =
777
7
      (isToAtomic ? CK_AtomicToNonAtomic : 
CK_NonAtomicToAtomic4
);
778
11
779
    // These two cases are reverses of each other; try to peephole them.
780
11
    if (Expr *op =
781
0
            findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
782
0
      assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
783
0
                                                     E->getType()) &&
784
0
           "peephole significantly changed types?");
785
0
      return Visit(op);
786
0
    }
787
11
788
    // If we're converting an r-value of non-atomic type to an r-value
789
    // of atomic type, just emit directly into the relevant sub-object.
790
11
    if (isToAtomic) {
791
7
      AggValueSlot valueDest = Dest;
792
7
      if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
793
        // Zero-initialize.  (Strictly speaking, we only need to initialize
794
        // the padding at the end, but this is simpler.)
795
7
        if (!Dest.isZeroed())
796
7
          CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
797
7
798
        // Build a GEP to refer to the subobject.
799
7
        Address valueAddr =
800
7
            CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
801
7
        valueDest = AggValueSlot::forAddr(valueAddr,
802
7
                                          valueDest.getQualifiers(),
803
7
                                          valueDest.isExternallyDestructed(),
804
7
                                          valueDest.requiresGCollection(),
805
7
                                          valueDest.isPotentiallyAliased(),
806
7
                                          AggValueSlot::DoesNotOverlap,
807
7
                                          AggValueSlot::IsZeroed);
808
7
      }
809
7
810
7
      CGF.EmitAggExpr(E->getSubExpr(), valueDest);
811
7
      return;
812
7
    }
813
4
814
    // Otherwise, we're converting an atomic type to a non-atomic type.
815
    // Make an atomic temporary, emit into that, and then copy the value out.
816
4
    AggValueSlot atomicSlot =
817
4
      CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
818
4
    CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
819
4
820
4
    Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
821
4
    RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
822
4
    return EmitFinalDestCopy(valueType, rvalue);
823
4
  }
824
0
  case CK_AddressSpaceConversion:
825
0
     return Visit(E->getSubExpr());
826
4
827
2.76k
  case CK_LValueToRValue:
828
    // If we're loading from a volatile type, force the destination
829
    // into existence.
830
2.76k
    if (E->getSubExpr()->getType().isVolatileQualified()) {
831
19
      bool Destruct =
832
19
          !Dest.isExternallyDestructed() &&
833
10
          E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct;
834
19
      if (Destruct)
835
2
        Dest.setExternallyDestructed();
836
19
      EnsureDest(E->getType());
837
19
      Visit(E->getSubExpr());
838
19
839
19
      if (Destruct)
840
2
        CGF.pushDestroy(QualType::DK_nontrivial_c_struct, Dest.getAddress(),
841
2
                        E->getType());
842
19
843
19
      return;
844
19
    }
845
2.74k
846
2.74k
    LLVM_FALLTHROUGH;
847
2.74k
848
2.74k
849
12.8k
  case CK_NoOp:
850
12.8k
  case CK_UserDefinedConversion:
851
12.8k
  case CK_ConstructorConversion:
852
12.8k
    assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
853
12.8k
                                                   E->getType()) &&
854
12.8k
           "Implicit cast types must be compatible");
855
12.8k
    Visit(E->getSubExpr());
856
12.8k
    break;
857
12.8k
858
0
  case CK_LValueBitCast:
859
0
    llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
860
12.8k
861
0
  case CK_Dependent:
862
0
  case CK_BitCast:
863
0
  case CK_ArrayToPointerDecay:
864
0
  case CK_FunctionToPointerDecay:
865
0
  case CK_NullToPointer:
866
0
  case CK_NullToMemberPointer:
867
0
  case CK_BaseToDerivedMemberPointer:
868
0
  case CK_DerivedToBaseMemberPointer:
869
0
  case CK_MemberPointerToBoolean:
870
0
  case CK_ReinterpretMemberPointer:
871
0
  case CK_IntegralToPointer:
872
0
  case CK_PointerToIntegral:
873
0
  case CK_PointerToBoolean:
874
0
  case CK_ToVoid:
875
0
  case CK_VectorSplat:
876
0
  case CK_IntegralCast:
877
0
  case CK_BooleanToSignedIntegral:
878
0
  case CK_IntegralToBoolean:
879
0
  case CK_IntegralToFloating:
880
0
  case CK_FloatingToIntegral:
881
0
  case CK_FloatingToBoolean:
882
0
  case CK_FloatingCast:
883
0
  case CK_CPointerToObjCPointerCast:
884
0
  case CK_BlockPointerToObjCPointerCast:
885
0
  case CK_AnyPointerToBlockPointerCast:
886
0
  case CK_ObjCObjectLValueCast:
887
0
  case CK_FloatingRealToComplex:
888
0
  case CK_FloatingComplexToReal:
889
0
  case CK_FloatingComplexToBoolean:
890
0
  case CK_FloatingComplexCast:
891
0
  case CK_FloatingComplexToIntegralComplex:
892
0
  case CK_IntegralRealToComplex:
893
0
  case CK_IntegralComplexToReal:
894
0
  case CK_IntegralComplexToBoolean:
895
0
  case CK_IntegralComplexCast:
896
0
  case CK_IntegralComplexToFloatingComplex:
897
0
  case CK_ARCProduceObject:
898
0
  case CK_ARCConsumeObject:
899
0
  case CK_ARCReclaimReturnedObject:
900
0
  case CK_ARCExtendBlockObject:
901
0
  case CK_CopyAndAutoreleaseBlockObject:
902
0
  case CK_BuiltinFnToFnPtr:
903
0
  case CK_ZeroToOCLOpaqueType:
904
0
905
0
  case CK_IntToOCLSampler:
906
0
  case CK_FixedPointCast:
907
0
  case CK_FixedPointToBoolean:
908
0
  case CK_FixedPointToIntegral:
909
0
  case CK_IntegralToFixedPoint:
910
0
    llvm_unreachable("cast kind invalid for aggregate types");
911
12.8k
  }
912
12.8k
}
913
914
6.55k
void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
915
6.55k
  if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
916
0
    EmitAggLoadOfLValue(E);
917
0
    return;
918
0
  }
919
6.55k
920
6.55k
  withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
921
6.55k
    return CGF.EmitCallExpr(E, Slot);
922
6.55k
  });
923
6.55k
}
924
925
69
void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
926
69
  withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
927
69
    return CGF.EmitObjCMessageExpr(E, Slot);
928
69
  });
929
69
}
930
931
43
void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
932
43
  CGF.EmitIgnoredExpr(E->getLHS());
933
43
  Visit(E->getRHS());
934
43
}
935
936
645
void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
937
645
  CodeGenFunction::StmtExprEvaluation eval(CGF);
938
645
  CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
939
645
}
940
941
enum CompareKind {
942
  CK_Less,
943
  CK_Greater,
944
  CK_Equal,
945
};
946
947
static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
948
                                const BinaryOperator *E, llvm::Value *LHS,
949
                                llvm::Value *RHS, CompareKind Kind,
950
27
                                const char *NameSuffix = "") {
951
27
  QualType ArgTy = E->getLHS()->getType();
952
27
  if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
953
0
    ArgTy = CT->getElementType();
954
27
955
27
  if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
956
0
    assert(Kind == CK_Equal &&
957
0
           "member pointers may only be compared for equality");
958
0
    return CGF.CGM.getCXXABI().EmitMemberPointerComparison(
959
0
        CGF, LHS, RHS, MPT, /*IsInequality*/ false);
960
0
  }
961
27
962
  // Compute the comparison instructions for the specified comparison kind.
963
27
  struct CmpInstInfo {
964
27
    const char *Name;
965
27
    llvm::CmpInst::Predicate FCmp;
966
27
    llvm::CmpInst::Predicate SCmp;
967
27
    llvm::CmpInst::Predicate UCmp;
968
27
  };
969
27
  CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
970
27
    using FI = llvm::FCmpInst;
971
27
    using II = llvm::ICmpInst;
972
27
    switch (Kind) {
973
13
    case CK_Less:
974
13
      return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
975
1
    case CK_Greater:
976
1
      return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
977
13
    case CK_Equal:
978
13
      return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
979
0
    }
980
0
    llvm_unreachable("Unrecognised CompareKind enum");
981
0
  }();
982
27
983
27
  if (ArgTy->hasFloatingRepresentation())
984
3
    return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
985
3
                              llvm::Twine(InstInfo.Name) + NameSuffix);
986
24
  if (ArgTy->isIntegralOrEnumerationType() || 
ArgTy->isPointerType()2
) {
987
24
    auto Inst =
988
14
        ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : 
InstInfo.UCmp10
;
989
24
    return Builder.CreateICmp(Inst, LHS, RHS,
990
24
                              llvm::Twine(InstInfo.Name) + NameSuffix);
991
24
  }
992
0
993
0
  llvm_unreachable("unsupported aggregate binary expression should have "
994
0
                   "already been handled");
995
0
}
996
997
13
void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
998
13
  using llvm::BasicBlock;
999
13
  using llvm::PHINode;
1000
13
  using llvm::Value;
1001
13
  assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
1002
13
                                      E->getRHS()->getType()));
1003
13
  const ComparisonCategoryInfo &CmpInfo =
1004
13
      CGF.getContext().CompCategories.getInfoForType(E->getType());
1005
13
  assert(CmpInfo.Record->isTriviallyCopyable() &&
1006
13
         "cannot copy non-trivially copyable aggregate");
1007
13
1008
13
  QualType ArgTy = E->getLHS()->getType();
1009
13
1010
13
  if (!ArgTy->isIntegralOrEnumerationType() && 
!ArgTy->isRealFloatingType()2
&&
1011
1
      !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
1012
0
      !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
1013
0
    return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
1014
0
  }
1015
13
  bool IsComplex = ArgTy->isAnyComplexType();
1016
13
1017
  // Evaluate the operands to the expression and extract their values.
1018
26
  auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
1019
26
    RValue RV = CGF.EmitAnyExpr(E);
1020
26
    if (RV.isScalar())
1021
26
      return {RV.getScalarVal(), nullptr};
1022
0
    if (RV.isAggregate())
1023
0
      return {RV.getAggregatePointer(), nullptr};
1024
0
    assert(RV.isComplex());
1025
0
    return RV.getComplexVal();
1026
0
  };
1027
13
  auto LHSValues = EmitOperand(E->getLHS()),
1028
13
       RHSValues = EmitOperand(E->getRHS());
1029
13
1030
27
  auto EmitCmp = [&](CompareKind K) {
1031
27
    Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
1032
27
                             K, IsComplex ? 
".r"0
: "");
1033
27
    if (!IsComplex)
1034
27
      return Cmp;
1035
0
    assert(K == CompareKind::CK_Equal);
1036
0
    Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
1037
0
                                 RHSValues.second, K, ".i");
1038
0
    return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
1039
0
  };
1040
40
  auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
1041
40
    return Builder.getInt(VInfo->getIntValue());
1042
40
  };
1043
13
1044
13
  Value *Select;
1045
13
  if (ArgTy->isNullPtrType()) {
1046
0
    Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
1047
13
  } else if (!CmpInfo.isPartial()) {
1048
12
    Value *SelectOne =
1049
12
        Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
1050
12
                             EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
1051
12
    Select = Builder.CreateSelect(EmitCmp(CK_Equal),
1052
12
                                  EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1053
12
                                  SelectOne, "sel.eq");
1054
1
  } else {
1055
1
    Value *SelectEq = Builder.CreateSelect(
1056
1
        EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1057
1
        EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
1058
1
    Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
1059
1
                                           EmitCmpRes(CmpInfo.getGreater()),
1060
1
                                           SelectEq, "sel.gt");
1061
1
    Select = Builder.CreateSelect(
1062
1
        EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
1063
1
  }
1064
  // Create the return value in the destination slot.
1065
13
  EnsureDest(E->getType());
1066
13
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1067
13
1068
  // Emit the address of the first (and only) field in the comparison category
1069
  // type, and initialize it from the constant integer value selected above.
1070
13
  LValue FieldLV = CGF.EmitLValueForFieldInitialization(
1071
13
      DestLV, *CmpInfo.Record->field_begin());
1072
13
  CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
1073
13
1074
  // All done! The result is in the Dest slot.
1075
13
}
1076
1077
0
void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
1078
0
  if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
1079
0
    VisitPointerToDataMemberBinaryOperator(E);
1080
0
  else
1081
0
    CGF.ErrorUnsupported(E, "aggregate binary expression");
1082
0
}
1083
1084
void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
1085
0
                                                    const BinaryOperator *E) {
1086
0
  LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
1087
0
  EmitFinalDestCopy(E->getType(), LV);
1088
0
}
1089
1090
/// Is the value of the given expression possibly a reference to or
1091
/// into a __block variable?
1092
686
static bool isBlockVarRef(const Expr *E) {
1093
  // Make sure we look through parens.
1094
686
  E = E->IgnoreParens();
1095
686
1096
  // Check for a direct reference to a __block variable.
1097
686
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1098
238
    const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
1099
238
    return (var && var->hasAttr<BlocksAttr>());
1100
238
  }
1101
448
1102
  // More complicated stuff.
1103
448
1104
  // Binary operators.
1105
448
  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
1106
    // For an assignment or pointer-to-member operation, just care
1107
    // about the LHS.
1108
0
    if (op->isAssignmentOp() || op->isPtrMemOp())
1109
0
      return isBlockVarRef(op->getLHS());
1110
0
1111
    // For a comma, just care about the RHS.
1112
0
    if (op->getOpcode() == BO_Comma)
1113
0
      return isBlockVarRef(op->getRHS());
1114
0
1115
    // FIXME: pointer arithmetic?
1116
0
    return false;
1117
0
1118
  // Check both sides of a conditional operator.
1119
448
  } else if (const AbstractConditionalOperator *op
1120
0
               = dyn_cast<AbstractConditionalOperator>(E)) {
1121
0
    return isBlockVarRef(op->getTrueExpr())
1122
0
        || isBlockVarRef(op->getFalseExpr());
1123
0
1124
  // OVEs are required to support BinaryConditionalOperators.
1125
448
  } else if (const OpaqueValueExpr *op
1126
0
               = dyn_cast<OpaqueValueExpr>(E)) {
1127
0
    if (const Expr *src = op->getSourceExpr())
1128
0
      return isBlockVarRef(src);
1129
448
1130
  // Casts are necessary to get things like (*(int*)&var) = foo().
1131
  // We don't really care about the kind of cast here, except
1132
  // we don't want to look through l2r casts, because it's okay
1133
  // to get the *value* in a __block variable.
1134
448
  } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
1135
225
    if (cast->getCastKind() == CK_LValueToRValue)
1136
211
      return false;
1137
14
    return isBlockVarRef(cast->getSubExpr());
1138
14
1139
  // Handle unary operators.  Again, just aggressively look through
1140
  // it, ignoring the operation.
1141
223
  } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
1142
198
    return isBlockVarRef(uop->getSubExpr());
1143
198
1144
  // Look into the base of a field access.
1145
25
  } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
1146
5
    return isBlockVarRef(mem->getBase());
1147
5
1148
  // Look into the base of a subscript.
1149
20
  } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
1150
13
    return isBlockVarRef(sub->getBase());
1151
13
  }
1152
7
1153
7
  return false;
1154
7
}
1155
1156
456
void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1157
  // For an assignment to work, the value on the right has
1158
  // to be compatible with the value on the left.
1159
456
  assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1160
456
                                                 E->getRHS()->getType())
1161
456
         && "Invalid assignment");
1162
456
1163
  // If the LHS might be a __block variable, and the RHS can
1164
  // potentially cause a block copy, we need to evaluate the RHS first
1165
  // so that the assignment goes the right place.
1166
  // This is pretty semantically fragile.
1167
456
  if (isBlockVarRef(E->getLHS()) &&
1168
3
      E->getRHS()->HasSideEffects(CGF.getContext())) {
1169
    // Ensure that we have a destination, and evaluate the RHS into that.
1170
3
    EnsureDest(E->getRHS()->getType());
1171
3
    Visit(E->getRHS());
1172
3
1173
    // Now emit the LHS and copy into it.
1174
3
    LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1175
3
1176
    // That copy is an atomic copy if the LHS is atomic.
1177
3
    if (LHS.getType()->isAtomicType() ||
1178
3
        CGF.LValueIsSuitableForInlineAtomic(LHS)) {
1179
0
      CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1180
0
      return;
1181
0
    }
1182
3
1183
3
    EmitCopy(E->getLHS()->getType(),
1184
3
             AggValueSlot::forLValue(LHS, CGF, AggValueSlot::IsDestructed,
1185
3
                                     needsGC(E->getLHS()->getType()),
1186
3
                                     AggValueSlot::IsAliased,
1187
3
                                     AggValueSlot::MayOverlap),
1188
3
             Dest);
1189
3
    return;
1190
3
  }
1191
453
1192
453
  LValue LHS = CGF.EmitLValue(E->getLHS());
1193
453
1194
  // If we have an atomic type, evaluate into the destination and then
1195
  // do an atomic copy.
1196
453
  if (LHS.getType()->isAtomicType() ||
1197
444
      CGF.LValueIsSuitableForInlineAtomic(LHS)) {
1198
12
    EnsureDest(E->getRHS()->getType());
1199
12
    Visit(E->getRHS());
1200
12
    CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1201
12
    return;
1202
12
  }
1203
441
1204
  // Codegen the RHS so that it stores directly into the LHS.
1205
441
  AggValueSlot LHSSlot = AggValueSlot::forLValue(
1206
441
      LHS, CGF, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
1207
441
      AggValueSlot::IsAliased, AggValueSlot::MayOverlap);
1208
  // A non-volatile aggregate destination might have volatile member.
1209
441
  if (!LHSSlot.isVolatile() &&
1210
429
      CGF.hasVolatileMember(E->getLHS()->getType()))
1211
5
    LHSSlot.setVolatile(true);
1212
441
1213
441
  CGF.EmitAggExpr(E->getRHS(), LHSSlot);
1214
441
1215
  // Copy into the destination if the assignment isn't ignored.
1216
441
  EmitFinalDestCopy(E->getType(), LHS);
1217
441
}
1218
1219
void AggExprEmitter::
1220
56
VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1221
56
  llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1222
56
  llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1223
56
  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1224
56
1225
  // Bind the common expression if necessary.
1226
56
  CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1227
56
1228
56
  CodeGenFunction::ConditionalEvaluation eval(CGF);
1229
56
  CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1230
56
                           CGF.getProfileCount(E));
1231
56
1232
  // Save whether the destination's lifetime is externally managed.
1233
56
  bool isExternallyDestructed = Dest.isExternallyDestructed();
1234
56
1235
56
  eval.begin(CGF);
1236
56
  CGF.EmitBlock(LHSBlock);
1237
56
  CGF.incrementProfileCounter(E);
1238
56
  Visit(E->getTrueExpr());
1239
56
  eval.end(CGF);
1240
56
1241
56
  assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1242
56
  CGF.Builder.CreateBr(ContBlock);
1243
56
1244
  // If the result of an agg expression is unused, then the emission
1245
  // of the LHS might need to create a destination slot.  That's fine
1246
  // with us, and we can safely emit the RHS into the same slot, but
1247
  // we shouldn't claim that it's already being destructed.
1248
56
  Dest.setExternallyDestructed(isExternallyDestructed);
1249
56
1250
56
  eval.begin(CGF);
1251
56
  CGF.EmitBlock(RHSBlock);
1252
56
  Visit(E->getFalseExpr());
1253
56
  eval.end(CGF);
1254
56
1255
56
  CGF.EmitBlock(ContBlock);
1256
56
}
1257
1258
0
void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
1259
0
  Visit(CE->getChosenSubExpr());
1260
0
}
1261
1262
308
void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1263
308
  Address ArgValue = Address::invalid();
1264
308
  Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
1265
308
1266
  // If EmitVAArg fails, emit an error.
1267
308
  if (!ArgPtr.isValid()) {
1268
0
    CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1269
0
    return;
1270
0
  }
1271
308
1272
308
  EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
1273
308
}
1274
1275
6.01k
void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1276
  // Ensure that we have a slot, but if we already do, remember
1277
  // whether it was externally destructed.
1278
6.01k
  bool wasExternallyDestructed = Dest.isExternallyDestructed();
1279
6.01k
  EnsureDest(E->getType());
1280
6.01k
1281
  // We're going to push a destructor if there isn't already one.
1282
6.01k
  Dest.setExternallyDestructed();
1283
6.01k
1284
6.01k
  Visit(E->getSubExpr());
1285
6.01k
1286
  // Push that destructor we promised.
1287
6.01k
  if (!wasExternallyDestructed)
1288
760
    CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1289
6.01k
}
1290
1291
void
1292
61.5k
AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1293
61.5k
  AggValueSlot Slot = EnsureSlot(E->getType());
1294
61.5k
  CGF.EmitCXXConstructExpr(E, Slot);
1295
61.5k
}
1296
1297
void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1298
200
    const CXXInheritedCtorInitExpr *E) {
1299
200
  AggValueSlot Slot = EnsureSlot(E->getType());
1300
200
  CGF.EmitInheritedCXXConstructorCall(
1301
200
      E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
1302
200
      E->inheritedFromVBase(), E);
1303
200
}
1304
1305
void
1306
1.50k
AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1307
1.50k
  AggValueSlot Slot = EnsureSlot(E->getType());
1308
1.50k
  LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
1309
1.50k
1310
  // We'll need to enter cleanup scopes in case any of the element
1311
  // initializers throws an exception.
1312
1.50k
  SmallVector<EHScopeStack::stable_iterator, 16> Cleanups;
1313
1.50k
  llvm::Instruction *CleanupDominator = nullptr;
1314
1.50k
1315
1.50k
  CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1316
1.50k
  for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1317
1.50k
                                               e = E->capture_init_end();
1318
4.03k
       i != e; 
++i, ++CurField2.52k
) {
1319
    // Emit initialization
1320
2.52k
    LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
1321
2.52k
    if (CurField->hasCapturedVLAType()) {
1322
24
      CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
1323
24
      continue;
1324
24
    }
1325
2.49k
1326
2.49k
    EmitInitializationToLValue(*i, LV);
1327
2.49k
1328
    // Push a destructor if necessary.
1329
2.49k
    if (QualType::DestructionKind DtorKind =
1330
26
            CurField->getType().isDestructedType()) {
1331
26
      assert(LV.isSimple());
1332
26
      if (CGF.needsEHCleanup(DtorKind)) {
1333
19
        if (!CleanupDominator)
1334
18
          CleanupDominator = CGF.Builder.CreateAlignedLoad(
1335
18
              CGF.Int8Ty,
1336
18
              llvm::Constant::getNullValue(CGF.Int8PtrTy),
1337
18
              CharUnits::One()); // placeholder
1338
19
1339
19
        CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), CurField->getType(),
1340
19
                        CGF.getDestroyer(DtorKind), false);
1341
19
        Cleanups.push_back(CGF.EHStack.stable_begin());
1342
19
      }
1343
26
    }
1344
2.49k
  }
1345
1.50k
1346
  // Deactivate all the partial cleanups in reverse order, which
1347
  // generally means popping them.
1348
1.52k
  for (unsigned i = Cleanups.size(); i != 0; 
--i19
)
1349
19
    CGF.DeactivateCleanupBlock(Cleanups[i-1], CleanupDominator);
1350
1.50k
1351
  // Destroy the placeholder if we made one.
1352
1.50k
  if (CleanupDominator)
1353
18
    CleanupDominator->eraseFromParent();
1354
1.50k
}
1355
1356
6.51k
void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1357
6.51k
  CodeGenFunction::RunCleanupsScope cleanups(CGF);
1358
6.51k
  Visit(E->getSubExpr());
1359
6.51k
}
1360
1361
0
void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1362
0
  QualType T = E->getType();
1363
0
  AggValueSlot Slot = EnsureSlot(T);
1364
0
  EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1365
0
}
1366
1367
18
void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1368
18
  QualType T = E->getType();
1369
18
  AggValueSlot Slot = EnsureSlot(T);
1370
18
  EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1371
18
}
1372
1373
/// isSimpleZero - If emitting this value will obviously just cause a store of
1374
/// zero to memory, return true.  This can return false if uncertain, so it just
1375
/// handles simple cases.
1376
4.57k
static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1377
4.57k
  E = E->IgnoreParens();
1378
4.57k
1379
  // 0
1380
4.57k
  if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1381
264
    return IL->getValue() == 0;
1382
  // +0.0
1383
4.31k
  if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1384
80
    return FL->getValue().isPosZero();
1385
  // int()
1386
4.23k
  if ((isa<ImplicitValueInitExpr>(E) || 
isa<CXXScalarValueInitExpr>(E)4.10k
) &&
1387
126
      CGF.getTypes().isZeroInitializable(E->getType()))
1388
126
    return true;
1389
  // (int*)0 - Null pointer expressions.
1390
4.10k
  if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1391
1.57k
    return ICE->getCastKind() == CK_NullToPointer &&
1392
15
           CGF.getTypes().isPointerZeroInitializable(E->getType()) &&
1393
15
           !E->HasSideEffects(CGF.getContext());
1394
  // '\0'
1395
2.53k
  if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1396
1
    return CL->getValue() == 0;
1397
2.53k
1398
  // Otherwise, hard case: conservatively return false.
1399
2.53k
  return false;
1400
2.53k
}
1401
1402
1403
void
1404
8.15k
AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1405
8.15k
  QualType type = LV.getType();
1406
  // FIXME: Ignore result?
1407
  // FIXME: Are initializers affected by volatile?
1408
8.15k
  if (Dest.isZeroed() && 
isSimpleZero(E, CGF)132
) {
1409
    // Storing "i32 0" to a zero'd memory location is a noop.
1410
45
    return;
1411
8.10k
  } else if (isa<ImplicitValueInitExpr>(E) || 
isa<CXXScalarValueInitExpr>(E)8.04k
) {
1412
63
    return EmitNullInitializationToLValue(LV);
1413
8.04k
  } else if (isa<NoInitExpr>(E)) {
1414
    // Do nothing.
1415
14
    return;
1416
8.02k
  } else if (type->isReferenceType()) {
1417
2.39k
    RValue RV = CGF.EmitReferenceBindingToExpr(E);
1418
2.39k
    return CGF.EmitStoreThroughLValue(RV, LV);
1419
2.39k
  }
1420
5.63k
1421
5.63k
  switch (CGF.getEvaluationKind(type)) {
1422
9
  case TEK_Complex:
1423
9
    CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1424
9
    return;
1425
3.11k
  case TEK_Aggregate:
1426
3.11k
    CGF.EmitAggExpr(
1427
3.11k
        E, AggValueSlot::forLValue(LV, CGF, AggValueSlot::IsDestructed,
1428
3.11k
                                   AggValueSlot::DoesNotNeedGCBarriers,
1429
3.11k
                                   AggValueSlot::IsNotAliased,
1430
3.11k
                                   AggValueSlot::MayOverlap, Dest.isZeroed()));
1431
3.11k
    return;
1432
2.51k
  case TEK_Scalar:
1433
2.51k
    if (LV.isSimple()) {
1434
2.50k
      CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1435
11
    } else {
1436
11
      CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1437
11
    }
1438
2.51k
    return;
1439
0
  }
1440
0
  llvm_unreachable("bad evaluation kind");
1441
0
}
1442
1443
81
void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1444
81
  QualType type = lv.getType();
1445
81
1446
  // If the destination slot is already zeroed out before the aggregate is
1447
  // copied into it, we don't have to emit any zeros here.
1448
81
  if (Dest.isZeroed() && 
CGF.getTypes().isZeroInitializable(type)10
)
1449
10
    return;
1450
71
1451
71
  if (CGF.hasScalarEvaluationKind(type)) {
1452
    // For non-aggregates, we can store the appropriate null constant.
1453
53
    llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1454
    // Note that the following is not equivalent to
1455
    // EmitStoreThroughBitfieldLValue for ARC types.
1456
53
    if (lv.isBitField()) {
1457
1
      CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1458
52
    } else {
1459
52
      assert(lv.isSimple());
1460
52
      CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1461
52
    }
1462
18
  } else {
1463
    // There's a potential optimization opportunity in combining
1464
    // memsets; that would be easy for arrays, but relatively
1465
    // difficult for structures with the current code.
1466
18
    CGF.EmitNullInitialization(lv.getAddress(CGF), lv.getType());
1467
18
  }
1468
71
}
1469
1470
3.04k
void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1471
#if 0
1472
  // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
1473
  // (Length of globals? Chunks of zeroed-out space?).
1474
  //
1475
  // If we can, prefer a copy from a global; this is a lot less code for long
1476
  // globals, and it's easier for the current optimizers to analyze.
1477
  if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1478
    llvm::GlobalVariable* GV =
1479
    new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1480
                             llvm::GlobalValue::InternalLinkage, C, "");
1481
    EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1482
    return;
1483
  }
1484
#endif
1485
3.04k
  if (E->hadArrayRangeDesignator())
1486
0
    CGF.ErrorUnsupported(E, "GNU array range designator extension");
1487
3.04k
1488
3.04k
  if (E->isTransparent())
1489
10
    return Visit(E->getInit(0));
1490
3.03k
1491
3.03k
  AggValueSlot Dest = EnsureSlot(E->getType());
1492
3.03k
1493
3.03k
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1494
3.03k
1495
  // Handle initialization of an array.
1496
3.03k
  if (E->getType()->isArrayType()) {
1497
1.62k
    auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1498
1.62k
    EmitArrayInit(Dest.getAddress(), AType, E->getType(), E);
1499
1.62k
    return;
1500
1.62k
  }
1501
1.40k
1502
1.40k
  assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1503
1.40k
1504
  // Do struct initialization; this code just sets each individual member
1505
  // to the approprate value.  This makes bitfield support automatic;
1506
  // the disadvantage is that the generated code is more difficult for
1507
  // the optimizer, especially with bitfields.
1508
1.40k
  unsigned NumInitElements = E->getNumInits();
1509
1.40k
  RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1510
1.40k
1511
  // We'll need to enter cleanup scopes in case any of the element
1512
  // initializers throws an exception.
1513
1.40k
  SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1514
1.40k
  llvm::Instruction *cleanupDominator = nullptr;
1515
16
  auto addCleanup = [&](const EHScopeStack::stable_iterator &cleanup) {
1516
16
    cleanups.push_back(cleanup);
1517
16
    if (!cleanupDominator) // create placeholder once needed
1518
8
      cleanupDominator = CGF.Builder.CreateAlignedLoad(
1519
8
          CGF.Int8Ty, llvm::Constant::getNullValue(CGF.Int8PtrTy),
1520
8
          CharUnits::One());
1521
16
  };
1522
1.40k
1523
1.40k
  unsigned curInitIndex = 0;
1524
1.40k
1525
  // Emit initialization of base classes.
1526
1.40k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1527
869
    assert(E->getNumInits() >= CXXRD->getNumBases() &&
1528
869
           "missing initializer for base class");
1529
14
    for (auto &Base : CXXRD->bases()) {
1530
14
      assert(!Base.isVirtual() && "should not see vbases here");
1531
14
      auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1532
14
      Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
1533
14
          Dest.getAddress(), CXXRD, BaseRD,
1534
14
          /*isBaseVirtual*/ false);
1535
14
      AggValueSlot AggSlot = AggValueSlot::forAddr(
1536
14
          V, Qualifiers(),
1537
14
          AggValueSlot::IsDestructed,
1538
14
          AggValueSlot::DoesNotNeedGCBarriers,
1539
14
          AggValueSlot::IsNotAliased,
1540
14
          CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
1541
14
      CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
1542
14
1543
14
      if (QualType::DestructionKind dtorKind =
1544
8
              Base.getType().isDestructedType()) {
1545
8
        CGF.pushDestroy(dtorKind, V, Base.getType());
1546
8
        addCleanup(CGF.EHStack.stable_begin());
1547
8
      }
1548
14
    }
1549
869
  }
1550
1.40k
1551
  // Prepare a 'this' for CXXDefaultInitExprs.
1552
1.40k
  CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1553
1.40k
1554
1.40k
  if (record->isUnion()) {
1555
    // Only initialize one field of a union. The field itself is
1556
    // specified by the initializer list.
1557
47
    if (!E->getInitializedFieldInUnion()) {
1558
      // Empty union; we have nothing to do.
1559
12
1560
12
#ifndef NDEBUG
1561
      // Make sure that it's really an empty and not a failure of
1562
      // semantic analysis.
1563
12
      for (const auto *Field : record->fields())
1564
12
        assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1565
12
#endif
1566
12
      return;
1567
12
    }
1568
35
1569
    // FIXME: volatility
1570
35
    FieldDecl *Field = E->getInitializedFieldInUnion();
1571
35
1572
35
    LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1573
35
    if (NumInitElements) {
1574
      // Store the initializer into the field
1575
35
      EmitInitializationToLValue(E->getInit(0), FieldLoc);
1576
0
    } else {
1577
      // Default-initialize to null.
1578
0
      EmitNullInitializationToLValue(FieldLoc);
1579
0
    }
1580
35
1581
35
    return;
1582
35
  }
1583
1.35k
1584
  // Here we iterate over the fields; this makes it simpler to both
1585
  // default-initialize fields and skip over unnamed fields.
1586
2.28k
  
for (const auto *field : record->fields())1.35k
{
1587
    // We're done once we hit the flexible array member.
1588
2.28k
    if (field->getType()->isIncompleteArrayType())
1589
0
      break;
1590
2.28k
1591
    // Always skip anonymous bitfields.
1592
2.28k
    if (field->isUnnamedBitfield())
1593
24
      continue;
1594
2.26k
1595
    // We're done if we reach the end of the explicit initializers, we
1596
    // have a zeroed object, and the rest of the fields are
1597
    // zero-initializable.
1598
2.26k
    if (curInitIndex == NumInitElements && 
Dest.isZeroed()0
&&
1599
0
        CGF.getTypes().isZeroInitializable(E->getType()))
1600
0
      break;
1601
2.26k
1602
2.26k
1603
2.26k
    LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1604
    // We never generate write-barries for initialized fields.
1605
2.26k
    LV.setNonGC(true);
1606
2.26k
1607
2.26k
    if (curInitIndex < NumInitElements) {
1608
      // Store the initializer into the field.
1609
2.26k
      EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1610
0
    } else {
1611
      // We're out of initializers; default-initialize to null
1612
0
      EmitNullInitializationToLValue(LV);
1613
0
    }
1614
2.26k
1615
    // Push a destructor if necessary.
1616
    // FIXME: if we have an array of structures, all explicitly
1617
    // initialized, we can end up pushing a linear number of cleanups.
1618
2.26k
    bool pushedCleanup = false;
1619
2.26k
    if (QualType::DestructionKind dtorKind
1620
60
          = field->getType().isDestructedType()) {
1621
60
      assert(LV.isSimple());
1622
60
      if (CGF.needsEHCleanup(dtorKind)) {
1623
8
        CGF.pushDestroy(EHCleanup, LV.getAddress(CGF), field->getType(),
1624
8
                        CGF.getDestroyer(dtorKind), false);
1625
8
        addCleanup(CGF.EHStack.stable_begin());
1626
8
        pushedCleanup = true;
1627
8
      }
1628
60
    }
1629
2.26k
1630
    // If the GEP didn't get used because of a dead zero init or something
1631
    // else, clean it up for -O0 builds and general tidiness.
1632
2.26k
    if (!pushedCleanup && 
LV.isSimple()2.25k
)
1633
2.24k
      if (llvm::GetElementPtrInst *GEP =
1634
2.15k
              dyn_cast<llvm::GetElementPtrInst>(LV.getPointer(CGF)))
1635
2.15k
        if (GEP->use_empty())
1636
85
          GEP->eraseFromParent();
1637
2.26k
  }
1638
1.35k
1639
  // Deactivate all the partial cleanups in reverse order, which
1640
  // generally means popping them.
1641
1.35k
  assert((cleanupDominator || cleanups.empty()) &&
1642
1.35k
         "Missing cleanupDominator before deactivating cleanup blocks");
1643
1.37k
  for (unsigned i = cleanups.size(); i != 0; 
--i16
)
1644
16
    CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1645
1.35k
1646
  // Destroy the placeholder if we made one.
1647
1.35k
  if (cleanupDominator)
1648
8
    cleanupDominator->eraseFromParent();
1649
1.35k
}
1650
1651
void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1652
28
                                            llvm::Value *outerBegin) {
1653
  // Emit the common subexpression.
1654
28
  CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1655
28
1656
28
  Address destPtr = EnsureSlot(E->getType()).getAddress();
1657
28
  uint64_t numElements = E->getArraySize().getZExtValue();
1658
28
1659
28
  if (!numElements)
1660
0
    return;
1661
28
1662
  // destPtr is an array*. Construct an elementType* by drilling down a level.
1663
28
  llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1664
28
  llvm::Value *indices[] = {zero, zero};
1665
28
  llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
1666
28
                                                 "arrayinit.begin");
1667
28
1668
  // Prepare to special-case multidimensional array initialization: we avoid
1669
  // emitting multiple destructor loops in that case.
1670
28
  if (!outerBegin)
1671
21
    outerBegin = begin;
1672
28
  ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1673
28
1674
28
  QualType elementType =
1675
28
      CGF.getContext().getAsArrayType(E->getType())->getElementType();
1676
28
  CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1677
28
  CharUnits elementAlign =
1678
28
      destPtr.getAlignment().alignmentOfArrayElement(elementSize);
1679
28
1680
28
  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1681
28
  llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1682
28
1683
  // Jump into the body.
1684
28
  CGF.EmitBlock(bodyBB);
1685
28
  llvm::PHINode *index =
1686
28
      Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
1687
28
  index->addIncoming(zero, entryBB);
1688
28
  llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
1689
28
1690
  // Prepare for a cleanup.
1691
28
  QualType::DestructionKind dtorKind = elementType.isDestructedType();
1692
28
  EHScopeStack::stable_iterator cleanup;
1693
28
  if (CGF.needsEHCleanup(dtorKind) && 
!InnerLoop6
) {
1694
5
    if (outerBegin->getType() != element->getType())
1695
1
      outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
1696
5
    CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
1697
5
                                       elementAlign,
1698
5
                                       CGF.getDestroyer(dtorKind));
1699
5
    cleanup = CGF.EHStack.stable_begin();
1700
23
  } else {
1701
23
    dtorKind = QualType::DK_none;
1702
23
  }
1703
28
1704
  // Emit the actual filler expression.
1705
28
  {
1706
    // Temporaries created in an array initialization loop are destroyed
1707
    // at the end of each iteration.
1708
28
    CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
1709
28
    CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
1710
28
    LValue elementLV =
1711
28
        CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
1712
28
1713
28
    if (InnerLoop) {
1714
      // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
1715
7
      auto elementSlot = AggValueSlot::forLValue(
1716
7
          elementLV, CGF, AggValueSlot::IsDestructed,
1717
7
          AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
1718
7
          AggValueSlot::DoesNotOverlap);
1719
7
      AggExprEmitter(CGF, elementSlot, false)
1720
7
          .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
1721
7
    } else
1722
21
      EmitInitializationToLValue(E->getSubExpr(), elementLV);
1723
28
  }
1724
28
1725
  // Move on to the next element.
1726
28
  llvm::Value *nextIndex = Builder.CreateNUWAdd(
1727
28
      index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
1728
28
  index->addIncoming(nextIndex, Builder.GetInsertBlock());
1729
28
1730
  // Leave the loop if we're done.
1731
28
  llvm::Value *done = Builder.CreateICmpEQ(
1732
28
      nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
1733
28
      "arrayinit.done");
1734
28
  llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
1735
28
  Builder.CreateCondBr(done, endBB, bodyBB);
1736
28
1737
28
  CGF.EmitBlock(endBB);
1738
28
1739
  // Leave the partial-array cleanup if we entered one.
1740
28
  if (dtorKind)
1741
5
    CGF.DeactivateCleanupBlock(cleanup, index);
1742
28
}
1743
1744
8
void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1745
8
  AggValueSlot Dest = EnsureSlot(E->getType());
1746
8
1747
8
  LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1748
8
  EmitInitializationToLValue(E->getBase(), DestLV);
1749
8
  VisitInitListExpr(E->getUpdater());
1750
8
}
1751
1752
//===----------------------------------------------------------------------===//
1753
//                        Entry Points into this File
1754
//===----------------------------------------------------------------------===//
1755
1756
/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1757
/// non-zero bytes that will be stored when outputting the initializer for the
1758
/// specified initializer expression.
1759
4.44k
static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1760
4.44k
  E = E->IgnoreParens();
1761
4.44k
1762
  // 0 and 0.0 won't require any non-zero stores!
1763
4.44k
  if (isSimpleZero(E, CGF)) 
return CharUnits::Zero()110
;
1764
4.33k
1765
  // If this is an initlist expr, sum up the size of sizes of the (present)
1766
  // elements.  If this is something weird, assume the whole thing is non-zero.
1767
4.33k
  const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1768
4.34k
  while (ILE && 
ILE->isTransparent()222
)
1769
6
    ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
1770
4.33k
  if (!ILE || 
!CGF.getTypes().isZeroInitializable(ILE->getType())216
)
1771
4.11k
    return CGF.getContext().getTypeSizeInChars(E->getType());
1772
216
1773
  // InitListExprs for structs have to be handled carefully.  If there are
1774
  // reference members, we need to consider the size of the reference, not the
1775
  // referencee.  InitListExprs for unions and arrays can't have references.
1776
216
  if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1777
106
    if (!RT->isUnionType()) {
1778
103
      RecordDecl *SD = RT->getDecl();
1779
103
      CharUnits NumNonZeroBytes = CharUnits::Zero();
1780
103
1781
103
      unsigned ILEElement = 0;
1782
103
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
1783
69
        while (ILEElement != CXXRD->getNumBases())
1784
0
          NumNonZeroBytes +=
1785
0
              GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
1786
416
      for (const auto *Field : SD->fields()) {
1787
        // We're done once we hit the flexible array member or run out of
1788
        // InitListExpr elements.
1789
416
        if (Field->getType()->isIncompleteArrayType() ||
1790
416
            ILEElement == ILE->getNumInits())
1791
0
          break;
1792
416
        if (Field->isUnnamedBitfield())
1793
0
          continue;
1794
416
1795
416
        const Expr *E = ILE->getInit(ILEElement++);
1796
416
1797
        // Reference values are always non-null and have the width of a pointer.
1798
416
        if (Field->getType()->isReferenceType())
1799
4
          NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1800
4
              CGF.getTarget().getPointerWidth(0));
1801
412
        else
1802
412
          NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1803
416
      }
1804
103
1805
103
      return NumNonZeroBytes;
1806
103
    }
1807
113
  }
1808
113
1809
113
1810
113
  CharUnits NumNonZeroBytes = CharUnits::Zero();
1811
469
  for (unsigned i = 0, e = ILE->getNumInits(); i != e; 
++i356
)
1812
356
    NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1813
113
  return NumNonZeroBytes;
1814
113
}
1815
1816
/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1817
/// zeros in it, emit a memset and avoid storing the individual zeros.
1818
///
1819
static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1820
77.7k
                                     CodeGenFunction &CGF) {
1821
  // If the slot is already known to be zeroed, nothing to do.  Don't mess with
1822
  // volatile stores.
1823
77.7k
  if (Slot.isZeroed() || 
Slot.isVolatile()77.6k
||
!Slot.getAddress().isValid()77.6k
)
1824
1.53k
    return;
1825
76.1k
1826
  // C++ objects with a user-declared constructor don't need zero'ing.
1827
76.1k
  if (CGF.getLangOpts().CPlusPlus)
1828
70.9k
    if (const RecordType *RT = CGF.getContext()
1829
70.7k
                       .getBaseElementType(E->getType())->getAs<RecordType>()) {
1830
70.7k
      const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1831
70.7k
      if (RD->hasUserDeclaredConstructor())
1832
49.0k
        return;
1833
27.0k
    }
1834
27.0k
1835
  // If the type is 16-bytes or smaller, prefer individual stores over memset.
1836
27.0k
  CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
1837
27.0k
  if (Size <= CharUnits::fromQuantity(16))
1838
23.4k
    return;
1839
3.67k
1840
  // Check to see if over 3/4 of the initializer are known to be zero.  If so,
1841
  // we prefer to emit memset + individual stores for the rest.
1842
3.67k
  CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1843
3.67k
  if (NumNonZeroBytes*4 > Size)
1844
3.63k
    return;
1845
46
1846
  // Okay, it seems like a good idea to use an initial memset, emit the call.
1847
46
  llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
1848
46
1849
46
  Address Loc = Slot.getAddress();
1850
46
  Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
1851
46
  CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
1852
46
1853
  // Tell the AggExprEmitter that the slot is known zero.
1854
46
  Slot.setZeroed();
1855
46
}
1856
1857
1858
1859
1860
/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1861
/// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1862
/// the value of the aggregate expression is not needed.  If VolatileDest is
1863
/// true, DestPtr cannot be 0.
1864
77.7k
void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1865
77.7k
  assert(E && hasAggregateEvaluationKind(E->getType()) &&
1866
77.7k
         "Invalid aggregate expression to emit");
1867
77.7k
  assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
1868
77.7k
         "slot has bits but no address");
1869
77.7k
1870
  // Optimize the slot if possible.
1871
77.7k
  CheckAggExprForMemSetUse(Slot, E, *this);
1872
77.7k
1873
77.7k
  AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1874
77.7k
}
1875
1876
81
LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1877
81
  assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1878
81
  Address Temp = CreateMemTemp(E->getType());
1879
81
  LValue LV = MakeAddrLValue(Temp, E->getType());
1880
81
  EmitAggExpr(E, AggValueSlot::forLValue(
1881
81
                     LV, *this, AggValueSlot::IsNotDestructed,
1882
81
                     AggValueSlot::DoesNotNeedGCBarriers,
1883
81
                     AggValueSlot::IsNotAliased, AggValueSlot::DoesNotOverlap));
1884
81
  return LV;
1885
81
}
1886
1887
AggValueSlot::Overlap_t
1888
4.28k
CodeGenFunction::getOverlapForFieldInit(const FieldDecl *FD) {
1889
4.28k
  if (!FD->hasAttr<NoUniqueAddressAttr>() || 
!FD->getType()->isRecordType()3
)
1890
4.27k
    return AggValueSlot::DoesNotOverlap;
1891
3
1892
  // If the field lies entirely within the enclosing class's nvsize, its tail
1893
  // padding cannot overlap any already-initialized object. (The only subobjects
1894
  // with greater addresses that might already be initialized are vbases.)
1895
3
  const RecordDecl *ClassRD = FD->getParent();
1896
3
  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
1897
3
  if (Layout.getFieldOffset(FD->getFieldIndex()) +
1898
3
          getContext().getTypeSize(FD->getType()) <=
1899
3
      (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
1900
1
    return AggValueSlot::DoesNotOverlap;
1901
2
1902
  // The tail padding may contain values we need to preserve.
1903
2
  return AggValueSlot::MayOverlap;
1904
2
}
1905
1906
AggValueSlot::Overlap_t CodeGenFunction::getOverlapForBaseInit(
1907
9.50k
    const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
1908
  // If the most-derived object is a field declared with [[no_unique_address]],
1909
  // the tail padding of any virtual base could be reused for other subobjects
1910
  // of that field's class.
1911
9.50k
  if (IsVirtual)
1912
779
    return AggValueSlot::MayOverlap;
1913
8.72k
1914
  // If the base class is laid out entirely within the nvsize of the derived
1915
  // class, its tail padding cannot yet be initialized, so we can issue
1916
  // stores at the full width of the base class.
1917
8.72k
  const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1918
8.72k
  if (Layout.getBaseClassOffset(BaseRD) +
1919
8.72k
          getContext().getASTRecordLayout(BaseRD).getSize() <=
1920
8.72k
      Layout.getNonVirtualSize())
1921
8.43k
    return AggValueSlot::DoesNotOverlap;
1922
293
1923
  // The tail padding may contain values we need to preserve.
1924
293
  return AggValueSlot::MayOverlap;
1925
293
}
1926
1927
void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src, QualType Ty,
1928
                                        AggValueSlot::Overlap_t MayOverlap,
1929
13.5k
                                        bool isVolatile) {
1930
13.5k
  assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1931
13.5k
1932
13.5k
  Address DestPtr = Dest.getAddress(*this);
1933
13.5k
  Address SrcPtr = Src.getAddress(*this);
1934
13.5k
1935
13.5k
  if (getLangOpts().CPlusPlus) {
1936
10.8k
    if (const RecordType *RT = Ty->getAs<RecordType>()) {
1937
9.58k
      CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1938
9.58k
      assert((Record->hasTrivialCopyConstructor() ||
1939
9.58k
              Record->hasTrivialCopyAssignment() ||
1940
9.58k
              Record->hasTrivialMoveConstructor() ||
1941
9.58k
              Record->hasTrivialMoveAssignment() ||
1942
9.58k
              Record->isUnion()) &&
1943
9.58k
             "Trying to aggregate-copy a type without a trivial copy/move "
1944
9.58k
             "constructor or assignment operator");
1945
      // Ignore empty classes in C++.
1946
9.58k
      if (Record->isEmpty())
1947
3.57k
        return;
1948
10.0k
    }
1949
10.8k
  }
1950
10.0k
1951
10.0k
  if (getLangOpts().CUDAIsDevice) {
1952
3
    if (Ty->isCUDADeviceBuiltinSurfaceType()) {
1953
1
      if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
1954
1
                                                                  Src))
1955
1
        return;
1956
2
    } else if (Ty->isCUDADeviceBuiltinTextureType()) {
1957
2
      if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
1958
2
                                                                  Src))
1959
2
        return;
1960
10.0k
    }
1961
3
  }
1962
10.0k
1963
  // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1964
  // C99 6.5.16.1p3, which states "If the value being stored in an object is
1965
  // read from another object that overlaps in anyway the storage of the first
1966
  // object, then the overlap shall be exact and the two objects shall have
1967
  // qualified or unqualified versions of a compatible type."
1968
  //
1969
  // memcpy is not defined if the source and destination pointers are exactly
1970
  // equal, but other compilers do this optimization, and almost every memcpy
1971
  // implementation handles this case safely.  If there is a libc that does not
1972
  // safely handle this, we can add a target hook.
1973
10.0k
1974
  // Get data size info for this aggregate. Don't copy the tail padding if this
1975
  // might be a potentially-overlapping subobject, since the tail padding might
1976
  // be occupied by a different object. Otherwise, copying it is fine.
1977
10.0k
  std::pair<CharUnits, CharUnits> TypeInfo;
1978
10.0k
  if (MayOverlap)
1979
4.39k
    TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1980
5.61k
  else
1981
5.61k
    TypeInfo = getContext().getTypeInfoInChars(Ty);
1982
10.0k
1983
10.0k
  llvm::Value *SizeVal = nullptr;
1984
10.0k
  if (TypeInfo.first.isZero()) {
1985
    // But note that getTypeInfo returns 0 for a VLA.
1986
138
    if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1987
84
            getContext().getAsArrayType(Ty))) {
1988
84
      QualType BaseEltTy;
1989
84
      SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1990
84
      TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1991
84
      assert(!TypeInfo.first.isZero());
1992
84
      SizeVal = Builder.CreateNUWMul(
1993
84
          SizeVal,
1994
84
          llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1995
84
    }
1996
138
  }
1997
10.0k
  if (!SizeVal) {
1998
9.92k
    SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1999
9.92k
  }
2000
10.0k
2001
  // FIXME: If we have a volatile struct, the optimizer can remove what might
2002
  // appear to be `extra' memory ops:
2003
  //
2004
  // volatile struct { int i; } a, b;
2005
  //
2006
  // int main() {
2007
  //   a = b;
2008
  //   a = b;
2009
  // }
2010
  //
2011
  // we need to use a different call here.  We use isVolatile to indicate when
2012
  // either the source or the destination is volatile.
2013
10.0k
2014
10.0k
  DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
2015
10.0k
  SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
2016
10.0k
2017
  // Don't do any of the memmove_collectable tests if GC isn't set.
2018
10.0k
  if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
2019
    // fall through
2020
30
  } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
2021
28
    RecordDecl *Record = RecordTy->getDecl();
2022
28
    if (Record->hasObjectMember()) {
2023
23
      CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2024
23
                                                    SizeVal);
2025
23
      return;
2026
23
    }
2027
2
  } else if (Ty->isArrayType()) {
2028
2
    QualType BaseType = getContext().getBaseElementType(Ty);
2029
2
    if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
2030
1
      if (RecordTy->getDecl()->hasObjectMember()) {
2031
1
        CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2032
1
                                                      SizeVal);
2033
1
        return;
2034
1
      }
2035
9.98k
    }
2036
2
  }
2037
9.98k
2038
9.98k
  auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
2039
9.98k
2040
  // Determine the metadata to describe the position of any padding in this
2041
  // memcpy, as well as the TBAA tags for the members of the struct, in case
2042
  // the optimizer wishes to expand it in to scalar memory operations.
2043
9.98k
  if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
2044
432
    Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
2045
9.98k
2046
9.98k
  if (CGM.getCodeGenOpts().NewStructPathTBAA) {
2047
7
    TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
2048
7
        Dest.getTBAAInfo(), Src.getTBAAInfo());
2049
7
    CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
2050
7
  }
2051
9.98k
}