clang 23.0.0git
CGExprAgg.cpp
Go to the documentation of this file.
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 "CGDebugInfo.h"
15#include "CGHLSLRuntime.h"
16#include "CGObjCRuntime.h"
17#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "ConstantEmitter.h"
21#include "EHScopeStack.h"
22#include "TargetInfo.h"
24#include "clang/AST/Attr.h"
25#include "clang/AST/DeclCXX.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Instruction.h"
32#include "llvm/IR/IntrinsicInst.h"
33#include "llvm/IR/Intrinsics.h"
34using namespace clang;
35using namespace CodeGen;
36
37//===----------------------------------------------------------------------===//
38// Aggregate Expression Emitter
39//===----------------------------------------------------------------------===//
40
41namespace {
42class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
43 CodeGenFunction &CGF;
44 CGBuilderTy &Builder;
45 AggValueSlot Dest;
46 bool IsResultUnused;
47
48 AggValueSlot EnsureSlot(QualType T) {
49 if (!Dest.isIgnored())
50 return Dest;
51 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
52 }
53 void EnsureDest(QualType T) {
54 if (!Dest.isIgnored())
55 return;
56 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
57 }
58
59 // Calls `Fn` with a valid return value slot, potentially creating a temporary
60 // to do so. If a temporary is created, an appropriate copy into `Dest` will
61 // be emitted, as will lifetime markers.
62 //
63 // The given function should take a ReturnValueSlot, and return an RValue that
64 // points to said slot.
65 void withReturnValueSlot(const Expr *E,
66 llvm::function_ref<RValue(ReturnValueSlot)> Fn);
67
68 void DoZeroInitPadding(uint64_t &PaddingStart, uint64_t PaddingEnd,
69 const FieldDecl *NextField);
70
71public:
72 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
73 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
74 IsResultUnused(IsResultUnused) {}
75
76 //===--------------------------------------------------------------------===//
77 // Utilities
78 //===--------------------------------------------------------------------===//
79
80 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
81 /// represents a value lvalue, this method emits the address of the lvalue,
82 /// then loads the result into DestPtr.
83 void EmitAggLoadOfLValue(const Expr *E);
84
85 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
86 /// SrcIsRValue is true if source comes from an RValue.
87 void EmitFinalDestCopy(QualType type, const LValue &src,
90 void EmitFinalDestCopy(QualType type, RValue src);
91 void EmitCopy(QualType type, const AggValueSlot &dest,
92 const AggValueSlot &src);
93
94 void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType, QualType ArrayQTy,
95 Expr *ExprToVisit, ArrayRef<Expr *> Args,
96 Expr *ArrayFiller);
97
98 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
99 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
102 }
103
104 bool TypeRequiresGCollection(QualType T);
105
106 //===--------------------------------------------------------------------===//
107 // Visitor Methods
108 //===--------------------------------------------------------------------===//
109
110 void Visit(Expr *E) {
111 ApplyDebugLocation DL(CGF, E);
112 StmtVisitor<AggExprEmitter>::Visit(E);
113 }
114
115 void VisitStmt(Stmt *S) { CGF.ErrorUnsupported(S, "aggregate expression"); }
116 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
117 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
118 Visit(GE->getResultExpr());
119 }
120 void VisitCoawaitExpr(CoawaitExpr *E) {
121 CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
122 }
123 void VisitCoyieldExpr(CoyieldExpr *E) {
124 CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
125 }
126 void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
127 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
128 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
129 return Visit(E->getReplacement());
130 }
131
132 void VisitConstantExpr(ConstantExpr *E) {
133 EnsureDest(E->getType());
134
135 if (llvm::Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
137 Result, E->getType(), Dest.getAddress(),
138 llvm::TypeSize::getFixed(
139 Dest.getPreferredSize(CGF.getContext(), E->getType())
140 .getQuantity()),
142 return;
143 }
144 return Visit(E->getSubExpr());
145 }
146
147 // l-values.
148 void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
149 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
150 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
151 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
152 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
153 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
154 EmitAggLoadOfLValue(E);
155 }
156 void VisitPredefinedExpr(const PredefinedExpr *E) { EmitAggLoadOfLValue(E); }
157
158 // Operators.
159 void VisitCastExpr(CastExpr *E);
160 void VisitCallExpr(const CallExpr *E);
161 void VisitStmtExpr(const StmtExpr *E);
162 void VisitBinaryOperator(const BinaryOperator *BO);
163 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
164 void VisitBinAssign(const BinaryOperator *E);
165 void VisitBinComma(const BinaryOperator *E);
166 void VisitBinCmp(const BinaryOperator *E);
167 void VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
168 Visit(E->getSemanticForm());
169 }
170
171 void VisitObjCMessageExpr(ObjCMessageExpr *E);
172 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { EmitAggLoadOfLValue(E); }
173
174 void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
175 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
176 void VisitChooseExpr(const ChooseExpr *CE);
177 void VisitInitListExpr(InitListExpr *E);
178 void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
179 FieldDecl *InitializedFieldInUnion,
180 Expr *ArrayFiller);
181 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
182 llvm::Value *outerBegin = nullptr);
183 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
184 void VisitNoInitExpr(NoInitExpr *E) {} // Do nothing.
185 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
186 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
187 Visit(DAE->getExpr());
188 }
189 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
190 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
191 Visit(DIE->getExpr());
192 }
193 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
194 void VisitCXXConstructExpr(const CXXConstructExpr *E);
195 void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
196 void VisitLambdaExpr(LambdaExpr *E);
197 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
198 void VisitExprWithCleanups(ExprWithCleanups *E);
199 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
200 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
201 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
202 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
203
204 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
205 if (E->isGLValue()) {
206 LValue LV = CGF.EmitPseudoObjectLValue(E);
207 return EmitFinalDestCopy(E->getType(), LV);
208 }
209
210 AggValueSlot Slot = EnsureSlot(E->getType());
211 bool NeedsDestruction =
212 !Slot.isExternallyDestructed() &&
214 if (NeedsDestruction)
216 CGF.EmitPseudoObjectRValue(E, Slot);
217 if (NeedsDestruction)
219 E->getType());
220 }
221
222 void VisitVAArgExpr(VAArgExpr *E);
223 void VisitCXXParenListInitExpr(CXXParenListInitExpr *E);
224 void VisitCXXParenListOrInitListExpr(Expr *ExprToVisit, ArrayRef<Expr *> Args,
225 Expr *ArrayFiller);
226
227 void EmitInitializationToLValue(Expr *E, LValue Address);
228 void EmitNullInitializationToLValue(LValue Address);
229 // case Expr::ChooseExprClass:
230 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
231 void VisitAtomicExpr(AtomicExpr *E) {
232 RValue Res = CGF.EmitAtomicExpr(E);
233 EmitFinalDestCopy(E->getType(), Res);
234 }
235 void VisitPackIndexingExpr(PackIndexingExpr *E) {
236 Visit(E->getSelectedExpr());
237 }
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.
248void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
250
251 // If the type of the l-value is atomic, then do an atomic load.
252 if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
253 CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
254 return;
255 }
256
257 if (E->getType().getAddressSpace() == LangAS::hlsl_constant)
258 if (CGF.CGM.getHLSLRuntime().emitBufferCopy(CGF, E, LV, Dest))
259 return;
260
261 EmitFinalDestCopy(E->getType(), LV);
262}
263
264/// True if the given aggregate type requires special GC API calls.
265bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
266 // Only record types have members that might require garbage collection.
267 const auto *Record = T->getAsRecordDecl();
268 if (!Record)
269 return false;
270
271 // Don't mess with non-trivial C++ types.
273 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
274 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
275 return false;
276
277 // Check whether the type has an object member.
278 return Record->hasObjectMember();
279}
280
281void AggExprEmitter::withReturnValueSlot(
282 const Expr *E, llvm::function_ref<RValue(ReturnValueSlot)> EmitCall) {
283 QualType RetTy = E->getType();
284 bool RequiresDestruction =
285 !Dest.isExternallyDestructed() &&
287
288 // If it makes no observable difference, save a memcpy + temporary.
289 //
290 // We need to always provide our own temporary if destruction is required.
291 // Otherwise, EmitCall will emit its own, notice that it's "unused", and end
292 // its lifetime before we have the chance to emit a proper destructor call.
293 //
294 // We also need a temporary if the destination is in a different address space
295 // from the sret AS. Use the target hook to get the actual sret AS for this
296 // return type.
297 const CXXRecordDecl *RD = RetTy->getAsCXXRecordDecl();
298 LangAS SRetLangAS = CGF.CGM.getTargetCodeGenInfo().getSRetAddrSpace(RD);
299 unsigned SRetAS = CGF.getContext().getTargetAddressSpace(SRetLangAS);
300 bool CanAggregateCopy =
301 RD ? (RD->hasTrivialCopyConstructor() ||
303 RD->hasTrivialMoveAssignment() || RD->hasAttr<TrivialABIAttr>() ||
304 RD->isUnion())
305 : RetTy.isTriviallyCopyableType(CGF.getContext());
306 bool DestASMismatch = !Dest.isIgnored() && CanAggregateCopy &&
307 Dest.getAddress()
309 ->stripPointerCasts()
310 ->getType()
311 ->getPointerAddressSpace() != SRetAS;
312 bool UseTemp = Dest.isPotentiallyAliased() || Dest.requiresGCollection() ||
313 (RequiresDestruction && Dest.isIgnored()) || DestASMismatch;
314
315 Address RetAddr = Address::invalid();
316
317 EHScopeStack::stable_iterator LifetimeEndBlock;
318 llvm::IntrinsicInst *LifetimeStartInst = nullptr;
319 if (!UseTemp) {
320 RetAddr = Dest.getAddress();
321 if (RetAddr.isValid() && RetAddr.getAddressSpace() != SRetAS) {
322 llvm::Type *SRetPtrTy =
323 llvm::PointerType::get(CGF.getLLVMContext(), SRetAS);
324 RetAddr = RetAddr.withPointer(
325 CGF.performAddrSpaceCast(RetAddr.getBasePointer(), SRetPtrTy),
326 RetAddr.isKnownNonNull());
327 }
328 } else {
329 RetAddr = CGF.CreateMemTempWithoutCast(RetTy, "tmp");
330 if (CGF.EmitLifetimeStart(RetAddr.getBasePointer())) {
331 LifetimeStartInst =
332 cast<llvm::IntrinsicInst>(std::prev(Builder.GetInsertPoint()));
333 assert(LifetimeStartInst->getIntrinsicID() ==
334 llvm::Intrinsic::lifetime_start &&
335 "Last insertion wasn't a lifetime.start?");
336
337 CGF.pushFullExprCleanup<CodeGenFunction::CallLifetimeEnd>(
338 NormalEHLifetimeMarker, RetAddr);
339 LifetimeEndBlock = CGF.EHStack.stable_begin();
340 }
341 }
342
343 RValue Src =
344 EmitCall(ReturnValueSlot(RetAddr, Dest.isVolatile(), IsResultUnused,
345 Dest.isExternallyDestructed()));
346
347 if (!UseTemp)
348 return;
349
350 assert(Dest.isIgnored() || Dest.emitRawPointer(CGF) !=
351 Src.getAggregatePointer(E->getType(), CGF));
352 EmitFinalDestCopy(E->getType(), Src);
353
354 if (!RequiresDestruction && LifetimeStartInst) {
355 // If there's no dtor to run, the copy was the last use of our temporary.
356 // Since we're not guaranteed to be in an ExprWithCleanups, clean up
357 // eagerly.
358 CGF.DeactivateCleanupBlock(LifetimeEndBlock, LifetimeStartInst);
359 CGF.EmitLifetimeEnd(RetAddr.getBasePointer());
360 }
361}
362
363/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
364void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
365 assert(src.isAggregate() && "value must be aggregate value!");
366 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
367 EmitFinalDestCopy(type, srcLV, CodeGenFunction::EVK_RValue);
368}
369
370/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
371void AggExprEmitter::EmitFinalDestCopy(
372 QualType type, const LValue &src,
373 CodeGenFunction::ExprValueKind SrcValueKind) {
374 // If Dest is ignored, then we're evaluating an aggregate expression
375 // in a context that doesn't care about the result. Note that loads
376 // from volatile l-values force the existence of a non-ignored
377 // destination.
378 if (Dest.isIgnored())
379 return;
380
381 // Copy non-trivial C structs here.
382 LValue DstLV = CGF.MakeAddrLValue(
383 Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
384
385 if (SrcValueKind == CodeGenFunction::EVK_RValue) {
386 if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
387 if (Dest.isPotentiallyAliased())
388 CGF.callCStructMoveAssignmentOperator(DstLV, src);
389 else
390 CGF.callCStructMoveConstructor(DstLV, src);
391 return;
392 }
393 } else {
394 if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
395 if (Dest.isPotentiallyAliased())
396 CGF.callCStructCopyAssignmentOperator(DstLV, src);
397 else
398 CGF.callCStructCopyConstructor(DstLV, src);
399 return;
400 }
401 }
402
403 AggValueSlot srcAgg = AggValueSlot::forLValue(
406 EmitCopy(type, Dest, srcAgg);
407}
408
409/// Perform a copy from the source into the destination.
410///
411/// \param type - the type of the aggregate being copied; qualifiers are
412/// ignored
413void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
414 const AggValueSlot &src) {
415 if (dest.requiresGCollection()) {
416 CharUnits sz = dest.getPreferredSize(CGF.getContext(), type);
417 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
419 src.getAddress(), size);
420 return;
421 }
422
423 // If the result of the assignment is used, copy the LHS there also.
424 // It's volatile if either side is. Use the minimum alignment of
425 // the two sides.
426 LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
427 LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
428 CGF.EmitAggregateCopy(DestLV, SrcLV, type, dest.mayOverlap(),
429 dest.isVolatile() || src.isVolatile());
430}
431
432/// Emit the initializer for a std::initializer_list initialized with a
433/// real initializer list.
434void AggExprEmitter::VisitCXXStdInitializerListExpr(
435 CXXStdInitializerListExpr *E) {
436 // Emit an array containing the elements. The array is externally destructed
437 // if the std::initializer_list object is.
438 ASTContext &Ctx = CGF.getContext();
439 LValue Array = CGF.EmitLValue(E->getSubExpr());
440 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
441 Address ArrayPtr = Array.getAddress();
442
443 const ConstantArrayType *ArrayType =
445 assert(ArrayType && "std::initializer_list constructed from non-array");
446
447 auto *Record = E->getType()->castAsRecordDecl();
448 RecordDecl::field_iterator Field = Record->field_begin();
449 assert(Field != Record->field_end() &&
450 Ctx.hasSameType(Field->getType()->getPointeeType(),
451 ArrayType->getElementType()) &&
452 "Expected std::initializer_list first field to be const E *");
453
454 // Start pointer.
455 AggValueSlot Dest = EnsureSlot(E->getType());
456 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
457 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
458 llvm::Value *ArrayStart = ArrayPtr.emitRawPointer(CGF);
459 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
460 ++Field;
461 assert(Field != Record->field_end() &&
462 "Expected std::initializer_list to have two fields");
463
464 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
465 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
466 if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
467 // Length.
468 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
469
470 } else {
471 // End pointer.
472 assert(Field->getType()->isPointerType() &&
473 Ctx.hasSameType(Field->getType()->getPointeeType(),
474 ArrayType->getElementType()) &&
475 "Expected std::initializer_list second field to be const E *");
476 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
477 llvm::Value *IdxEnd[] = {Zero, Size};
478 llvm::Value *ArrayEnd = Builder.CreateInBoundsGEP(
479 ArrayPtr.getElementType(), ArrayPtr.emitRawPointer(CGF), IdxEnd,
480 "arrayend");
481 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
482 }
483
484 assert(++Field == Record->field_end() &&
485 "Expected std::initializer_list to only have two fields");
486}
487
488/// Determine if E is a trivial array filler, that is, one that is
489/// equivalent to zero-initialization.
490static bool isTrivialFiller(Expr *E) {
491 if (!E)
492 return true;
493
495 return true;
496
497 if (auto *ILE = dyn_cast<InitListExpr>(E)) {
498 if (ILE->getNumInits())
499 return false;
500 return isTrivialFiller(ILE->getArrayFiller());
501 }
502
503 if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
504 return Cons->getConstructor()->isDefaultConstructor() &&
505 Cons->getConstructor()->isTrivial();
506
507 // FIXME: Are there other cases where we can avoid emitting an initializer?
508 return false;
509}
510
511// emit an elementwise cast where the RHS is a scalar or vector
512// or emit an aggregate splat cast
514 LValue DestVal,
515 llvm::Value *SrcVal,
516 QualType SrcTy,
517 SourceLocation Loc) {
518 // Flatten our destination
519 SmallVector<LValue, 16> StoreList;
520 CGF.FlattenAccessAndTypeLValue(DestVal, StoreList);
521
522 bool isVector = false;
523 if (auto *VT = SrcTy->getAs<VectorType>()) {
524 isVector = true;
525 SrcTy = VT->getElementType();
526 assert(StoreList.size() <= VT->getNumElements() &&
527 "Cannot perform HLSL flat cast when vector source \
528 object has less elements than flattened destination \
529 object.");
530 }
531
532 for (unsigned I = 0, Size = StoreList.size(); I < Size; I++) {
533 LValue DestLVal = StoreList[I];
534 llvm::Value *Load =
535 isVector ? CGF.Builder.CreateExtractElement(SrcVal, I, "vec.load")
536 : SrcVal;
537 llvm::Value *Cast =
538 CGF.EmitScalarConversion(Load, SrcTy, DestLVal.getType(), Loc);
539 CGF.EmitStoreThroughLValue(RValue::get(Cast), DestLVal);
540 }
541}
542
543// emit a flat cast where the RHS is an aggregate
544static void EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue DestVal,
545 LValue SrcVal, SourceLocation Loc) {
546 // Flatten our destination
547 SmallVector<LValue, 16> StoreList;
548 CGF.FlattenAccessAndTypeLValue(DestVal, StoreList);
549 // Flatten our src
551 CGF.FlattenAccessAndTypeLValue(SrcVal, LoadList);
552
553 assert(StoreList.size() <= LoadList.size() &&
554 "Cannot perform HLSL elementwise cast when flattened source object \
555 has less elements than flattened destination object.");
556 // apply casts to what we load from LoadList
557 // and store result in Dest
558 for (unsigned I = 0, E = StoreList.size(); I < E; I++) {
559 LValue DestLVal = StoreList[I];
560 LValue SrcLVal = LoadList[I];
561 RValue RVal = CGF.EmitLoadOfLValue(SrcLVal, Loc);
562 assert(RVal.isScalar() && "All flattened source values should be scalars");
563 llvm::Value *Val = RVal.getScalarVal();
564 llvm::Value *Cast = CGF.EmitScalarConversion(Val, SrcLVal.getType(),
565 DestLVal.getType(), Loc);
566 CGF.EmitStoreThroughLValue(RValue::get(Cast), DestLVal);
567 }
568}
569
570/// Emit initialization of an array from an initializer list. ExprToVisit must
571/// be either an InitListEpxr a CXXParenInitListExpr.
572void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
573 QualType ArrayQTy, Expr *ExprToVisit,
574 ArrayRef<Expr *> Args, Expr *ArrayFiller) {
575 uint64_t NumInitElements = Args.size();
576
577 uint64_t NumArrayElements = AType->getNumElements();
578 for (const auto *Init : Args) {
579 if (const auto *Embed = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
580 NumInitElements += Embed->getDataElementCount() - 1;
581 if (NumInitElements > NumArrayElements) {
582 NumInitElements = NumArrayElements;
583 break;
584 }
585 }
586 }
587
588 assert(NumInitElements <= NumArrayElements);
589
590 QualType elementType =
591 CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
592 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
593 CharUnits elementAlign =
594 DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
595 llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
596
597 // Consider initializing the array by copying from a global. For this to be
598 // more efficient than per-element initialization, the size of the elements
599 // with explicit initializers should be large enough.
600 if (NumInitElements * elementSize.getQuantity() > 16 &&
601 elementType.isTriviallyCopyableType(CGF.getContext())) {
602 CodeGen::CodeGenModule &CGM = CGF.CGM;
603 ConstantEmitter Emitter(CGF);
604 QualType GVArrayQTy = CGM.getContext().getAddrSpaceQualType(
605 CGM.getContext().removeAddrSpaceQualType(ArrayQTy),
607 LangAS AS = GVArrayQTy.getAddressSpace();
608 if (llvm::Constant *C =
609 Emitter.tryEmitForInitializer(ExprToVisit, AS, GVArrayQTy)) {
610 auto GV = new llvm::GlobalVariable(
611 CGM.getModule(), C->getType(),
612 /* isConstant= */ true, llvm::GlobalValue::PrivateLinkage, C,
613 "constinit",
614 /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
616 Emitter.finalize(GV);
617 CharUnits Align = CGM.getContext().getTypeAlignInChars(GVArrayQTy);
618 GV->setAlignment(Align.getAsAlign());
619 Address GVAddr(GV, GV->getValueType(), Align);
620 EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GVAddr, GVArrayQTy));
621 return;
622 }
623 }
624
625 // Exception safety requires us to destroy all the
626 // already-constructed members if an initializer throws.
627 // For that, we'll need an EH cleanup.
628 QualType::DestructionKind dtorKind = elementType.isDestructedType();
629 Address endOfInit = Address::invalid();
630 CodeGenFunction::CleanupDeactivationScope deactivation(CGF);
631
632 llvm::Value *begin = DestPtr.emitRawPointer(CGF);
633 if (dtorKind) {
634 CodeGenFunction::AllocaTrackerRAII allocaTracker(CGF);
635 // In principle we could tell the cleanup where we are more
636 // directly, but the control flow can get so varied here that it
637 // would actually be quite complex. Therefore we go through an
638 // alloca.
639 llvm::Instruction *dominatingIP =
640 Builder.CreateFlagLoad(llvm::ConstantInt::getNullValue(CGF.Int8PtrTy));
641 endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
642 "arrayinit.endOfInit");
643 Builder.CreateStore(begin, endOfInit);
644 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
645 elementAlign,
646 CGF.getDestroyer(dtorKind));
648 .AddAuxAllocas(allocaTracker.Take());
649
651 {CGF.EHStack.stable_begin(), dominatingIP});
652 }
653
654 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
655
656 auto Emit = [&](Expr *Init, uint64_t ArrayIndex) {
657 llvm::Value *element = begin;
658 if (ArrayIndex > 0) {
659 if (CGF.getLangOpts().EmitLogicalPointer)
660 element = Builder.CreateStructuredGEP(
661 AType, begin, llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex),
662 "arrayinit.element");
663 else
664 element = Builder.CreateInBoundsGEP(
665 llvmElementType, begin,
666 llvm::ConstantInt::get(CGF.SizeTy, ArrayIndex),
667 "arrayinit.element");
668
669 // Tell the cleanup that it needs to destroy up to this
670 // element. TODO: some of these stores can be trivially
671 // observed to be unnecessary.
672 if (endOfInit.isValid())
673 Builder.CreateStore(element, endOfInit);
674 }
675
676 LValue elementLV = CGF.MakeAddrLValue(
677 Address(element, llvmElementType, elementAlign), elementType);
678 EmitInitializationToLValue(Init, elementLV);
679 return true;
680 };
681
682 unsigned ArrayIndex = 0;
683 // Emit the explicit initializers.
684 for (uint64_t i = 0; i != NumInitElements; ++i) {
685 if (ArrayIndex >= NumInitElements)
686 break;
687 if (auto *EmbedS = dyn_cast<EmbedExpr>(Args[i]->IgnoreParenImpCasts())) {
688 EmbedS->doForEachDataElement(Emit, ArrayIndex);
689 } else {
690 Emit(Args[i], ArrayIndex);
691 ArrayIndex++;
692 }
693 }
694
695 // Check whether there's a non-trivial array-fill expression.
696 bool hasTrivialFiller = isTrivialFiller(ArrayFiller);
697
698 // Any remaining elements need to be zero-initialized, possibly
699 // using the filler expression. We can skip this if the we're
700 // emitting to zeroed memory.
701 if (NumInitElements != NumArrayElements &&
702 !(Dest.isZeroed() && hasTrivialFiller &&
703 CGF.getTypes().isZeroInitializable(elementType))) {
704
705 // Use an actual loop. This is basically
706 // do { *array++ = filler; } while (array != end);
707
708 // Advance to the start of the rest of the array.
709 llvm::Value *element = begin;
710 if (NumInitElements) {
711 element = Builder.CreateInBoundsGEP(
712 llvmElementType, element,
713 llvm::ConstantInt::get(CGF.SizeTy, NumInitElements),
714 "arrayinit.start");
715 if (endOfInit.isValid())
716 Builder.CreateStore(element, endOfInit);
717 }
718
719 // Compute the end of the array.
720 llvm::Value *end = Builder.CreateInBoundsGEP(
721 llvmElementType, begin,
722 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements), "arrayinit.end");
723
724 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
725 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
726
727 // Jump into the body.
728 CGF.EmitBlock(bodyBB);
729 llvm::PHINode *currentElement =
730 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
731 currentElement->addIncoming(element, entryBB);
732
734 CGF.ConvergenceTokenStack.push_back(CGF.emitConvergenceLoopToken(bodyBB));
735
736 // Emit the actual filler expression.
737 {
738 // C++1z [class.temporary]p5:
739 // when a default constructor is called to initialize an element of
740 // an array with no corresponding initializer [...] the destruction of
741 // every temporary created in a default argument is sequenced before
742 // the construction of the next array element, if any
743 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
744 LValue elementLV = CGF.MakeAddrLValue(
745 Address(currentElement, llvmElementType, elementAlign), elementType);
746 if (ArrayFiller)
747 EmitInitializationToLValue(ArrayFiller, elementLV);
748 else
749 EmitNullInitializationToLValue(elementLV);
750 }
751
752 // Move on to the next element.
753 llvm::Value *nextElement = Builder.CreateInBoundsGEP(
754 llvmElementType, currentElement, one, "arrayinit.next");
755
756 // Tell the EH cleanup that we finished with the last element.
757 if (endOfInit.isValid())
758 Builder.CreateStore(nextElement, endOfInit);
759
760 // Leave the loop if we're done.
761 llvm::Value *done =
762 Builder.CreateICmpEQ(nextElement, end, "arrayinit.done");
763 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
764 Builder.CreateCondBr(done, endBB, bodyBB);
765 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
766
768 CGF.ConvergenceTokenStack.pop_back();
769
770 CGF.EmitBlock(endBB);
771 }
772}
773
774//===----------------------------------------------------------------------===//
775// Visitor Methods
776//===----------------------------------------------------------------------===//
777
778void AggExprEmitter::VisitMaterializeTemporaryExpr(
779 MaterializeTemporaryExpr *E) {
780 Visit(E->getSubExpr());
781}
782
783void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
784 // If this is a unique OVE, just visit its source expression.
785 if (e->isUnique())
786 Visit(e->getSourceExpr());
787 else
788 EmitFinalDestCopy(e->getType(), CGF.getOrCreateOpaqueLValueMapping(e));
789}
790
791void AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
792 if (Dest.isPotentiallyAliased()) {
793 // Just emit a load of the lvalue + a copy, because our compound literal
794 // might alias the destination.
795 EmitAggLoadOfLValue(E);
796 return;
797 }
798
799 AggValueSlot Slot = EnsureSlot(E->getType());
800
801 // Block-scope compound literals are destroyed at the end of the enclosing
802 // scope in C.
803 bool Destruct =
804 !CGF.getLangOpts().CPlusPlus && !Slot.isExternallyDestructed();
805 if (Destruct)
807
808 CGF.EmitAggExpr(E->getInitializer(), Slot);
809
810 if (Destruct)
813 CGF.getCleanupKind(DtorKind), Slot.getAddress(), E->getType(),
814 CGF.getDestroyer(DtorKind), DtorKind & EHCleanup);
815}
816
817/// Attempt to look through various unimportant expressions to find a
818/// cast of the given kind.
819static Expr *findPeephole(Expr *op, CastKind kind, const ASTContext &ctx) {
820 op = op->IgnoreParenNoopCasts(ctx);
821 if (auto castE = dyn_cast<CastExpr>(op)) {
822 if (castE->getCastKind() == kind)
823 return castE->getSubExpr();
824 }
825 return nullptr;
826}
827
828void AggExprEmitter::VisitCastExpr(CastExpr *E) {
829 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
830 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
831 switch (E->getCastKind()) {
832 case CK_Dynamic: {
833 // FIXME: Can this actually happen? We have no test coverage for it.
834 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
835 LValue LV =
837 // FIXME: Do we also need to handle property references here?
838 if (LV.isSimple())
839 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
840 else
841 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
842
843 if (!Dest.isIgnored())
844 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
845 break;
846 }
847
848 case CK_ToUnion: {
849 // Evaluate even if the destination is ignored.
850 if (Dest.isIgnored()) {
852 /*ignoreResult=*/true);
853 break;
854 }
855
856 // GCC union extension
857 QualType Ty = E->getSubExpr()->getType();
858 Address CastPtr = Dest.getAddress().withElementType(CGF.ConvertType(Ty));
859 EmitInitializationToLValue(E->getSubExpr(),
860 CGF.MakeAddrLValue(CastPtr, Ty));
861 break;
862 }
863
864 case CK_LValueToRValueBitCast: {
865 if (Dest.isIgnored()) {
867 /*ignoreResult=*/true);
868 break;
869 }
870
871 LValue SourceLV = CGF.EmitLValue(E->getSubExpr());
872 Address SourceAddress = SourceLV.getAddress().withElementType(CGF.Int8Ty);
873 Address DestAddress = Dest.getAddress().withElementType(CGF.Int8Ty);
874 llvm::Value *SizeVal = llvm::ConstantInt::get(
875 CGF.SizeTy,
877 Builder.CreateMemCpy(DestAddress, SourceAddress, SizeVal);
878 break;
879 }
880
881 case CK_DerivedToBase: {
882 assert(CGF.getLangOpts().HLSL &&
883 "Derived/Base casts in EmitAggExpr are only supported in HLSL");
884
885 // Create a temporary for the derived record, switch it out with the current
886 // Dest slot, and emit the derived value.
887 QualType DerivedTy = E->getSubExpr()->getType();
888 RawAddress DerivedAddr = CGF.CreateMemTempWithoutCast(DerivedTy);
889 AggValueSlot DerivedTmpSlot = AggValueSlot::forAddr(
890 DerivedAddr, DerivedTy.getQualifiers(), AggValueSlot::IsNotDestructed,
893
894 AggValueSlot DestBaseSlot = Dest;
895 Dest = DerivedTmpSlot;
896
897 Visit(E->getSubExpr());
898
899 // Perform derived-to-base address conversion to get the address
900 // of the base record within the derived record. In HLSL this should
901 // always be same as the derived because of single inheritance, but let's
902 // do it properly.
903 Address BaseAddrInDerived = CGF.GetAddressOfBaseClass(
904 DerivedTmpSlot.getAddress(), DerivedTy->castAsCXXRecordDecl(),
905 E->path_begin(), E->path_end(),
906 /*NullCheckValue=*/false, E->getExprLoc());
907
908 AggValueSlot SrcBaseSlot = AggValueSlot::forAddr(
909 BaseAddrInDerived, E->getType().getQualifiers(),
912
913 // Copy the base class to the original destination slot and restore it.
914 EmitCopy(E->getType(), DestBaseSlot, SrcBaseSlot);
915 Dest = DestBaseSlot;
916 break;
917 }
918
919 case CK_BaseToDerived:
920 case CK_UncheckedDerivedToBase: {
921 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
922 "should have been unpacked before we got here");
923 }
924
925 case CK_NonAtomicToAtomic:
926 case CK_AtomicToNonAtomic: {
927 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
928
929 // Determine the atomic and value types.
930 QualType atomicType = E->getSubExpr()->getType();
931 QualType valueType = E->getType();
932 if (isToAtomic)
933 std::swap(atomicType, valueType);
934
935 assert(atomicType->isAtomicType());
937 valueType, atomicType->castAs<AtomicType>()->getValueType()));
938
939 // Just recurse normally if we're ignoring the result or the
940 // atomic type doesn't change representation.
941 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
942 return Visit(E->getSubExpr());
943 }
944
945 CastKind peepholeTarget =
946 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
947
948 // These two cases are reverses of each other; try to peephole them.
949 if (Expr *op =
950 findPeephole(E->getSubExpr(), peepholeTarget, CGF.getContext())) {
951 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
952 E->getType()) &&
953 "peephole significantly changed types?");
954 return Visit(op);
955 }
956
957 // If we're converting an r-value of non-atomic type to an r-value
958 // of atomic type, just emit directly into the relevant sub-object.
959 if (isToAtomic) {
960 AggValueSlot valueDest = Dest;
961 if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
962 // Zero-initialize. (Strictly speaking, we only need to initialize
963 // the padding at the end, but this is simpler.)
964 if (!Dest.isZeroed())
966
967 // Build a GEP to refer to the subobject.
968 Address valueAddr =
969 CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0);
970 valueDest = AggValueSlot::forAddr(
971 valueAddr, valueDest.getQualifiers(),
972 valueDest.isExternallyDestructed(), valueDest.requiresGCollection(),
975 }
976
977 CGF.EmitAggExpr(E->getSubExpr(), valueDest);
978 return;
979 }
980
981 // Otherwise, we're converting an atomic type to a non-atomic type.
982 // Make an atomic temporary, emit into that, and then copy the value out.
983 AggValueSlot atomicSlot =
984 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
985 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
986
987 Address valueAddr = Builder.CreateStructGEP(atomicSlot.getAddress(), 0);
988 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
989 return EmitFinalDestCopy(valueType, rvalue);
990 }
991 case CK_AddressSpaceConversion:
992 return Visit(E->getSubExpr());
993
994 case CK_LValueToRValue:
995 // If we're loading from a volatile type, force the destination
996 // into existence.
997 if (E->getSubExpr()->getType().isVolatileQualified()) {
998 bool Destruct =
999 !Dest.isExternallyDestructed() &&
1001 if (Destruct)
1003 EnsureDest(E->getType());
1004 Visit(E->getSubExpr());
1005
1006 if (Destruct)
1008 E->getType());
1009
1010 return;
1011 }
1012
1013 [[fallthrough]];
1014
1015 case CK_HLSLArrayRValue:
1016 if (CGF.getLangOpts().HLSL &&
1018 if (CGF.CGM.getHLSLRuntime().emitGlobalResourceArray(CGF, E, Dest))
1019 break;
1020 Visit(E->getSubExpr());
1021 break;
1022 case CK_HLSLAggregateSplatCast: {
1023 Expr *Src = E->getSubExpr();
1024 QualType SrcTy = Src->getType();
1025 RValue RV = CGF.EmitAnyExpr(Src);
1026 LValue DestLVal = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1027 SourceLocation Loc = E->getExprLoc();
1028
1029 assert(RV.isScalar() && SrcTy->isScalarType() &&
1030 "RHS of HLSL splat cast must be a scalar.");
1031 llvm::Value *SrcVal = RV.getScalarVal();
1032 EmitHLSLScalarElementwiseAndSplatCasts(CGF, DestLVal, SrcVal, SrcTy, Loc);
1033 break;
1034 }
1035 case CK_HLSLElementwiseCast: {
1036 Expr *Src = E->getSubExpr();
1037 QualType SrcTy = Src->getType();
1038 RValue RV = CGF.EmitAnyExpr(Src);
1039 LValue DestLVal = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1040 SourceLocation Loc = E->getExprLoc();
1041
1042 if (RV.isScalar()) {
1043 llvm::Value *SrcVal = RV.getScalarVal();
1044 assert(SrcTy->isVectorType() &&
1045 "HLSL Elementwise cast doesn't handle splatting.");
1046 EmitHLSLScalarElementwiseAndSplatCasts(CGF, DestLVal, SrcVal, SrcTy, Loc);
1047 } else {
1048 assert(RV.isAggregate() &&
1049 "Can't perform HLSL Aggregate cast on a complex type.");
1050 Address SrcVal = RV.getAggregateAddress();
1051 EmitHLSLElementwiseCast(CGF, DestLVal, CGF.MakeAddrLValue(SrcVal, SrcTy),
1052 Loc);
1053 }
1054 break;
1055 }
1056 case CK_NoOp:
1057 case CK_UserDefinedConversion:
1058 case CK_ConstructorConversion:
1060 E->getType()) &&
1061 "Implicit cast types must be compatible");
1062 Visit(E->getSubExpr());
1063 break;
1064
1065 case CK_LValueBitCast:
1066 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
1067
1068 case CK_Dependent:
1069 case CK_BitCast:
1070 case CK_ArrayToPointerDecay:
1071 case CK_FunctionToPointerDecay:
1072 case CK_NullToPointer:
1073 case CK_NullToMemberPointer:
1074 case CK_BaseToDerivedMemberPointer:
1075 case CK_DerivedToBaseMemberPointer:
1076 case CK_MemberPointerToBoolean:
1077 case CK_ReinterpretMemberPointer:
1078 case CK_IntegralToPointer:
1079 case CK_PointerToIntegral:
1080 case CK_PointerToBoolean:
1081 case CK_ToVoid:
1082 case CK_VectorSplat:
1083 case CK_IntegralCast:
1084 case CK_BooleanToSignedIntegral:
1085 case CK_IntegralToBoolean:
1086 case CK_IntegralToFloating:
1087 case CK_FloatingToIntegral:
1088 case CK_FloatingToBoolean:
1089 case CK_FloatingCast:
1090 case CK_CPointerToObjCPointerCast:
1091 case CK_BlockPointerToObjCPointerCast:
1092 case CK_AnyPointerToBlockPointerCast:
1093 case CK_ObjCObjectLValueCast:
1094 case CK_FloatingRealToComplex:
1095 case CK_FloatingComplexToReal:
1096 case CK_FloatingComplexToBoolean:
1097 case CK_FloatingComplexCast:
1098 case CK_FloatingComplexToIntegralComplex:
1099 case CK_IntegralRealToComplex:
1100 case CK_IntegralComplexToReal:
1101 case CK_IntegralComplexToBoolean:
1102 case CK_IntegralComplexCast:
1103 case CK_IntegralComplexToFloatingComplex:
1104 case CK_ARCProduceObject:
1105 case CK_ARCConsumeObject:
1106 case CK_ARCReclaimReturnedObject:
1107 case CK_ARCExtendBlockObject:
1108 case CK_CopyAndAutoreleaseBlockObject:
1109 case CK_BuiltinFnToFnPtr:
1110 case CK_ZeroToOCLOpaqueType:
1111 case CK_MatrixCast:
1112 case CK_HLSLVectorTruncation:
1113 case CK_HLSLMatrixTruncation:
1114 case CK_IntToOCLSampler:
1115 case CK_FloatingToFixedPoint:
1116 case CK_FixedPointToFloating:
1117 case CK_FixedPointCast:
1118 case CK_FixedPointToBoolean:
1119 case CK_FixedPointToIntegral:
1120 case CK_IntegralToFixedPoint:
1121 llvm_unreachable("cast kind invalid for aggregate types");
1122 }
1123}
1124
1125void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
1126 if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
1127 EmitAggLoadOfLValue(E);
1128 return;
1129 }
1130
1131 withReturnValueSlot(
1132 E, [&](ReturnValueSlot Slot) { return CGF.EmitCallExpr(E, Slot); });
1133}
1134
1135void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
1136 withReturnValueSlot(E, [&](ReturnValueSlot Slot) {
1137 return CGF.EmitObjCMessageExpr(E, Slot);
1138 });
1139}
1140
1141void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
1142 CGF.EmitIgnoredExpr(E->getLHS());
1143 Visit(E->getRHS());
1144}
1145
1146void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1147 CodeGenFunction::StmtExprEvaluation eval(CGF);
1148 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
1149}
1150
1156
1157static llvm::Value *EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF,
1158 const BinaryOperator *E, llvm::Value *LHS,
1159 llvm::Value *RHS, CompareKind Kind,
1160 const char *NameSuffix = "") {
1161 QualType ArgTy = E->getLHS()->getType();
1162 if (const ComplexType *CT = ArgTy->getAs<ComplexType>())
1163 ArgTy = CT->getElementType();
1164
1165 if (const auto *MPT = ArgTy->getAs<MemberPointerType>()) {
1166 assert(Kind == CK_Equal &&
1167 "member pointers may only be compared for equality");
1169 CGF, LHS, RHS, MPT, /*IsInequality*/ false);
1170 }
1171
1172 // Compute the comparison instructions for the specified comparison kind.
1173 struct CmpInstInfo {
1174 const char *Name;
1175 llvm::CmpInst::Predicate FCmp;
1176 llvm::CmpInst::Predicate SCmp;
1177 llvm::CmpInst::Predicate UCmp;
1178 };
1179 CmpInstInfo InstInfo = [&]() -> CmpInstInfo {
1180 using FI = llvm::FCmpInst;
1181 using II = llvm::ICmpInst;
1182 switch (Kind) {
1183 case CK_Less:
1184 return {"cmp.lt", FI::FCMP_OLT, II::ICMP_SLT, II::ICMP_ULT};
1185 case CK_Greater:
1186 return {"cmp.gt", FI::FCMP_OGT, II::ICMP_SGT, II::ICMP_UGT};
1187 case CK_Equal:
1188 return {"cmp.eq", FI::FCMP_OEQ, II::ICMP_EQ, II::ICMP_EQ};
1189 }
1190 llvm_unreachable("Unrecognised CompareKind enum");
1191 }();
1192
1193 if (ArgTy->hasFloatingRepresentation())
1194 return Builder.CreateFCmp(InstInfo.FCmp, LHS, RHS,
1195 llvm::Twine(InstInfo.Name) + NameSuffix);
1196 if (ArgTy->isIntegralOrEnumerationType() || ArgTy->isPointerType()) {
1197 auto Inst =
1198 ArgTy->hasSignedIntegerRepresentation() ? InstInfo.SCmp : InstInfo.UCmp;
1199 return Builder.CreateICmp(Inst, LHS, RHS,
1200 llvm::Twine(InstInfo.Name) + NameSuffix);
1201 }
1202
1203 llvm_unreachable("unsupported aggregate binary expression should have "
1204 "already been handled");
1205}
1206
1207void AggExprEmitter::VisitBinCmp(const BinaryOperator *E) {
1208 using llvm::BasicBlock;
1209 using llvm::PHINode;
1210 using llvm::Value;
1211 assert(CGF.getContext().hasSameType(E->getLHS()->getType(),
1212 E->getRHS()->getType()));
1213 const ComparisonCategoryInfo &CmpInfo =
1215 assert(CmpInfo.Record->isTriviallyCopyable() &&
1216 "cannot copy non-trivially copyable aggregate");
1217
1218 QualType ArgTy = E->getLHS()->getType();
1219
1220 if (!ArgTy->isIntegralOrEnumerationType() && !ArgTy->isRealFloatingType() &&
1221 !ArgTy->isNullPtrType() && !ArgTy->isPointerType() &&
1222 !ArgTy->isMemberPointerType() && !ArgTy->isAnyComplexType()) {
1223 return CGF.ErrorUnsupported(E, "aggregate three-way comparison");
1224 }
1225 bool IsComplex = ArgTy->isAnyComplexType();
1226
1227 // Evaluate the operands to the expression and extract their values.
1228 auto EmitOperand = [&](Expr *E) -> std::pair<Value *, Value *> {
1229 RValue RV = CGF.EmitAnyExpr(E);
1230 if (RV.isScalar())
1231 return {RV.getScalarVal(), nullptr};
1232 if (RV.isAggregate())
1233 return {RV.getAggregatePointer(E->getType(), CGF), nullptr};
1234 assert(RV.isComplex());
1235 return RV.getComplexVal();
1236 };
1237 auto LHSValues = EmitOperand(E->getLHS()),
1238 RHSValues = EmitOperand(E->getRHS());
1239
1240 auto EmitCmp = [&](CompareKind K) {
1241 Value *Cmp = EmitCompare(Builder, CGF, E, LHSValues.first, RHSValues.first,
1242 K, IsComplex ? ".r" : "");
1243 if (!IsComplex)
1244 return Cmp;
1245 assert(K == CompareKind::CK_Equal);
1246 Value *CmpImag = EmitCompare(Builder, CGF, E, LHSValues.second,
1247 RHSValues.second, K, ".i");
1248 return Builder.CreateAnd(Cmp, CmpImag, "and.eq");
1249 };
1250 auto EmitCmpRes = [&](const ComparisonCategoryInfo::ValueInfo *VInfo) {
1251 return Builder.getInt(VInfo->getIntValue());
1252 };
1253
1254 Value *Select;
1255 if (ArgTy->isNullPtrType()) {
1256 Select = EmitCmpRes(CmpInfo.getEqualOrEquiv());
1257 } else if (!CmpInfo.isPartial()) {
1258 Value *SelectOne =
1259 Builder.CreateSelect(EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()),
1260 EmitCmpRes(CmpInfo.getGreater()), "sel.lt");
1261 Select = Builder.CreateSelect(EmitCmp(CK_Equal),
1262 EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1263 SelectOne, "sel.eq");
1264 } else {
1265 Value *SelectEq = Builder.CreateSelect(
1266 EmitCmp(CK_Equal), EmitCmpRes(CmpInfo.getEqualOrEquiv()),
1267 EmitCmpRes(CmpInfo.getUnordered()), "sel.eq");
1268 Value *SelectGT = Builder.CreateSelect(EmitCmp(CK_Greater),
1269 EmitCmpRes(CmpInfo.getGreater()),
1270 SelectEq, "sel.gt");
1271 Select = Builder.CreateSelect(
1272 EmitCmp(CK_Less), EmitCmpRes(CmpInfo.getLess()), SelectGT, "sel.lt");
1273 }
1274 // Create the return value in the destination slot.
1275 EnsureDest(E->getType());
1276 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1277
1278 // Emit the address of the first (and only) field in the comparison category
1279 // type, and initialize it from the constant integer value selected above.
1280 LValue FieldLV = CGF.EmitLValueForFieldInitialization(
1281 DestLV, *CmpInfo.Record->field_begin());
1282 CGF.EmitStoreThroughLValue(RValue::get(Select), FieldLV, /*IsInit*/ true);
1283
1284 // All done! The result is in the Dest slot.
1285}
1286
1287void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
1288 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
1289 VisitPointerToDataMemberBinaryOperator(E);
1290 else
1291 CGF.ErrorUnsupported(E, "aggregate binary expression");
1292}
1293
1294void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
1295 const BinaryOperator *E) {
1296 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
1297 EmitFinalDestCopy(E->getType(), LV);
1298}
1299
1300/// Is the value of the given expression possibly a reference to or
1301/// into a __block variable?
1302static bool isBlockVarRef(const Expr *E) {
1303 // Make sure we look through parens.
1304 E = E->IgnoreParens();
1305
1306 // Check for a direct reference to a __block variable.
1307 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1308 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
1309 return (var && var->hasAttr<BlocksAttr>());
1310 }
1311
1312 // More complicated stuff.
1313
1314 // Binary operators.
1315 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
1316 // For an assignment or pointer-to-member operation, just care
1317 // about the LHS.
1318 if (op->isAssignmentOp() || op->isPtrMemOp())
1319 return isBlockVarRef(op->getLHS());
1320
1321 // For a comma, just care about the RHS.
1322 if (op->getOpcode() == BO_Comma)
1323 return isBlockVarRef(op->getRHS());
1324
1325 // FIXME: pointer arithmetic?
1326 return false;
1327
1328 // Check both sides of a conditional operator.
1329 } else if (const AbstractConditionalOperator *op =
1330 dyn_cast<AbstractConditionalOperator>(E)) {
1331 return isBlockVarRef(op->getTrueExpr()) ||
1332 isBlockVarRef(op->getFalseExpr());
1333
1334 // OVEs are required to support BinaryConditionalOperators.
1335 } else if (const OpaqueValueExpr *op = dyn_cast<OpaqueValueExpr>(E)) {
1336 if (const Expr *src = op->getSourceExpr())
1337 return isBlockVarRef(src);
1338
1339 // Casts are necessary to get things like (*(int*)&var) = foo().
1340 // We don't really care about the kind of cast here, except
1341 // we don't want to look through l2r casts, because it's okay
1342 // to get the *value* in a __block variable.
1343 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
1344 if (cast->getCastKind() == CK_LValueToRValue)
1345 return false;
1346 return isBlockVarRef(cast->getSubExpr());
1347
1348 // Handle unary operators. Again, just aggressively look through
1349 // it, ignoring the operation.
1350 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
1351 return isBlockVarRef(uop->getSubExpr());
1352
1353 // Look into the base of a field access.
1354 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
1355 return isBlockVarRef(mem->getBase());
1356
1357 // Look into the base of a subscript.
1358 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
1359 return isBlockVarRef(sub->getBase());
1360 }
1361
1362 return false;
1363}
1364
1365void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1366 ApplyAtomGroup Grp(CGF.getDebugInfo());
1367 // For an assignment to work, the value on the right has
1368 // to be compatible with the value on the left.
1369 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
1370 E->getRHS()->getType()) &&
1371 "Invalid assignment");
1372
1373 // If the LHS might be a __block variable, and the RHS can
1374 // potentially cause a block copy, we need to evaluate the RHS first
1375 // so that the assignment goes the right place.
1376 // This is pretty semantically fragile.
1377 if (isBlockVarRef(E->getLHS()) &&
1378 E->getRHS()->HasSideEffects(CGF.getContext())) {
1379 // Ensure that we have a destination, and evaluate the RHS into that.
1380 EnsureDest(E->getRHS()->getType());
1381 Visit(E->getRHS());
1382
1383 // Now emit the LHS and copy into it.
1384 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1385
1386 // That copy is an atomic copy if the LHS is atomic.
1387 if (LHS.getType()->isAtomicType() ||
1389 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1390 return;
1391 }
1392
1393 EmitCopy(E->getLHS()->getType(),
1395 needsGC(E->getLHS()->getType()),
1398 Dest);
1399 return;
1400 }
1401
1402 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1403
1404 // If we have an atomic type, evaluate into the destination and then
1405 // do an atomic copy.
1406 if (LHS.getType()->isAtomicType() ||
1408 EnsureDest(E->getRHS()->getType());
1409 Visit(E->getRHS());
1410 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
1411 return;
1412 }
1413
1414 // Codegen the RHS so that it stores directly into the LHS.
1415 AggValueSlot LHSSlot = AggValueSlot::forLValue(
1416 LHS, AggValueSlot::IsDestructed, needsGC(E->getLHS()->getType()),
1418 // A non-volatile aggregate destination might have volatile member.
1419 if (!LHSSlot.isVolatile() && CGF.hasVolatileMember(E->getLHS()->getType()))
1420 LHSSlot.setVolatile(true);
1421
1422 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
1423
1424 // Copy into the destination if the assignment isn't ignored.
1425 EmitFinalDestCopy(E->getType(), LHS);
1426
1427 if (!Dest.isIgnored() && !Dest.isExternallyDestructed() &&
1430 E->getType());
1431}
1432
1433void AggExprEmitter::VisitAbstractConditionalOperator(
1434 const AbstractConditionalOperator *E) {
1435 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1436 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
1437 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
1438
1439 // Bind the common expression if necessary.
1440 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1441
1442 CodeGenFunction::ConditionalEvaluation eval(CGF);
1443 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
1444 CGF.getProfileCount(E));
1445
1446 // Save whether the destination's lifetime is externally managed.
1447 bool isExternallyDestructed = Dest.isExternallyDestructed();
1448 bool destructNonTrivialCStruct =
1449 !isExternallyDestructed &&
1451 isExternallyDestructed |= destructNonTrivialCStruct;
1452 Dest.setExternallyDestructed(isExternallyDestructed);
1453
1454 eval.begin(CGF);
1455 CGF.EmitBlock(LHSBlock);
1457 Visit(E->getTrueExpr());
1458 eval.end(CGF);
1459
1460 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1461 CGF.Builder.CreateBr(ContBlock);
1462
1463 // If the result of an agg expression is unused, then the emission
1464 // of the LHS might need to create a destination slot. That's fine
1465 // with us, and we can safely emit the RHS into the same slot, but
1466 // we shouldn't claim that it's already being destructed.
1467 Dest.setExternallyDestructed(isExternallyDestructed);
1468
1469 eval.begin(CGF);
1470 CGF.EmitBlock(RHSBlock);
1472 Visit(E->getFalseExpr());
1473 eval.end(CGF);
1474
1475 if (destructNonTrivialCStruct)
1477 E->getType());
1478
1479 CGF.EmitBlock(ContBlock);
1480}
1481
1482void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
1483 Visit(CE->getChosenSubExpr());
1484}
1485
1486void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1487 Address ArgValue = Address::invalid();
1488 CGF.EmitVAArg(VE, ArgValue, Dest);
1489
1490 // If EmitVAArg fails, emit an error.
1491 if (!ArgValue.isValid()) {
1492 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1493 return;
1494 }
1495}
1496
1497void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1498 // Ensure that we have a slot, but if we already do, remember
1499 // whether it was externally destructed.
1500 bool wasExternallyDestructed = Dest.isExternallyDestructed();
1501 EnsureDest(E->getType());
1502
1503 // We're going to push a destructor if there isn't already one.
1505
1506 Visit(E->getSubExpr());
1507
1508 // Push that destructor we promised.
1509 if (!wasExternallyDestructed)
1510 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1511}
1512
1513void AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1514 AggValueSlot Slot = EnsureSlot(E->getType());
1515 CGF.EmitCXXConstructExpr(E, Slot);
1516}
1517
1518void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1519 const CXXInheritedCtorInitExpr *E) {
1520 AggValueSlot Slot = EnsureSlot(E->getType());
1522 Slot.getAddress(),
1523 E->inheritedFromVBase(), E);
1524}
1525
1526void AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1527 AggValueSlot Slot = EnsureSlot(E->getType());
1528 LValue SlotLV = CGF.MakeAddrLValue(Slot.getAddress(), E->getType());
1529
1530 // We'll need to enter cleanup scopes in case any of the element
1531 // initializers throws an exception or contains branch out of the expressions.
1532 CodeGenFunction::CleanupDeactivationScope scope(CGF);
1533
1534 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1536 e = E->capture_init_end();
1537 i != e; ++i, ++CurField) {
1538 // Emit initialization
1539 LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
1540 if (CurField->hasCapturedVLAType()) {
1541 CGF.EmitLambdaVLACapture(CurField->getCapturedVLAType(), LV);
1542 continue;
1543 }
1544
1545 EmitInitializationToLValue(*i, LV);
1546
1547 // Push a destructor if necessary.
1548 if (QualType::DestructionKind DtorKind =
1549 CurField->getType().isDestructedType()) {
1550 assert(LV.isSimple());
1551 if (DtorKind)
1553 CurField->getType(),
1554 CGF.getDestroyer(DtorKind), false);
1555 }
1556 }
1557}
1558
1559void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1560 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1561 Visit(E->getSubExpr());
1562}
1563
1564void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1565 QualType T = E->getType();
1566 AggValueSlot Slot = EnsureSlot(T);
1567 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1568}
1569
1570void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1571 QualType T = E->getType();
1572 AggValueSlot Slot = EnsureSlot(T);
1573 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1574}
1575
1576/// Determine whether the given cast kind is known to always convert values
1577/// with all zero bits in their value representation to values with all zero
1578/// bits in their value representation.
1579static bool castPreservesZero(const CastExpr *CE) {
1580 switch (CE->getCastKind()) {
1581 // No-ops.
1582 case CK_NoOp:
1583 case CK_UserDefinedConversion:
1584 case CK_ConstructorConversion:
1585 case CK_BitCast:
1586 case CK_ToUnion:
1587 case CK_ToVoid:
1588 // Conversions between (possibly-complex) integral, (possibly-complex)
1589 // floating-point, and bool.
1590 case CK_BooleanToSignedIntegral:
1591 case CK_FloatingCast:
1592 case CK_FloatingComplexCast:
1593 case CK_FloatingComplexToBoolean:
1594 case CK_FloatingComplexToIntegralComplex:
1595 case CK_FloatingComplexToReal:
1596 case CK_FloatingRealToComplex:
1597 case CK_FloatingToBoolean:
1598 case CK_FloatingToIntegral:
1599 case CK_IntegralCast:
1600 case CK_IntegralComplexCast:
1601 case CK_IntegralComplexToBoolean:
1602 case CK_IntegralComplexToFloatingComplex:
1603 case CK_IntegralComplexToReal:
1604 case CK_IntegralRealToComplex:
1605 case CK_IntegralToBoolean:
1606 case CK_IntegralToFloating:
1607 // Reinterpreting integers as pointers and vice versa.
1608 case CK_IntegralToPointer:
1609 case CK_PointerToIntegral:
1610 // Language extensions.
1611 case CK_VectorSplat:
1612 case CK_MatrixCast:
1613 case CK_NonAtomicToAtomic:
1614 case CK_AtomicToNonAtomic:
1615 case CK_HLSLVectorTruncation:
1616 case CK_HLSLMatrixTruncation:
1617 case CK_HLSLElementwiseCast:
1618 case CK_HLSLAggregateSplatCast:
1619 return true;
1620
1621 case CK_BaseToDerivedMemberPointer:
1622 case CK_DerivedToBaseMemberPointer:
1623 case CK_MemberPointerToBoolean:
1624 case CK_NullToMemberPointer:
1625 case CK_ReinterpretMemberPointer:
1626 // FIXME: ABI-dependent.
1627 return false;
1628
1629 case CK_AnyPointerToBlockPointerCast:
1630 case CK_BlockPointerToObjCPointerCast:
1631 case CK_CPointerToObjCPointerCast:
1632 case CK_ObjCObjectLValueCast:
1633 case CK_IntToOCLSampler:
1634 case CK_ZeroToOCLOpaqueType:
1635 // FIXME: Check these.
1636 return false;
1637
1638 case CK_FixedPointCast:
1639 case CK_FixedPointToBoolean:
1640 case CK_FixedPointToFloating:
1641 case CK_FixedPointToIntegral:
1642 case CK_FloatingToFixedPoint:
1643 case CK_IntegralToFixedPoint:
1644 // FIXME: Do all fixed-point types represent zero as all 0 bits?
1645 return false;
1646
1647 case CK_AddressSpaceConversion:
1648 case CK_BaseToDerived:
1649 case CK_DerivedToBase:
1650 case CK_Dynamic:
1651 case CK_NullToPointer:
1652 case CK_PointerToBoolean:
1653 // FIXME: Preserves zeroes only if zero pointers and null pointers have the
1654 // same representation in all involved address spaces.
1655 return false;
1656
1657 case CK_ARCConsumeObject:
1658 case CK_ARCExtendBlockObject:
1659 case CK_ARCProduceObject:
1660 case CK_ARCReclaimReturnedObject:
1661 case CK_CopyAndAutoreleaseBlockObject:
1662 case CK_ArrayToPointerDecay:
1663 case CK_FunctionToPointerDecay:
1664 case CK_BuiltinFnToFnPtr:
1665 case CK_Dependent:
1666 case CK_LValueBitCast:
1667 case CK_LValueToRValue:
1668 case CK_LValueToRValueBitCast:
1669 case CK_UncheckedDerivedToBase:
1670 case CK_HLSLArrayRValue:
1671 return false;
1672 }
1673 llvm_unreachable("Unhandled clang::CastKind enum");
1674}
1675
1676/// isSimpleZero - If emitting this value will obviously just cause a store of
1677/// zero to memory, return true. This can return false if uncertain, so it just
1678/// handles simple cases.
1679static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1680 E = E->IgnoreParens();
1681 while (auto *CE = dyn_cast<CastExpr>(E)) {
1682 if (!castPreservesZero(CE))
1683 break;
1684 E = CE->getSubExpr()->IgnoreParens();
1685 }
1686
1687 // 0
1688 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1689 return IL->getValue() == 0;
1690 // +0.0
1691 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1692 return FL->getValue().isPosZero();
1693 // int()
1696 return true;
1697 // (int*)0 - Null pointer expressions.
1698 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1699 return ICE->getCastKind() == CK_NullToPointer &&
1701 !E->HasSideEffects(CGF.getContext());
1702 // '\0'
1703 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1704 return CL->getValue() == 0;
1705
1706 // Otherwise, hard case: conservatively return false.
1707 return false;
1708}
1709
1710void AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1711 QualType type = LV.getType();
1712 // FIXME: Ignore result?
1713 // FIXME: Are initializers affected by volatile?
1714 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1715 // Storing "i32 0" to a zero'd memory location is a noop.
1716 return;
1718 return EmitNullInitializationToLValue(LV);
1719 } else if (isa<NoInitExpr>(E)) {
1720 // Do nothing.
1721 return;
1722 } else if (type->isReferenceType()) {
1723 RValue RV = CGF.EmitReferenceBindingToExpr(E);
1724 return CGF.EmitStoreThroughLValue(RV, LV);
1725 }
1726
1727 CGF.EmitInitializationToLValue(E, LV, Dest.isZeroed());
1728}
1729
1730void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1731 QualType type = lv.getType();
1732
1733 // If the destination slot is already zeroed out before the aggregate is
1734 // copied into it, we don't have to emit any zeros here.
1735 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1736 return;
1737
1738 if (CGF.hasScalarEvaluationKind(type)) {
1739 // For non-aggregates, we can store the appropriate null constant.
1740 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1741 // Note that the following is not equivalent to
1742 // EmitStoreThroughBitfieldLValue for ARC types.
1743 if (lv.isBitField()) {
1745 } else {
1746 assert(lv.isSimple());
1747 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1748 }
1749 } else {
1750 // There's a potential optimization opportunity in combining
1751 // memsets; that would be easy for arrays, but relatively
1752 // difficult for structures with the current code.
1753 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1754 }
1755}
1756
1757void AggExprEmitter::VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
1758 VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
1760 E->getArrayFiller());
1761}
1762
1763void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1764 if (E->hadArrayRangeDesignator())
1765 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1766
1767 if (E->isTransparent())
1768 return Visit(E->getInit(0));
1769
1770 VisitCXXParenListOrInitListExpr(
1771 E, E->inits(), E->getInitializedFieldInUnion(), E->getArrayFiller());
1772}
1773
1774void AggExprEmitter::VisitCXXParenListOrInitListExpr(
1775 Expr *ExprToVisit, ArrayRef<Expr *> InitExprs,
1776 FieldDecl *InitializedFieldInUnion, Expr *ArrayFiller) {
1777#if 0
1778 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1779 // (Length of globals? Chunks of zeroed-out space?).
1780 //
1781 // If we can, prefer a copy from a global; this is a lot less code for long
1782 // globals, and it's easier for the current optimizers to analyze.
1783 if (llvm::Constant *C =
1784 CGF.CGM.EmitConstantExpr(ExprToVisit, ExprToVisit->getType(), &CGF)) {
1785 llvm::GlobalVariable* GV =
1786 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1787 llvm::GlobalValue::InternalLinkage, C, "");
1788 EmitFinalDestCopy(ExprToVisit->getType(),
1789 CGF.MakeAddrLValue(GV, ExprToVisit->getType()));
1790 return;
1791 }
1792#endif
1793
1794 // HLSL initialization lists in the AST are an expansion which can contain
1795 // side-effecting expressions wrapped in opaque value expressions. To properly
1796 // emit these we need to emit the opaque values before we emit the argument
1797 // expressions themselves. This is a little hacky, but it prevents us needing
1798 // to do a bigger AST-level change for a language feature that we need
1799 // deprecate in the near future. See related HLSL language proposals:
1800 // * 0005-strict-initializer-lists.md
1801 // * https://github.com/microsoft/hlsl-specs/pull/325
1802 if (CGF.getLangOpts().HLSL && isa<InitListExpr>(ExprToVisit))
1804 CGF, cast<InitListExpr>(ExprToVisit));
1805
1806 AggValueSlot Dest = EnsureSlot(ExprToVisit->getType());
1807
1808 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), ExprToVisit->getType());
1809
1810 // Handle initialization of an array.
1811 if (ExprToVisit->getType()->isConstantArrayType()) {
1812 auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1813 EmitArrayInit(Dest.getAddress(), AType, ExprToVisit->getType(), ExprToVisit,
1814 InitExprs, ArrayFiller);
1815 return;
1816 } else if (ExprToVisit->getType()->isVariableArrayType()) {
1817 // A variable array type that has an initializer can only do empty
1818 // initialization. And because this feature is not exposed as an extension
1819 // in C++, we can safely memset the array memory to zero.
1820 assert(InitExprs.size() == 0 &&
1821 "you can only use an empty initializer with VLAs");
1822 CGF.EmitNullInitialization(Dest.getAddress(), ExprToVisit->getType());
1823 return;
1824 }
1825
1826 assert(ExprToVisit->getType()->isRecordType() &&
1827 "Only support structs/unions here!");
1828
1829 // Do struct initialization; this code just sets each individual member
1830 // to the approprate value. This makes bitfield support automatic;
1831 // the disadvantage is that the generated code is more difficult for
1832 // the optimizer, especially with bitfields.
1833 unsigned NumInitElements = InitExprs.size();
1834 RecordDecl *record = ExprToVisit->getType()->castAsRecordDecl();
1835
1836 // We'll need to enter cleanup scopes in case any of the element
1837 // initializers throws an exception.
1838 CodeGenFunction::CleanupDeactivationScope DeactivateCleanups(CGF);
1839
1840 unsigned curInitIndex = 0;
1841
1842 // Emit initialization of base classes.
1843 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1844 assert(NumInitElements >= CXXRD->getNumBases() &&
1845 "missing initializer for base class");
1846 for (auto &Base : CXXRD->bases()) {
1847 assert(!Base.isVirtual() && "should not see vbases here");
1848 auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1850 Dest.getAddress(), CXXRD, BaseRD,
1851 /*isBaseVirtual*/ false);
1852 AggValueSlot AggSlot = AggValueSlot::forAddr(
1853 V, Qualifiers(), AggValueSlot::IsDestructed,
1855 CGF.getOverlapForBaseInit(CXXRD, BaseRD, Base.isVirtual()));
1856 CGF.EmitAggExpr(InitExprs[curInitIndex++], AggSlot);
1857
1858 if (QualType::DestructionKind dtorKind =
1859 Base.getType().isDestructedType())
1860 CGF.pushDestroyAndDeferDeactivation(dtorKind, V, Base.getType());
1861 }
1862 }
1863
1864 // Prepare a 'this' for CXXDefaultInitExprs.
1865 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1866
1867 const bool ZeroInitPadding =
1868 CGF.CGM.shouldZeroInitPadding() && !Dest.isZeroed();
1869
1870 if (record->isUnion()) {
1871 // Only initialize one field of a union. The field itself is
1872 // specified by the initializer list.
1873 if (!InitializedFieldInUnion) {
1874 // Empty union; we have nothing to do.
1875
1876#ifndef NDEBUG
1877 // Make sure that it's really an empty and not a failure of
1878 // semantic analysis.
1879 for (const auto *Field : record->fields())
1880 assert(
1881 (Field->isUnnamedBitField() || Field->isAnonymousStructOrUnion()) &&
1882 "Only unnamed bitfields or anonymous class allowed");
1883#endif
1884 return;
1885 }
1886
1887 // FIXME: volatility
1888 FieldDecl *Field = InitializedFieldInUnion;
1889
1890 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1891 if (NumInitElements) {
1892 // Store the initializer into the field
1893 EmitInitializationToLValue(InitExprs[0], FieldLoc);
1894 if (ZeroInitPadding) {
1895 uint64_t TotalSize = CGF.getContext().toBits(
1896 Dest.getPreferredSize(CGF.getContext(), DestLV.getType()));
1897 uint64_t FieldSize = CGF.getContext().getTypeSize(FieldLoc.getType());
1898 DoZeroInitPadding(FieldSize, TotalSize, nullptr);
1899 }
1900 } else {
1901 // Default-initialize to null.
1902 if (ZeroInitPadding)
1903 EmitNullInitializationToLValue(DestLV);
1904 else
1905 EmitNullInitializationToLValue(FieldLoc);
1906 }
1907 return;
1908 }
1909
1910 // Here we iterate over the fields; this makes it simpler to both
1911 // default-initialize fields and skip over unnamed fields.
1912 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(record);
1913 uint64_t PaddingStart = 0;
1914
1915 for (const auto *field : record->fields()) {
1916 // We're done once we hit the flexible array member.
1917 if (field->getType()->isIncompleteArrayType())
1918 break;
1919
1920 // Always skip anonymous bitfields.
1921 if (field->isUnnamedBitField())
1922 continue;
1923
1924 // We're done if we reach the end of the explicit initializers, we
1925 // have a zeroed object, and the rest of the fields are
1926 // zero-initializable.
1927 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1928 CGF.getTypes().isZeroInitializable(ExprToVisit->getType()))
1929 break;
1930
1931 if (ZeroInitPadding)
1932 DoZeroInitPadding(PaddingStart,
1933 Layout.getFieldOffset(field->getFieldIndex()), field);
1934
1935 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1936 // We never generate write-barries for initialized fields.
1937 LV.setNonGC(true);
1938
1939 if (curInitIndex < NumInitElements) {
1940 // Store the initializer into the field.
1941 EmitInitializationToLValue(InitExprs[curInitIndex++], LV);
1942 } else {
1943 // We're out of initializers; default-initialize to null
1944 EmitNullInitializationToLValue(LV);
1945 }
1946
1947 // Push a destructor if necessary.
1948 // FIXME: if we have an array of structures, all explicitly
1949 // initialized, we can end up pushing a linear number of cleanups.
1950 if (QualType::DestructionKind dtorKind =
1951 field->getType().isDestructedType()) {
1952 assert(LV.isSimple());
1953 if (dtorKind) {
1955 field->getType(),
1956 CGF.getDestroyer(dtorKind), false);
1957 }
1958 }
1959 }
1960 if (ZeroInitPadding) {
1961 uint64_t TotalSize = CGF.getContext().toBits(
1962 Dest.getPreferredSize(CGF.getContext(), DestLV.getType()));
1963 DoZeroInitPadding(PaddingStart, TotalSize, nullptr);
1964 }
1965}
1966
1967void AggExprEmitter::DoZeroInitPadding(uint64_t &PaddingStart,
1968 uint64_t PaddingEnd,
1969 const FieldDecl *NextField) {
1970
1971 auto InitBytes = [&](uint64_t StartBit, uint64_t EndBit) {
1972 CharUnits Start = CGF.getContext().toCharUnitsFromBits(StartBit);
1973 CharUnits End = CGF.getContext().toCharUnitsFromBits(EndBit);
1975 if (!Start.isZero())
1976 Addr = Builder.CreateConstGEP(Addr, Start.getQuantity());
1977 llvm::Constant *SizeVal = Builder.getInt64((End - Start).getQuantity());
1978 CGF.Builder.CreateMemSet(Addr, Builder.getInt8(0), SizeVal, false);
1979 };
1980
1981 if (NextField != nullptr && NextField->isBitField()) {
1982 // For bitfield, zero init StorageSize before storing the bits. So we don't
1983 // need to handle big/little endian.
1984 const CGRecordLayout &RL =
1985 CGF.getTypes().getCGRecordLayout(NextField->getParent());
1986 const CGBitFieldInfo &Info = RL.getBitFieldInfo(NextField);
1987 uint64_t StorageStart = CGF.getContext().toBits(Info.StorageOffset);
1988 if (StorageStart + Info.StorageSize > PaddingStart) {
1989 if (StorageStart > PaddingStart)
1990 InitBytes(PaddingStart, StorageStart);
1991 Address Addr = Dest.getAddress();
1992 if (!Info.StorageOffset.isZero())
1993 Addr = Builder.CreateConstGEP(Addr.withElementType(CGF.CharTy),
1994 Info.StorageOffset.getQuantity());
1995 Addr = Addr.withElementType(
1996 llvm::Type::getIntNTy(CGF.getLLVMContext(), Info.StorageSize));
1997 Builder.CreateStore(Builder.getIntN(Info.StorageSize, 0), Addr);
1998 PaddingStart = StorageStart + Info.StorageSize;
1999 }
2000 return;
2001 }
2002
2003 if (PaddingStart < PaddingEnd)
2004 InitBytes(PaddingStart, PaddingEnd);
2005 if (NextField != nullptr)
2006 PaddingStart =
2007 PaddingEnd + CGF.getContext().getTypeSize(NextField->getType());
2008}
2009
2010void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
2011 llvm::Value *outerBegin) {
2012 // Emit the common subexpression.
2013 CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
2014
2015 Address destPtr = EnsureSlot(E->getType()).getAddress();
2016 uint64_t numElements = E->getArraySize().getZExtValue();
2017
2018 if (!numElements)
2019 return;
2020
2021 // destPtr is an array*. Construct an elementType* by drilling down a level.
2022 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2023 llvm::Value *indices[] = {zero, zero};
2024 llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getElementType(),
2025 destPtr.emitRawPointer(CGF),
2026 indices, "arrayinit.begin");
2027
2028 // Prepare to special-case multidimensional array initialization: we avoid
2029 // emitting multiple destructor loops in that case.
2030 if (!outerBegin)
2031 outerBegin = begin;
2032 ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
2033
2034 QualType elementType =
2036 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2037 CharUnits elementAlign =
2038 destPtr.getAlignment().alignmentOfArrayElement(elementSize);
2039 llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
2040
2041 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2042 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
2043
2044 // Jump into the body.
2045 CGF.EmitBlock(bodyBB);
2046 llvm::PHINode *index =
2047 Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
2048 index->addIncoming(zero, entryBB);
2049 llvm::Value *element =
2050 Builder.CreateInBoundsGEP(llvmElementType, begin, index);
2051
2053 CGF.ConvergenceTokenStack.push_back(CGF.emitConvergenceLoopToken(bodyBB));
2054
2055 // Prepare for a cleanup.
2056 QualType::DestructionKind dtorKind = elementType.isDestructedType();
2057 EHScopeStack::stable_iterator cleanup;
2058 if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
2059 if (outerBegin->getType() != element->getType())
2060 outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
2061 CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
2062 elementAlign,
2063 CGF.getDestroyer(dtorKind));
2065 } else {
2066 dtorKind = QualType::DK_none;
2067 }
2068
2069 // Emit the actual filler expression.
2070 {
2071 // Temporaries created in an array initialization loop are destroyed
2072 // at the end of each iteration.
2073 CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
2074 CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
2075 LValue elementLV = CGF.MakeAddrLValue(
2076 Address(element, llvmElementType, elementAlign), elementType);
2077
2078 if (InnerLoop) {
2079 // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
2080 auto elementSlot = AggValueSlot::forLValue(
2081 elementLV, AggValueSlot::IsDestructed,
2084 AggExprEmitter(CGF, elementSlot, false)
2085 .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
2086 } else
2087 EmitInitializationToLValue(E->getSubExpr(), elementLV);
2088 }
2089
2090 // Move on to the next element.
2091 llvm::Value *nextIndex = Builder.CreateNUWAdd(
2092 index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
2093 index->addIncoming(nextIndex, Builder.GetInsertBlock());
2094
2095 // Leave the loop if we're done.
2096 llvm::Value *done = Builder.CreateICmpEQ(
2097 nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
2098 "arrayinit.done");
2099 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
2100 Builder.CreateCondBr(done, endBB, bodyBB);
2101
2103 CGF.ConvergenceTokenStack.pop_back();
2104
2105 CGF.EmitBlock(endBB);
2106
2107 // Leave the partial-array cleanup if we entered one.
2108 if (dtorKind)
2109 CGF.DeactivateCleanupBlock(cleanup, index);
2110}
2111
2112void AggExprEmitter::VisitDesignatedInitUpdateExpr(
2113 DesignatedInitUpdateExpr *E) {
2114 AggValueSlot Dest = EnsureSlot(E->getType());
2115
2116 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
2117 EmitInitializationToLValue(E->getBase(), DestLV);
2118 VisitInitListExpr(E->getUpdater());
2119}
2120
2121//===----------------------------------------------------------------------===//
2122// Entry Points into this File
2123//===----------------------------------------------------------------------===//
2124
2125/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
2126/// non-zero bytes that will be stored when outputting the initializer for the
2127/// specified initializer expression.
2129 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2130 E = MTE->getSubExpr();
2131 E = E->IgnoreParenNoopCasts(CGF.getContext());
2132
2133 // 0 and 0.0 won't require any non-zero stores!
2134 if (isSimpleZero(E, CGF))
2135 return CharUnits::Zero();
2136
2137 // If this is an initlist expr, sum up the size of sizes of the (present)
2138 // elements. If this is something weird, assume the whole thing is non-zero.
2139 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2140 while (ILE && ILE->isTransparent())
2141 ILE = dyn_cast<InitListExpr>(ILE->getInit(0));
2142 if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
2143 return CGF.getContext().getTypeSizeInChars(E->getType());
2144
2145 // InitListExprs for structs have to be handled carefully. If there are
2146 // reference members, we need to consider the size of the reference, not the
2147 // referencee. InitListExprs for unions and arrays can't have references.
2148 if (const RecordType *RT = E->getType()->getAsCanonical<RecordType>()) {
2149 if (!RT->isUnionType()) {
2150 RecordDecl *SD = RT->getDecl()->getDefinitionOrSelf();
2151 CharUnits NumNonZeroBytes = CharUnits::Zero();
2152
2153 unsigned ILEElement = 0;
2154 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
2155 while (ILEElement != CXXRD->getNumBases())
2156 NumNonZeroBytes +=
2157 GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
2158 for (const auto *Field : SD->fields()) {
2159 // We're done once we hit the flexible array member or run out of
2160 // InitListExpr elements.
2161 if (Field->getType()->isIncompleteArrayType() ||
2162 ILEElement == ILE->getNumInits())
2163 break;
2164 if (Field->isUnnamedBitField())
2165 continue;
2166
2167 const Expr *E = ILE->getInit(ILEElement++);
2168
2169 // Reference values are always non-null and have the width of a pointer.
2170 if (Field->getType()->isReferenceType())
2171 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
2173 else
2174 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
2175 }
2176
2177 return NumNonZeroBytes;
2178 }
2179 }
2180
2181 // FIXME: This overestimates the number of non-zero bytes for bit-fields.
2182 CharUnits NumNonZeroBytes = CharUnits::Zero();
2183 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
2184 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
2185 return NumNonZeroBytes;
2186}
2187
2188/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
2189/// zeros in it, emit a memset and avoid storing the individual zeros.
2190///
2191static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
2192 CodeGenFunction &CGF) {
2193 // If the slot is already known to be zeroed, nothing to do. Don't mess with
2194 // volatile stores.
2195 if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
2196 return;
2197
2198 // C++ objects with a user-declared constructor don't need zero'ing.
2199 if (CGF.getLangOpts().CPlusPlus)
2200 if (const RecordType *RT = CGF.getContext()
2202 ->getAsCanonical<RecordType>()) {
2203 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
2205 return;
2206 }
2207
2208 // If the type is 16-bytes or smaller, prefer individual stores over memset.
2209 CharUnits Size = Slot.getPreferredSize(CGF.getContext(), E->getType());
2210 if (Size <= CharUnits::fromQuantity(16))
2211 return;
2212
2213 // Check to see if over 3/4 of the initializer are known to be zero. If so,
2214 // we prefer to emit memset + individual stores for the rest.
2215 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
2216 if (NumNonZeroBytes * 4 > Size)
2217 return;
2218
2219 // Okay, it seems like a good idea to use an initial memset, emit the call.
2220 llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
2221
2222 Address Loc = Slot.getAddress().withElementType(CGF.Int8Ty);
2223 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
2224
2225 // Tell the AggExprEmitter that the slot is known zero.
2226 Slot.setZeroed();
2227}
2228
2229/// EmitAggExpr - Emit the computation of the specified expression of aggregate
2230/// type. The result is computed into DestPtr. Note that if DestPtr is null,
2231/// the value of the aggregate expression is not needed. If VolatileDest is
2232/// true, DestPtr cannot be 0.
2234 assert(E && hasAggregateEvaluationKind(E->getType()) &&
2235 "Invalid aggregate expression to emit");
2236 assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
2237 "slot has bits but no address");
2238
2239 // Optimize the slot if possible.
2240 CheckAggExprForMemSetUse(Slot, E, *this);
2241
2242 AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr *>(E));
2243}
2244
2255
2257 const LValue &Src,
2258 ExprValueKind SrcKind) {
2259 return AggExprEmitter(*this, Dest, Dest.isIgnored())
2260 .EmitFinalDestCopy(Type, Src, SrcKind);
2261}
2262
2265 if (!FD->hasAttr<NoUniqueAddressAttr>() || !FD->getType()->isRecordType())
2267
2268 // Empty fields can overlap earlier fields.
2269 if (FD->getType()->getAsCXXRecordDecl()->isEmpty())
2271
2272 // If the field lies entirely within the enclosing class's nvsize, its tail
2273 // padding cannot overlap any already-initialized object. (The only subobjects
2274 // with greater addresses that might already be initialized are vbases.)
2275 const RecordDecl *ClassRD = FD->getParent();
2276 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(ClassRD);
2277 if (Layout.getFieldOffset(FD->getFieldIndex()) +
2278 getContext().getTypeSize(FD->getType()) <=
2279 (uint64_t)getContext().toBits(Layout.getNonVirtualSize()))
2281
2282 // The tail padding may contain values we need to preserve.
2284}
2285
2287 const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual) {
2288 // If the most-derived object is a field declared with [[no_unique_address]],
2289 // the tail padding of any virtual base could be reused for other subobjects
2290 // of that field's class.
2291 if (IsVirtual)
2293
2294 // Empty bases can overlap earlier bases.
2295 if (BaseRD->isEmpty())
2297
2298 // If the base class is laid out entirely within the nvsize of the derived
2299 // class, its tail padding cannot yet be initialized, so we can issue
2300 // stores at the full width of the base class.
2301 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2302 if (Layout.getBaseClassOffset(BaseRD) +
2303 getContext().getASTRecordLayout(BaseRD).getSize() <=
2304 Layout.getNonVirtualSize())
2306
2307 // The tail padding may contain values we need to preserve.
2309}
2310
2312 AggValueSlot::Overlap_t MayOverlap,
2313 bool isVolatile) {
2314 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
2315
2316 Address DestPtr = Dest.getAddress();
2317 Address SrcPtr = Src.getAddress();
2318
2319 if (getLangOpts().CPlusPlus) {
2320 if (const auto *Record = Ty->getAsCXXRecordDecl()) {
2321 assert((Record->hasTrivialCopyConstructor() ||
2322 Record->hasTrivialCopyAssignment() ||
2323 Record->hasTrivialMoveConstructor() ||
2324 Record->hasTrivialMoveAssignment() ||
2325 Record->hasAttr<TrivialABIAttr>() || Record->isUnion() ||
2326 // HLSL uses aggregate-copy for user-defined record types.
2327 (getLangOpts().HLSL && !Record->isHLSLBuiltinRecord())) &&
2328 "Trying to aggregate-copy a type without a trivial copy/move "
2329 "constructor or assignment operator");
2330 // Ignore empty classes in C++.
2331 if (Record->isEmpty())
2332 return;
2333 }
2334 }
2335
2336 if (getLangOpts().CUDAIsDevice) {
2338 if (getTargetHooks().emitCUDADeviceBuiltinSurfaceDeviceCopy(*this, Dest,
2339 Src))
2340 return;
2341 } else if (Ty->isCUDADeviceBuiltinTextureType()) {
2342 if (getTargetHooks().emitCUDADeviceBuiltinTextureDeviceCopy(*this, Dest,
2343 Src))
2344 return;
2345 }
2346 }
2347
2348 assert(Ty.getAddressSpace() != LangAS::hlsl_constant &&
2349 "copies of aggregates in hlsl_constant address space should be "
2350 "handled earlier by the HLSL runtime");
2351
2352 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
2353 // C99 6.5.16.1p3, which states "If the value being stored in an object is
2354 // read from another object that overlaps in anyway the storage of the first
2355 // object, then the overlap shall be exact and the two objects shall have
2356 // qualified or unqualified versions of a compatible type."
2357 //
2358 // memcpy is not defined if the source and destination pointers are exactly
2359 // equal, but other compilers do this optimization, and almost every memcpy
2360 // implementation handles this case safely. If there is a libc that does not
2361 // safely handle this, we can add a target hook.
2362
2363 // Get data size info for this aggregate. Don't copy the tail padding if this
2364 // might be a potentially-overlapping subobject, since the tail padding might
2365 // be occupied by a different object. Otherwise, copying it is fine.
2367 if (MayOverlap)
2368 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
2369 else
2370 TypeInfo = getContext().getTypeInfoInChars(Ty);
2371
2372 llvm::Value *SizeVal = nullptr;
2373 if (TypeInfo.Width.isZero()) {
2374 // But note that getTypeInfo returns 0 for a VLA.
2375 if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
2376 getContext().getAsArrayType(Ty))) {
2377 QualType BaseEltTy;
2378 SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
2379 TypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
2380 assert(!TypeInfo.Width.isZero());
2381 SizeVal = Builder.CreateNUWMul(
2382 SizeVal,
2383 llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity()));
2384 }
2385 }
2386 if (!SizeVal) {
2387 SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.Width.getQuantity());
2388 }
2389
2390 // FIXME: If we have a volatile struct, the optimizer can remove what might
2391 // appear to be `extra' memory ops:
2392 //
2393 // volatile struct { int i; } a, b;
2394 //
2395 // int main() {
2396 // a = b;
2397 // a = b;
2398 // }
2399 //
2400 // we need to use a different call here. We use isVolatile to indicate when
2401 // either the source or the destination is volatile.
2402
2403 DestPtr = DestPtr.withElementType(Int8Ty);
2404 SrcPtr = SrcPtr.withElementType(Int8Ty);
2405
2406 // Don't do any of the memmove_collectable tests if GC isn't set.
2407 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
2408 // fall through
2409 } else if (const auto *Record = Ty->getAsRecordDecl()) {
2410 if (Record->hasObjectMember()) {
2411 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2412 SizeVal);
2413 return;
2414 }
2415 } else if (Ty->isArrayType()) {
2416 QualType BaseType = getContext().getBaseElementType(Ty);
2417 if (const auto *Record = BaseType->getAsRecordDecl()) {
2418 if (Record->hasObjectMember()) {
2419 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
2420 SizeVal);
2421 return;
2422 }
2423 }
2424 }
2425
2426 auto *Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
2427 addInstToCurrentSourceAtom(Inst, nullptr);
2428 emitPFPPostCopyUpdates(DestPtr, SrcPtr, Ty);
2429
2430 // Determine the metadata to describe the position of any padding in this
2431 // memcpy, as well as the TBAA tags for the members of the struct, in case
2432 // the optimizer wishes to expand it in to scalar memory operations.
2433 if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
2434 Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
2435
2436 if (CGM.getCodeGenOpts().NewStructPathTBAA) {
2437 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
2438 Dest.getTBAAInfo(), Src.getTBAAInfo());
2439 CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
2440 }
2441}
Defines the clang::ASTContext interface.
#define V(N, I)
CompareKind
@ CK_Greater
@ CK_Less
@ CK_Equal
static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF)
GetNumNonZeroBytesInInit - Get an approximate count of the number of non-zero bytes that will be stor...
static Expr * findPeephole(Expr *op, CastKind kind, const ASTContext &ctx)
Attempt to look through various unimportant expressions to find a cast of the given kind.
static bool isBlockVarRef(const Expr *E)
Is the value of the given expression possibly a reference to or into a __block variable?
static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF)
isSimpleZero - If emitting this value will obviously just cause a store of zero to memory,...
static llvm::Value * EmitCompare(CGBuilderTy &Builder, CodeGenFunction &CGF, const BinaryOperator *E, llvm::Value *LHS, llvm::Value *RHS, CompareKind Kind, const char *NameSuffix="")
static void EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue DestVal, LValue SrcVal, SourceLocation Loc)
static bool castPreservesZero(const CastExpr *CE)
Determine whether the given cast kind is known to always convert values with all zero bits in their v...
static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E, CodeGenFunction &CGF)
CheckAggExprForMemSetUse - If the initializer is large and has a lot of zeros in it,...
static void EmitHLSLScalarElementwiseAndSplatCasts(CodeGenFunction &CGF, LValue DestVal, llvm::Value *SrcVal, QualType SrcTy, SourceLocation Loc)
static bool isTrivialFiller(Expr *e)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
llvm::MachO::Record Record
Definition MachO.h:31
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
llvm::json::Array Array
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned getTargetAddressSpace(LangAS AS) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
llvm::APInt getArraySize() const
Definition Expr.h:5993
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5986
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
QualType getElementType() const
Definition TypeBase.h:3798
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
Expr * getRHS() const
Definition Expr.h:4096
Opcode getOpcode() const
Definition Expr.h:4089
CXXTemporary * getTemporary()
Definition ExprCXX.h:1515
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
bool constructsVBase() const
Determine whether this constructor is actually constructing a base class (rather than a complete obje...
Definition ExprCXX.h:1796
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
bool inheritedFromVBase() const
Determine whether the inherited constructor is inherited from a virtual base of the object we constru...
Definition ExprCXX.h:1806
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
FieldDecl * getInitializedFieldInUnion()
Definition ExprCXX.h:5215
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition DeclCXX.h:1352
bool isTriviallyCopyable() const
Determine whether this class is considered trivially copyable per (C++11 [class]p6).
Definition DeclCXX.cpp:611
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition DeclCXX.h:1312
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition DeclCXX.h:1289
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition DeclCXX.h:1339
bool hasUserDeclaredConstructor() const
Determine whether this class has any user-declared constructors.
Definition DeclCXX.h:781
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4890
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
bool isValid() const
Definition Address.h:177
An aggregate value slot.
Definition CGValue.h:551
void setVolatile(bool flag)
Definition CGValue.h:670
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
Address getAddress() const
Definition CGValue.h:691
CharUnits getPreferredSize(ASTContext &Ctx, QualType Type) const
Get the preferred size to use when storing a value to this slot.
Definition CGValue.h:729
NeedsGCBarriers_t requiresGCollection() const
Definition CGValue.h:681
void setExternallyDestructed(bool destructed=true)
Definition CGValue.h:660
void setZeroed(bool V=true)
Definition CGValue.h:721
IsZeroed_t isZeroed() const
Definition CGValue.h:722
Qualifiers getQualifiers() const
Definition CGValue.h:664
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:649
IsAliased_t isPotentiallyAliased() const
Definition CGValue.h:701
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
IsDestructed_t isExternallyDestructed() const
Definition CGValue.h:657
Overlap_t mayOverlap() const
Definition CGValue.h:705
RValue asRValue() const
Definition CGValue.h:713
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Definition CGValue.h:687
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:430
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
virtual llvm::Value * EmitMemberPointerComparison(CodeGenFunction &CGF, llvm::Value *L, llvm::Value *R, const MemberPointerType *MPT, bool Inequality)
Emit a comparison between two member pointers. Returns an i1.
Definition CGCXXABI.cpp:84
bool emitBufferCopy(CodeGenFunction &CGF, const Expr *E, const LValue &SrcLV, AggValueSlot &DestSlot)
bool emitGlobalResourceArray(CodeGenFunction &CGF, const Expr *E, AggValueSlot &DestSlot)
void emitInitListOpaqueValues(CodeGenFunction &CGF, InitListExpr *E)
virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF, Address DestPtr, Address SrcPtr, llvm::Value *Size)=0
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition CGObjC.cpp:591
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD)
Determine whether a field initialization may overlap some other object.
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
void callCStructMoveConstructor(LValue Dst, LValue Src)
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition CGClass.cpp:281
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
pushRegularPartialArrayCleanup - Push an EH cleanup to destroy already-constructed elements of the gi...
Definition CGDecl.cpp:2615
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
SmallVector< llvm::ConvergenceControlInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition CGExpr.cpp:3054
bool hasVolatileMember(QualType T)
hasVolatileMember - returns true if aggregate type has a volatile member.
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
Definition CGCall.cpp:6699
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7384
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD, const CXXRecordDecl *BaseRD, bool IsVirtual)
Determine whether a base class initialization may overlap some other object.
const LangOptions & getLangOpts() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:700
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition CGExpr.cpp:7212
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2299
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to destroy already-constructed elements ...
Definition CGDecl.cpp:2599
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2272
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition CGExpr.cpp:7389
void CreateCoercedStore(llvm::Value *Src, QualType SrcFETy, Address Dst, llvm::TypeSize DstSize, bool DstIsVolatile)
Create a store to.
Definition CGCall.cpp:1681
llvm::ConvergenceControlInst * emitConvergenceLoopToken(llvm::BasicBlock *BB)
Definition CGStmt.cpp:3522
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
const TargetInfo & getTarget() const
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:259
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6475
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2542
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
Definition CGDecl.cpp:2324
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
void callCStructCopyAssignmentOperator(LValue Dst, LValue Src)
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
void callCStructCopyConstructor(LValue Dst, LValue Src)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1357
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:5963
Address GetAddressOfDirectBaseInCompleteClass(Address Value, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, bool BaseIsVirtual)
GetAddressOfBaseOfCompleteClass - Convert the given pointer to a complete class to the given direct b...
Definition CGClass.cpp:214
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:160
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6414
const TargetCodeGenInfo & getTargetHooks() const
void EmitLifetimeEnd(llvm::Value *Addr)
Definition CGDecl.cpp:1369
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:232
void callCStructMoveAssignmentOperator(LValue Dst, LValue Src)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2793
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2352
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:560
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:281
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
CleanupKind getCleanupKind(QualType::DestructionKind kind)
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:941
void emitPFPPostCopyUpdates(Address DestPtr, Address SrcPtr, QualType Ty)
Copy all PFP fields from SrcPtr to DestPtr while updating signatures, assuming that DestPtr was alrea...
CodeGenTypes & getTypes() const
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
Definition CGExpr.cpp:7393
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1702
void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, bool ForVirtualBase, Address This, bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E)
Emit a call to a constructor inherited from a base class, passing the current constructor's arguments...
Definition CGClass.cpp:2403
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Definition CGExpr.cpp:340
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
static bool hasAggregateEvaluationKind(QualType T)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV)
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1737
llvm::LLVMContext & getLLVMContext()
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:643
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1417
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Module & getModule() const
bool isPaddedAtomicType(QualType type)
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
ASTContext & getContext() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
bool isPointerZeroInitializable(QualType T)
Check if the pointer type can be zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition CGCleanup.h:654
LValue - This represents an lvalue references.
Definition CGValue.h:183
Address getAddress() const
Definition CGValue.h:373
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:347
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
llvm::Value * getAggregatePointer(QualType PointeeType, CodeGenFunction &CGF) const
Definition CGValue.h:89
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
bool isComplex() const
Definition CGValue.h:65
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
virtual LangAS getSRetAddrSpace(const CXXRecordDecl *RD) const
Get the address space for an indirect (sret) return of the given type.
Definition TargetInfo.h:324
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
bool isPartial() const
True iff the comparison is not totally ordered.
const ValueInfo * getLess() const
const ValueInfo * getUnordered() const
const CXXRecordDecl * Record
The declaration for the comparison category type from the standard library.
const ValueInfo * getGreater() const
const ValueInfo * getEqualOrEquiv() const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
const Expr * getInitializer() const
Definition Expr.h:3639
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
bool hasAttr() const
Definition DeclBase.h:585
InitListExpr * getUpdater() const
Definition Expr.h:5939
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3126
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
Represents a member of a struct/union/class.
Definition Decl.h:3179
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3282
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3264
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3415
const Expr * getSubExpr() const
Definition Expr.h:1068
Describes an C or C++ initializer list.
Definition Expr.h:5305
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2471
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition Expr.h:5432
unsigned getNumInits() const
Definition Expr.h:5338
bool hadArrayRangeDesignator() const
Definition Expr.h:5486
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5408
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
ArrayRef< Expr * > inits() const
Definition Expr.h:5358
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
Definition ExprCXX.h:2110
Expr *const * const_capture_init_iterator
Const iterator that walks over the capture initialization arguments.
Definition ExprCXX.h:2084
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1407
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
bool isUnique() const
Definition Expr.h:1242
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
const Expr * getSubExpr() const
Definition Expr.h:2205
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2970
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
@ PCK_Struct
The type is a struct containing a field whose type is neither PCK_Trivial nor PCK_VolatileTrivial.
Definition TypeBase.h:1532
Represents a struct/union/class.
Definition Decl.h:4344
bool hasObjectMember() const
Definition Decl.h:4404
field_range fields() const
Definition Decl.h:4547
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4544
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4532
field_iterator field_begin() const
Definition Decl.cpp:5299
Encodes a location in the source.
CompoundStmt * getSubStmt()
Definition Expr.h:4618
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool isUnion() const
Definition Decl.h:3947
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:490
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8787
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8783
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8684
bool isReferenceType() const
Definition TypeBase.h:8708
bool isScalarType() const
Definition TypeBase.h:9156
bool isVariableArrayType() const
Definition TypeBase.h:8795
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5478
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2314
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5487
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2401
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5518
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Expr * getSubExpr() const
Definition Expr.h:2291
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
Represents a GCC generic vector type.
Definition TypeBase.h:4239
Definition SPIR.cpp:35
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< AtomicType > atomicType
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1539
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Result
The result type of a method or function.
Definition TypeBase.h:905
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * CharTy
char