Coverage Report

Created: 2024-01-17 10:31

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