1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This is the internal per-function state used for llvm translation.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
16 #include "CGBuilder.h"
17 #include "CGDebugInfo.h"
18 #include "CGLoopInfo.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenPGO.h"
22 #include "EHScopeStack.h"
23 #include "VarBypassDetector.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/CurrentSourceLocExprScope.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Basic/ABI.h"
31 #include "clang/Basic/CapturedStmt.h"
32 #include "clang/Basic/CodeGenOptions.h"
33 #include "clang/Basic/OpenMPKinds.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/MapVector.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/IR/ValueHandle.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Transforms/Utils/SanitizerStats.h"
56 class CXXDestructorDecl;
57 class CXXForRangeStmt;
61 class EnumConstantDecl;
63 class FunctionProtoType;
65 class ObjCContainerDecl;
66 class ObjCInterfaceDecl;
69 class ObjCImplementationDecl;
70 class ObjCPropertyImplDecl;
73 class ObjCForCollectionStmt;
75 class ObjCAtThrowStmt;
76 class ObjCAtSynchronizedStmt;
77 class ObjCAutoreleasePoolStmt;
79 namespace analyze_os_log {
80 class OSLogBufferLayout;
90 class BlockByrefHelpers;
93 class BlockFieldFlags;
94 class RegionCodeGenTy;
95 class TargetCodeGenInfo;
99 /// The kind of evaluation to perform on values of a particular
100 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
103 /// TODO: should vectors maybe be split out into their own thing?
104 enum TypeEvaluationKind {
110 #define LIST_SANITIZER_CHECKS \
111 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
112 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
113 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
114 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
115 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
116 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
117 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \
118 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \
119 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \
120 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
121 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
122 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
123 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
124 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
125 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \
126 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
127 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \
128 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
129 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \
130 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
131 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
132 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
133 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \
134 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
136 enum SanitizerHandler {
137 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
138 LIST_SANITIZER_CHECKS
139 #undef SANITIZER_CHECK
142 /// Helper class with most of the code for saving a value for a
143 /// conditional expression cleanup.
144 struct DominatingLLVMValue {
145 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
147 /// Answer whether the given value needs extra work to be saved.
148 static bool needsSaving(llvm::Value *value) {
149 // If it's not an instruction, we don't need to save.
150 if (!isa<llvm::Instruction>(value)) return false;
152 // If it's an instruction in the entry block, we don't need to save.
153 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
154 return (block != &block->getParent()->getEntryBlock());
157 static saved_type save(CodeGenFunction &CGF, llvm::Value *value);
158 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value);
161 /// A partial specialization of DominatingValue for llvm::Values that
162 /// might be llvm::Instructions.
163 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
165 static type restore(CodeGenFunction &CGF, saved_type value) {
166 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
170 /// A specialization of DominatingValue for Address.
171 template <> struct DominatingValue<Address> {
172 typedef Address type;
175 DominatingLLVMValue::saved_type SavedValue;
179 static bool needsSaving(type value) {
180 return DominatingLLVMValue::needsSaving(value.getPointer());
182 static saved_type save(CodeGenFunction &CGF, type value) {
183 return { DominatingLLVMValue::save(CGF, value.getPointer()),
184 value.getAlignment() };
186 static type restore(CodeGenFunction &CGF, saved_type value) {
187 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
192 /// A specialization of DominatingValue for RValue.
193 template <> struct DominatingValue<RValue> {
196 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
197 AggregateAddress, ComplexAddress };
202 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
203 : Value(v), K(k), Align(a) {}
206 static bool needsSaving(RValue value);
207 static saved_type save(CodeGenFunction &CGF, RValue value);
208 RValue restore(CodeGenFunction &CGF);
210 // implementations in CGCleanup.cpp
213 static bool needsSaving(type value) {
214 return saved_type::needsSaving(value);
216 static saved_type save(CodeGenFunction &CGF, type value) {
217 return saved_type::save(CGF, value);
219 static type restore(CodeGenFunction &CGF, saved_type value) {
220 return value.restore(CGF);
224 /// CodeGenFunction - This class organizes the per-function state that is used
225 /// while generating LLVM code.
226 class CodeGenFunction : public CodeGenTypeCache {
227 CodeGenFunction(const CodeGenFunction &) = delete;
228 void operator=(const CodeGenFunction &) = delete;
230 friend class CGCXXABI;
232 /// A jump destination is an abstract label, branching to which may
233 /// require a jump out through normal cleanups.
235 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
236 JumpDest(llvm::BasicBlock *Block,
237 EHScopeStack::stable_iterator Depth,
239 : Block(Block), ScopeDepth(Depth), Index(Index) {}
241 bool isValid() const { return Block != nullptr; }
242 llvm::BasicBlock *getBlock() const { return Block; }
243 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
244 unsigned getDestIndex() const { return Index; }
246 // This should be used cautiously.
247 void setScopeDepth(EHScopeStack::stable_iterator depth) {
252 llvm::BasicBlock *Block;
253 EHScopeStack::stable_iterator ScopeDepth;
257 CodeGenModule &CGM; // Per-module state.
258 const TargetInfo &Target;
260 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
261 LoopInfoStack LoopStack;
264 // Stores variables for which we can't generate correct lifetime markers
266 VarBypassDetector Bypasses;
268 // CodeGen lambda for loops and support for ordered clause
269 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
272 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
273 const unsigned, const bool)>
276 // Codegen lambda for loop bounds in worksharing loop constructs
277 typedef llvm::function_ref<std::pair<LValue, LValue>(
278 CodeGenFunction &, const OMPExecutableDirective &S)>
281 // Codegen lambda for loop bounds in dispatch-based loop implementation
282 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
283 CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
285 CodeGenDispatchBoundsTy;
287 /// CGBuilder insert helper. This function is called after an
288 /// instruction is created using Builder.
289 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
290 llvm::BasicBlock *BB,
291 llvm::BasicBlock::iterator InsertPt) const;
293 /// CurFuncDecl - Holds the Decl for the current outermost
294 /// non-closure context.
295 const Decl *CurFuncDecl;
296 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
297 const Decl *CurCodeDecl;
298 const CGFunctionInfo *CurFnInfo;
300 llvm::Function *CurFn = nullptr;
302 // Holds coroutine data if the current function is a coroutine. We use a
303 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
306 std::unique_ptr<CGCoroData> Data;
312 bool isCoroutine() const {
313 return CurCoro.Data != nullptr;
316 /// CurGD - The GlobalDecl for the current function being compiled.
319 /// PrologueCleanupDepth - The cleanup depth enclosing all the
320 /// cleanups associated with the parameters.
321 EHScopeStack::stable_iterator PrologueCleanupDepth;
323 /// ReturnBlock - Unified return block.
324 JumpDest ReturnBlock;
326 /// ReturnValue - The temporary alloca to hold the return
327 /// value. This is invalid iff the function has no return value.
328 Address ReturnValue = Address::invalid();
330 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
331 /// This is invalid if sret is not in use.
332 Address ReturnValuePointer = Address::invalid();
334 /// Return true if a label was seen in the current scope.
335 bool hasLabelBeenSeenInCurrentScope() const {
337 return CurLexicalScope->hasLabels();
338 return !LabelMap.empty();
341 /// AllocaInsertPoint - This is an instruction in the entry block before which
342 /// we prefer to insert allocas.
343 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
345 /// API for captured statement code generation.
346 class CGCapturedStmtInfo {
348 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
349 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
350 explicit CGCapturedStmtInfo(const CapturedStmt &S,
351 CapturedRegionKind K = CR_Default)
352 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
354 RecordDecl::field_iterator Field =
355 S.getCapturedRecordDecl()->field_begin();
356 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
358 I != E; ++I, ++Field) {
359 if (I->capturesThis())
360 CXXThisFieldDecl = *Field;
361 else if (I->capturesVariable())
362 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
363 else if (I->capturesVariableByCopy())
364 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field;
368 virtual ~CGCapturedStmtInfo();
370 CapturedRegionKind getKind() const { return Kind; }
372 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
373 // Retrieve the value of the context parameter.
374 virtual llvm::Value *getContextValue() const { return ThisValue; }
376 /// Lookup the captured field decl for a variable.
377 virtual const FieldDecl *lookup(const VarDecl *VD) const {
378 return CaptureFields.lookup(VD->getCanonicalDecl());
381 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
382 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
384 static bool classof(const CGCapturedStmtInfo *) {
388 /// Emit the captured statement body.
389 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
390 CGF.incrementProfileCounter(S);
394 /// Get the name of the capture helper.
395 virtual StringRef getHelperName() const { return "__captured_stmt"; }
398 /// The kind of captured statement being generated.
399 CapturedRegionKind Kind;
401 /// Keep the map between VarDecl and FieldDecl.
402 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
404 /// The base address of the captured record, passed in as the first
405 /// argument of the parallel region function.
406 llvm::Value *ThisValue;
408 /// Captured 'this' type.
409 FieldDecl *CXXThisFieldDecl;
411 CGCapturedStmtInfo *CapturedStmtInfo = nullptr;
413 /// RAII for correct setting/restoring of CapturedStmtInfo.
414 class CGCapturedStmtRAII {
416 CodeGenFunction &CGF;
417 CGCapturedStmtInfo *PrevCapturedStmtInfo;
419 CGCapturedStmtRAII(CodeGenFunction &CGF,
420 CGCapturedStmtInfo *NewCapturedStmtInfo)
421 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
422 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
424 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
427 /// An abstract representation of regular/ObjC call/message targets.
428 class AbstractCallee {
429 /// The function declaration of the callee.
430 const Decl *CalleeDecl;
433 AbstractCallee() : CalleeDecl(nullptr) {}
434 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
435 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
436 bool hasFunctionDecl() const {
437 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
439 const Decl *getDecl() const { return CalleeDecl; }
440 unsigned getNumParams() const {
441 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
442 return FD->getNumParams();
443 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
445 const ParmVarDecl *getParamDecl(unsigned I) const {
446 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
447 return FD->getParamDecl(I);
448 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
452 /// Sanitizers enabled for this function.
453 SanitizerSet SanOpts;
455 /// True if CodeGen currently emits code implementing sanitizer checks.
456 bool IsSanitizerScope = false;
458 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope.
459 class SanitizerScope {
460 CodeGenFunction *CGF;
462 SanitizerScope(CodeGenFunction *CGF);
466 /// In C++, whether we are code generating a thunk. This controls whether we
467 /// should emit cleanups.
468 bool CurFuncIsThunk = false;
470 /// In ARC, whether we should autorelease the return value.
471 bool AutoreleaseResult = false;
473 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
474 /// potentially set the return value.
475 bool SawAsmBlock = false;
477 const NamedDecl *CurSEHParent = nullptr;
479 /// True if the current function is an outlined SEH helper. This can be a
480 /// finally block or filter expression.
481 bool IsOutlinedSEHHelper = false;
483 /// True if CodeGen currently emits code inside presereved access index
485 bool IsInPreservedAIRegion = false;
487 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
488 llvm::Value *BlockPointer = nullptr;
490 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
491 FieldDecl *LambdaThisCaptureField = nullptr;
493 /// A mapping from NRVO variables to the flags used to indicate
494 /// when the NRVO has been applied to this variable.
495 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
497 EHScopeStack EHStack;
498 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
499 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
501 llvm::Instruction *CurrentFuncletPad = nullptr;
503 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
508 CallLifetimeEnd(Address addr, llvm::Value *size)
509 : Addr(addr.getPointer()), Size(size) {}
511 void Emit(CodeGenFunction &CGF, Flags flags) override {
512 CGF.EmitLifetimeEnd(Size, Addr);
516 /// Header for data within LifetimeExtendedCleanupStack.
517 struct LifetimeExtendedCleanupHeader {
518 /// The size of the following cleanup object.
520 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
522 /// Whether this is a conditional cleanup.
523 unsigned IsConditional : 1;
525 size_t getSize() const { return Size; }
526 CleanupKind getKind() const { return (CleanupKind)Kind; }
527 bool isConditional() const { return IsConditional; }
530 /// i32s containing the indexes of the cleanup destinations.
531 Address NormalCleanupDest = Address::invalid();
533 unsigned NextCleanupDestIndex = 1;
535 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
536 CGBlockInfo *FirstBlockInfo = nullptr;
538 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
539 llvm::BasicBlock *EHResumeBlock = nullptr;
541 /// The exception slot. All landing pads write the current exception pointer
542 /// into this alloca.
543 llvm::Value *ExceptionSlot = nullptr;
545 /// The selector slot. Under the MandatoryCleanup model, all landing pads
546 /// write the current selector value into this alloca.
547 llvm::AllocaInst *EHSelectorSlot = nullptr;
549 /// A stack of exception code slots. Entering an __except block pushes a slot
550 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
551 /// a value from the top of the stack.
552 SmallVector<Address, 1> SEHCodeSlotStack;
554 /// Value returned by __exception_info intrinsic.
555 llvm::Value *SEHInfo = nullptr;
557 /// Emits a landing pad for the current EH stack.
558 llvm::BasicBlock *EmitLandingPad();
560 llvm::BasicBlock *getInvokeDestImpl();
563 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
564 return DominatingValue<T>::save(*this, value);
568 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
570 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
572 /// A class controlling the emission of a finally block.
574 /// Where the catchall's edge through the cleanup should go.
575 JumpDest RethrowDest;
577 /// A function to call to enter the catch.
578 llvm::FunctionCallee BeginCatchFn;
580 /// An i1 variable indicating whether or not the @finally is
581 /// running for an exception.
582 llvm::AllocaInst *ForEHVar;
584 /// An i8* variable into which the exception pointer to rethrow
586 llvm::AllocaInst *SavedExnVar;
589 void enter(CodeGenFunction &CGF, const Stmt *Finally,
590 llvm::FunctionCallee beginCatchFn,
591 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn);
592 void exit(CodeGenFunction &CGF);
595 /// Returns true inside SEH __try blocks.
596 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
598 /// Returns true while emitting a cleanuppad.
599 bool isCleanupPadScope() const {
600 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
603 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
604 /// current full-expression. Safe against the possibility that
605 /// we're currently inside a conditionally-evaluated expression.
606 template <class T, class... As>
607 void pushFullExprCleanup(CleanupKind kind, As... A) {
608 // If we're not in a conditional branch, or if none of the
609 // arguments requires saving, then use the unconditional cleanup.
610 if (!isInConditionalBranch())
611 return EHStack.pushCleanup<T>(kind, A...);
613 // Stash values in a tuple so we can guarantee the order of saves.
614 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
615 SavedTuple Saved{saveValueInCond(A)...};
617 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
618 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
619 initFullExprCleanup();
622 /// Queue a cleanup to be pushed after finishing the current
624 template <class T, class... As>
625 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
626 if (!isInConditionalBranch())
627 return pushCleanupAfterFullExprImpl<T>(Kind, Address::invalid(), A...);
629 Address ActiveFlag = createCleanupActiveFlag();
630 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) &&
631 "cleanup active flag should never need saving");
633 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
634 SavedTuple Saved{saveValueInCond(A)...};
636 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
637 pushCleanupAfterFullExprImpl<CleanupType>(Kind, ActiveFlag, Saved);
640 template <class T, class... As>
641 void pushCleanupAfterFullExprImpl(CleanupKind Kind, Address ActiveFlag,
643 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind,
644 ActiveFlag.isValid()};
646 size_t OldSize = LifetimeExtendedCleanupStack.size();
647 LifetimeExtendedCleanupStack.resize(
648 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size +
649 (Header.IsConditional ? sizeof(ActiveFlag) : 0));
651 static_assert(sizeof(Header) % alignof(T) == 0,
652 "Cleanup will be allocated on misaligned address");
653 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
654 new (Buffer) LifetimeExtendedCleanupHeader(Header);
655 new (Buffer + sizeof(Header)) T(A...);
656 if (Header.IsConditional)
657 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag);
660 /// Set up the last cleanup that was pushed as a conditional
661 /// full-expression cleanup.
662 void initFullExprCleanup() {
663 initFullExprCleanupWithFlag(createCleanupActiveFlag());
666 void initFullExprCleanupWithFlag(Address ActiveFlag);
667 Address createCleanupActiveFlag();
669 /// PushDestructorCleanup - Push a cleanup to call the
670 /// complete-object destructor of an object of the given type at the
671 /// given address. Does nothing if T is not a C++ class type with a
672 /// non-trivial destructor.
673 void PushDestructorCleanup(QualType T, Address Addr);
675 /// PushDestructorCleanup - Push a cleanup to call the
676 /// complete-object variant of the given destructor on the object at
677 /// the given address.
678 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T,
681 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
682 /// process all branch fixups.
683 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
685 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
686 /// The block cannot be reactivated. Pops it if it's the top of the
689 /// \param DominatingIP - An instruction which is known to
690 /// dominate the current IP (if set) and which lies along
691 /// all paths of execution between the current IP and the
692 /// the point at which the cleanup comes into scope.
693 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
694 llvm::Instruction *DominatingIP);
696 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
697 /// Cannot be used to resurrect a deactivated cleanup.
699 /// \param DominatingIP - An instruction which is known to
700 /// dominate the current IP (if set) and which lies along
701 /// all paths of execution between the current IP and the
702 /// the point at which the cleanup comes into scope.
703 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
704 llvm::Instruction *DominatingIP);
706 /// Enters a new scope for capturing cleanups, all of which
707 /// will be executed once the scope is exited.
708 class RunCleanupsScope {
709 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth;
710 size_t LifetimeExtendedCleanupStackSize;
711 bool OldDidCallStackSave;
716 RunCleanupsScope(const RunCleanupsScope &) = delete;
717 void operator=(const RunCleanupsScope &) = delete;
720 CodeGenFunction& CGF;
723 /// Enter a new cleanup scope.
724 explicit RunCleanupsScope(CodeGenFunction &CGF)
725 : PerformCleanup(true), CGF(CGF)
727 CleanupStackDepth = CGF.EHStack.stable_begin();
728 LifetimeExtendedCleanupStackSize =
729 CGF.LifetimeExtendedCleanupStack.size();
730 OldDidCallStackSave = CGF.DidCallStackSave;
731 CGF.DidCallStackSave = false;
732 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth;
733 CGF.CurrentCleanupScopeDepth = CleanupStackDepth;
736 /// Exit this cleanup scope, emitting any accumulated cleanups.
737 ~RunCleanupsScope() {
742 /// Determine whether this scope requires any cleanups.
743 bool requiresCleanups() const {
744 return CGF.EHStack.stable_begin() != CleanupStackDepth;
747 /// Force the emission of cleanups now, instead of waiting
748 /// until this object is destroyed.
749 /// \param ValuesToReload - A list of values that need to be available at
750 /// the insertion point after cleanup emission. If cleanup emission created
751 /// a shared cleanup block, these value pointers will be rewritten.
752 /// Otherwise, they not will be modified.
753 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
754 assert(PerformCleanup && "Already forced cleanup");
755 CGF.DidCallStackSave = OldDidCallStackSave;
756 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
758 PerformCleanup = false;
759 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth;
763 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently.
764 EHScopeStack::stable_iterator CurrentCleanupScopeDepth =
765 EHScopeStack::stable_end();
767 class LexicalScope : public RunCleanupsScope {
769 SmallVector<const LabelDecl*, 4> Labels;
770 LexicalScope *ParentScope;
772 LexicalScope(const LexicalScope &) = delete;
773 void operator=(const LexicalScope &) = delete;
776 /// Enter a new cleanup scope.
777 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
778 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
779 CGF.CurLexicalScope = this;
780 if (CGDebugInfo *DI = CGF.getDebugInfo())
781 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
784 void addLabel(const LabelDecl *label) {
785 assert(PerformCleanup && "adding label to dead scope?");
786 Labels.push_back(label);
789 /// Exit this cleanup scope, emitting any accumulated
792 if (CGDebugInfo *DI = CGF.getDebugInfo())
793 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
795 // If we should perform a cleanup, force them now. Note that
796 // this ends the cleanup scope before rescoping any labels.
797 if (PerformCleanup) {
798 ApplyDebugLocation DL(CGF, Range.getEnd());
803 /// Force the emission of cleanups now, instead of waiting
804 /// until this object is destroyed.
805 void ForceCleanup() {
806 CGF.CurLexicalScope = ParentScope;
807 RunCleanupsScope::ForceCleanup();
813 bool hasLabels() const {
814 return !Labels.empty();
817 void rescopeLabels();
820 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
822 /// The class used to assign some variables some temporarily addresses.
824 DeclMapTy SavedLocals;
825 DeclMapTy SavedTempAddresses;
826 OMPMapVars(const OMPMapVars &) = delete;
827 void operator=(const OMPMapVars &) = delete;
830 explicit OMPMapVars() = default;
832 assert(SavedLocals.empty() && "Did not restored original addresses.");
835 /// Sets the address of the variable \p LocalVD to be \p TempAddr in
837 /// \return true if at least one variable was set already, false otherwise.
838 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD,
840 LocalVD = LocalVD->getCanonicalDecl();
841 // Only save it once.
842 if (SavedLocals.count(LocalVD)) return false;
844 // Copy the existing local entry to SavedLocals.
845 auto it = CGF.LocalDeclMap.find(LocalVD);
846 if (it != CGF.LocalDeclMap.end())
847 SavedLocals.try_emplace(LocalVD, it->second);
849 SavedLocals.try_emplace(LocalVD, Address::invalid());
851 // Generate the private entry.
852 QualType VarTy = LocalVD->getType();
853 if (VarTy->isReferenceType()) {
854 Address Temp = CGF.CreateMemTemp(VarTy);
855 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp);
858 SavedTempAddresses.try_emplace(LocalVD, TempAddr);
863 /// Applies new addresses to the list of the variables.
864 /// \return true if at least one variable is using new address, false
866 bool apply(CodeGenFunction &CGF) {
867 copyInto(SavedTempAddresses, CGF.LocalDeclMap);
868 SavedTempAddresses.clear();
869 return !SavedLocals.empty();
872 /// Restores original addresses of the variables.
873 void restore(CodeGenFunction &CGF) {
874 if (!SavedLocals.empty()) {
875 copyInto(SavedLocals, CGF.LocalDeclMap);
881 /// Copy all the entries in the source map over the corresponding
882 /// entries in the destination, which must exist.
883 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) {
884 for (auto &Pair : Src) {
885 if (!Pair.second.isValid()) {
886 Dest.erase(Pair.first);
890 auto I = Dest.find(Pair.first);
892 I->second = Pair.second;
899 /// The scope used to remap some variables as private in the OpenMP loop body
900 /// (or other captured region emitted without outlining), and to restore old
901 /// vars back on exit.
902 class OMPPrivateScope : public RunCleanupsScope {
903 OMPMapVars MappedVars;
904 OMPPrivateScope(const OMPPrivateScope &) = delete;
905 void operator=(const OMPPrivateScope &) = delete;
908 /// Enter a new OpenMP private scope.
909 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
911 /// Registers \p LocalVD variable as a private and apply \p PrivateGen
912 /// function for it to generate corresponding private variable. \p
913 /// PrivateGen returns an address of the generated private variable.
914 /// \return true if the variable is registered as private, false if it has
915 /// been privatized already.
916 bool addPrivate(const VarDecl *LocalVD,
917 const llvm::function_ref<Address()> PrivateGen) {
918 assert(PerformCleanup && "adding private to dead scope");
919 return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen());
922 /// Privatizes local variables previously registered as private.
923 /// Registration is separate from the actual privatization to allow
924 /// initializers use values of the original variables, not the private one.
925 /// This is important, for example, if the private variable is a class
926 /// variable initialized by a constructor that references other private
927 /// variables. But at initialization original variables must be used, not
929 /// \return true if at least one variable was privatized, false otherwise.
930 bool Privatize() { return MappedVars.apply(CGF); }
932 void ForceCleanup() {
933 RunCleanupsScope::ForceCleanup();
934 MappedVars.restore(CGF);
937 /// Exit scope - all the mapped variables are restored.
943 /// Checks if the global variable is captured in current function.
944 bool isGlobalVarCaptured(const VarDecl *VD) const {
945 VD = VD->getCanonicalDecl();
946 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
950 /// Takes the old cleanup stack size and emits the cleanup blocks
951 /// that have been added.
953 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
954 std::initializer_list<llvm::Value **> ValuesToReload = {});
956 /// Takes the old cleanup stack size and emits the cleanup blocks
957 /// that have been added, then adds all lifetime-extended cleanups from
958 /// the given position to the stack.
960 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
961 size_t OldLifetimeExtendedStackSize,
962 std::initializer_list<llvm::Value **> ValuesToReload = {});
964 void ResolveBranchFixups(llvm::BasicBlock *Target);
966 /// The given basic block lies in the current EH scope, but may be a
967 /// target of a potentially scope-crossing jump; get a stable handle
968 /// to which we can perform this jump later.
969 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
970 return JumpDest(Target,
971 EHStack.getInnermostNormalCleanup(),
972 NextCleanupDestIndex++);
975 /// The given basic block lies in the current EH scope, but may be a
976 /// target of a potentially scope-crossing jump; get a stable handle
977 /// to which we can perform this jump later.
978 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
979 return getJumpDestInCurrentScope(createBasicBlock(Name));
982 /// EmitBranchThroughCleanup - Emit a branch from the current insert
983 /// block through the normal cleanup handling code (if any) and then
985 void EmitBranchThroughCleanup(JumpDest Dest);
987 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
988 /// specified destination obviously has no cleanups to run. 'false' is always
989 /// a conservatively correct answer for this method.
990 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
992 /// popCatchScope - Pops the catch scope at the top of the EHScope
993 /// stack, emitting any required code (other than the catch handlers
995 void popCatchScope();
997 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
998 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
1000 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope);
1002 /// An object to manage conditionally-evaluated expressions.
1003 class ConditionalEvaluation {
1004 llvm::BasicBlock *StartBB;
1007 ConditionalEvaluation(CodeGenFunction &CGF)
1008 : StartBB(CGF.Builder.GetInsertBlock()) {}
1010 void begin(CodeGenFunction &CGF) {
1011 assert(CGF.OutermostConditional != this);
1012 if (!CGF.OutermostConditional)
1013 CGF.OutermostConditional = this;
1016 void end(CodeGenFunction &CGF) {
1017 assert(CGF.OutermostConditional != nullptr);
1018 if (CGF.OutermostConditional == this)
1019 CGF.OutermostConditional = nullptr;
1022 /// Returns a block which will be executed prior to each
1023 /// evaluation of the conditional code.
1024 llvm::BasicBlock *getStartingBlock() const {
1029 /// isInConditionalBranch - Return true if we're currently emitting
1030 /// one branch or the other of a conditional expression.
1031 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
1033 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
1034 assert(isInConditionalBranch());
1035 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
1036 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
1037 store->setAlignment(addr.getAlignment().getQuantity());
1040 /// An RAII object to record that we're evaluating a statement
1042 class StmtExprEvaluation {
1043 CodeGenFunction &CGF;
1045 /// We have to save the outermost conditional: cleanups in a
1046 /// statement expression aren't conditional just because the
1048 ConditionalEvaluation *SavedOutermostConditional;
1051 StmtExprEvaluation(CodeGenFunction &CGF)
1052 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
1053 CGF.OutermostConditional = nullptr;
1056 ~StmtExprEvaluation() {
1057 CGF.OutermostConditional = SavedOutermostConditional;
1058 CGF.EnsureInsertPoint();
1062 /// An object which temporarily prevents a value from being
1063 /// destroyed by aggressive peephole optimizations that assume that
1064 /// all uses of a value have been realized in the IR.
1065 class PeepholeProtection {
1066 llvm::Instruction *Inst;
1067 friend class CodeGenFunction;
1070 PeepholeProtection() : Inst(nullptr) {}
1073 /// A non-RAII class containing all the information about a bound
1074 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
1075 /// this which makes individual mappings very simple; using this
1076 /// class directly is useful when you have a variable number of
1077 /// opaque values or don't want the RAII functionality for some
1079 class OpaqueValueMappingData {
1080 const OpaqueValueExpr *OpaqueValue;
1082 CodeGenFunction::PeepholeProtection Protection;
1084 OpaqueValueMappingData(const OpaqueValueExpr *ov,
1086 : OpaqueValue(ov), BoundLValue(boundLValue) {}
1088 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
1090 static bool shouldBindAsLValue(const Expr *expr) {
1091 // gl-values should be bound as l-values for obvious reasons.
1092 // Records should be bound as l-values because IR generation
1093 // always keeps them in memory. Expressions of function type
1094 // act exactly like l-values but are formally required to be
1096 return expr->isGLValue() ||
1097 expr->getType()->isFunctionType() ||
1098 hasAggregateEvaluationKind(expr->getType());
1101 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1102 const OpaqueValueExpr *ov,
1104 if (shouldBindAsLValue(ov))
1105 return bind(CGF, ov, CGF.EmitLValue(e));
1106 return bind(CGF, ov, CGF.EmitAnyExpr(e));
1109 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1110 const OpaqueValueExpr *ov,
1112 assert(shouldBindAsLValue(ov));
1113 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
1114 return OpaqueValueMappingData(ov, true);
1117 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
1118 const OpaqueValueExpr *ov,
1120 assert(!shouldBindAsLValue(ov));
1121 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
1123 OpaqueValueMappingData data(ov, false);
1125 // Work around an extremely aggressive peephole optimization in
1126 // EmitScalarConversion which assumes that all other uses of a
1127 // value are extant.
1128 data.Protection = CGF.protectFromPeepholes(rv);
1133 bool isValid() const { return OpaqueValue != nullptr; }
1134 void clear() { OpaqueValue = nullptr; }
1136 void unbind(CodeGenFunction &CGF) {
1137 assert(OpaqueValue && "no data to unbind!");
1140 CGF.OpaqueLValues.erase(OpaqueValue);
1142 CGF.OpaqueRValues.erase(OpaqueValue);
1143 CGF.unprotectFromPeepholes(Protection);
1148 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
1149 class OpaqueValueMapping {
1150 CodeGenFunction &CGF;
1151 OpaqueValueMappingData Data;
1154 static bool shouldBindAsLValue(const Expr *expr) {
1155 return OpaqueValueMappingData::shouldBindAsLValue(expr);
1158 /// Build the opaque value mapping for the given conditional
1159 /// operator if it's the GNU ?: extension. This is a common
1160 /// enough pattern that the convenience operator is really
1163 OpaqueValueMapping(CodeGenFunction &CGF,
1164 const AbstractConditionalOperator *op) : CGF(CGF) {
1165 if (isa<ConditionalOperator>(op))
1166 // Leave Data empty.
1169 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1170 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1174 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1175 /// expression is set to the expression the OVE represents.
1176 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1179 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1180 "for OVE with no source expression");
1181 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1185 OpaqueValueMapping(CodeGenFunction &CGF,
1186 const OpaqueValueExpr *opaqueValue,
1188 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1191 OpaqueValueMapping(CodeGenFunction &CGF,
1192 const OpaqueValueExpr *opaqueValue,
1194 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1202 ~OpaqueValueMapping() {
1203 if (Data.isValid()) Data.unbind(CGF);
1208 CGDebugInfo *DebugInfo;
1209 /// Used to create unique names for artificial VLA size debug info variables.
1210 unsigned VLAExprCounter = 0;
1211 bool DisableDebugInfo = false;
1213 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1214 /// calling llvm.stacksave for multiple VLAs in the same scope.
1215 bool DidCallStackSave = false;
1217 /// IndirectBranch - The first time an indirect goto is seen we create a block
1218 /// with an indirect branch. Every time we see the address of a label taken,
1219 /// we add the label to the indirect goto. Every subsequent indirect goto is
1220 /// codegen'd as a jump to the IndirectBranch's basic block.
1221 llvm::IndirectBrInst *IndirectBranch = nullptr;
1223 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1225 DeclMapTy LocalDeclMap;
1227 // Keep track of the cleanups for callee-destructed parameters pushed to the
1228 // cleanup stack so that they can be deactivated later.
1229 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator>
1230 CalleeDestructedParamCleanups;
1232 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1233 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1235 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1238 /// Track escaped local variables with auto storage. Used during SEH
1239 /// outlining to produce a call to llvm.localescape.
1240 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1242 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1243 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1245 // BreakContinueStack - This keeps track of where break and continue
1246 // statements should jump to.
1247 struct BreakContinue {
1248 BreakContinue(JumpDest Break, JumpDest Continue)
1249 : BreakBlock(Break), ContinueBlock(Continue) {}
1251 JumpDest BreakBlock;
1252 JumpDest ContinueBlock;
1254 SmallVector<BreakContinue, 8> BreakContinueStack;
1256 /// Handles cancellation exit points in OpenMP-related constructs.
1257 class OpenMPCancelExitStack {
1258 /// Tracks cancellation exit point and join point for cancel-related exit
1259 /// and normal exit.
1261 CancelExit() = default;
1262 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1264 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1265 OpenMPDirectiveKind Kind = OMPD_unknown;
1266 /// true if the exit block has been emitted already by the special
1267 /// emitExit() call, false if the default codegen is used.
1268 bool HasBeenEmitted = false;
1273 SmallVector<CancelExit, 8> Stack;
1276 OpenMPCancelExitStack() : Stack(1) {}
1277 ~OpenMPCancelExitStack() = default;
1278 /// Fetches the exit block for the current OpenMP construct.
1279 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1280 /// Emits exit block with special codegen procedure specific for the related
1281 /// OpenMP construct + emits code for normal construct cleanup.
1282 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1283 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) {
1284 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1285 assert(CGF.getOMPCancelDestination(Kind).isValid());
1286 assert(CGF.HaveInsertPoint());
1287 assert(!Stack.back().HasBeenEmitted);
1288 auto IP = CGF.Builder.saveAndClearIP();
1289 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1291 CGF.EmitBranch(Stack.back().ContBlock.getBlock());
1292 CGF.Builder.restoreIP(IP);
1293 Stack.back().HasBeenEmitted = true;
1297 /// Enter the cancel supporting \a Kind construct.
1298 /// \param Kind OpenMP directive that supports cancel constructs.
1299 /// \param HasCancel true, if the construct has inner cancel directive,
1300 /// false otherwise.
1301 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1302 Stack.push_back({Kind,
1303 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1305 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1308 /// Emits default exit point for the cancel construct (if the special one
1309 /// has not be used) + join point for cancel/normal exits.
1310 void exit(CodeGenFunction &CGF) {
1311 if (getExitBlock().isValid()) {
1312 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1313 bool HaveIP = CGF.HaveInsertPoint();
1314 if (!Stack.back().HasBeenEmitted) {
1316 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1317 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1318 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1320 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1322 CGF.Builder.CreateUnreachable();
1323 CGF.Builder.ClearInsertionPoint();
1329 OpenMPCancelExitStack OMPCancelStack;
1333 /// Calculate branch weights appropriate for PGO data
1334 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1335 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1336 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1337 uint64_t LoopCount);
1340 /// Increment the profiler's counter for the given statement by \p StepV.
1341 /// If \p StepV is null, the default increment is 1.
1342 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1343 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1344 PGO.emitCounterIncrement(Builder, S, StepV);
1345 PGO.setCurrentStmt(S);
1348 /// Get the profiler's count for the given statement.
1349 uint64_t getProfileCount(const Stmt *S) {
1350 Optional<uint64_t> Count = PGO.getStmtCount(S);
1351 if (!Count.hasValue())
1356 /// Set the profiler's current count.
1357 void setCurrentProfileCount(uint64_t Count) {
1358 PGO.setCurrentRegionCount(Count);
1361 /// Get the profiler's current count. This is generally the count for the most
1362 /// recently incremented counter.
1363 uint64_t getCurrentProfileCount() {
1364 return PGO.getCurrentRegionCount();
1369 /// SwitchInsn - This is nearest current switch instruction. It is null if
1370 /// current context is not in a switch.
1371 llvm::SwitchInst *SwitchInsn = nullptr;
1372 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1373 SmallVector<uint64_t, 16> *SwitchWeights = nullptr;
1375 /// CaseRangeBlock - This block holds if condition check for last case
1376 /// statement range in current switch instruction.
1377 llvm::BasicBlock *CaseRangeBlock = nullptr;
1379 /// OpaqueLValues - Keeps track of the current set of opaque value
1381 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1382 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1384 // VLASizeMap - This keeps track of the associated size for each VLA type.
1385 // We track this by the size expression rather than the type itself because
1386 // in certain situations, like a const qualifier applied to an VLA typedef,
1387 // multiple VLA types can share the same size expression.
1388 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1389 // enter/leave scopes.
1390 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1392 /// A block containing a single 'unreachable' instruction. Created
1393 /// lazily by getUnreachableBlock().
1394 llvm::BasicBlock *UnreachableBlock = nullptr;
1396 /// Counts of the number return expressions in the function.
1397 unsigned NumReturnExprs = 0;
1399 /// Count the number of simple (constant) return expressions in the function.
1400 unsigned NumSimpleReturnExprs = 0;
1402 /// The last regular (non-return) debug location (breakpoint) in the function.
1403 SourceLocation LastStopPoint;
1406 /// Source location information about the default argument or member
1407 /// initializer expression we're evaluating, if any.
1408 CurrentSourceLocExprScope CurSourceLocExprScope;
1409 using SourceLocExprScopeGuard =
1410 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
1412 /// A scope within which we are constructing the fields of an object which
1413 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1414 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1415 class FieldConstructionScope {
1417 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1418 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1419 CGF.CXXDefaultInitExprThis = This;
1421 ~FieldConstructionScope() {
1422 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1426 CodeGenFunction &CGF;
1427 Address OldCXXDefaultInitExprThis;
1430 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1431 /// is overridden to be the object under construction.
1432 class CXXDefaultInitExprScope {
1434 CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E)
1435 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1436 OldCXXThisAlignment(CGF.CXXThisAlignment),
1437 SourceLocScope(E, CGF.CurSourceLocExprScope) {
1438 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1439 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1441 ~CXXDefaultInitExprScope() {
1442 CGF.CXXThisValue = OldCXXThisValue;
1443 CGF.CXXThisAlignment = OldCXXThisAlignment;
1447 CodeGenFunction &CGF;
1448 llvm::Value *OldCXXThisValue;
1449 CharUnits OldCXXThisAlignment;
1450 SourceLocExprScopeGuard SourceLocScope;
1453 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard {
1454 CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E)
1455 : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {}
1458 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1459 /// current loop index is overridden.
1460 class ArrayInitLoopExprScope {
1462 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1463 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1464 CGF.ArrayInitIndex = Index;
1466 ~ArrayInitLoopExprScope() {
1467 CGF.ArrayInitIndex = OldArrayInitIndex;
1471 CodeGenFunction &CGF;
1472 llvm::Value *OldArrayInitIndex;
1475 class InlinedInheritingConstructorScope {
1477 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1478 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1479 OldCurCodeDecl(CGF.CurCodeDecl),
1480 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1481 OldCXXABIThisValue(CGF.CXXABIThisValue),
1482 OldCXXThisValue(CGF.CXXThisValue),
1483 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1484 OldCXXThisAlignment(CGF.CXXThisAlignment),
1485 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1486 OldCXXInheritedCtorInitExprArgs(
1487 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1489 CGF.CurFuncDecl = CGF.CurCodeDecl =
1490 cast<CXXConstructorDecl>(GD.getDecl());
1491 CGF.CXXABIThisDecl = nullptr;
1492 CGF.CXXABIThisValue = nullptr;
1493 CGF.CXXThisValue = nullptr;
1494 CGF.CXXABIThisAlignment = CharUnits();
1495 CGF.CXXThisAlignment = CharUnits();
1496 CGF.ReturnValue = Address::invalid();
1497 CGF.FnRetTy = QualType();
1498 CGF.CXXInheritedCtorInitExprArgs.clear();
1500 ~InlinedInheritingConstructorScope() {
1501 CGF.CurGD = OldCurGD;
1502 CGF.CurFuncDecl = OldCurFuncDecl;
1503 CGF.CurCodeDecl = OldCurCodeDecl;
1504 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1505 CGF.CXXABIThisValue = OldCXXABIThisValue;
1506 CGF.CXXThisValue = OldCXXThisValue;
1507 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1508 CGF.CXXThisAlignment = OldCXXThisAlignment;
1509 CGF.ReturnValue = OldReturnValue;
1510 CGF.FnRetTy = OldFnRetTy;
1511 CGF.CXXInheritedCtorInitExprArgs =
1512 std::move(OldCXXInheritedCtorInitExprArgs);
1516 CodeGenFunction &CGF;
1517 GlobalDecl OldCurGD;
1518 const Decl *OldCurFuncDecl;
1519 const Decl *OldCurCodeDecl;
1520 ImplicitParamDecl *OldCXXABIThisDecl;
1521 llvm::Value *OldCXXABIThisValue;
1522 llvm::Value *OldCXXThisValue;
1523 CharUnits OldCXXABIThisAlignment;
1524 CharUnits OldCXXThisAlignment;
1525 Address OldReturnValue;
1526 QualType OldFnRetTy;
1527 CallArgList OldCXXInheritedCtorInitExprArgs;
1531 /// CXXThisDecl - When generating code for a C++ member function,
1532 /// this will hold the implicit 'this' declaration.
1533 ImplicitParamDecl *CXXABIThisDecl = nullptr;
1534 llvm::Value *CXXABIThisValue = nullptr;
1535 llvm::Value *CXXThisValue = nullptr;
1536 CharUnits CXXABIThisAlignment;
1537 CharUnits CXXThisAlignment;
1539 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1540 /// this expression.
1541 Address CXXDefaultInitExprThis = Address::invalid();
1543 /// The current array initialization index when evaluating an
1544 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1545 llvm::Value *ArrayInitIndex = nullptr;
1547 /// The values of function arguments to use when evaluating
1548 /// CXXInheritedCtorInitExprs within this context.
1549 CallArgList CXXInheritedCtorInitExprArgs;
1551 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1552 /// destructor, this will hold the implicit argument (e.g. VTT).
1553 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr;
1554 llvm::Value *CXXStructorImplicitParamValue = nullptr;
1556 /// OutermostConditional - Points to the outermost active
1557 /// conditional control. This is used so that we know if a
1558 /// temporary should be destroyed conditionally.
1559 ConditionalEvaluation *OutermostConditional = nullptr;
1561 /// The current lexical scope.
1562 LexicalScope *CurLexicalScope = nullptr;
1564 /// The current source location that should be used for exception
1566 SourceLocation CurEHLocation;
1568 /// BlockByrefInfos - For each __block variable, contains
1569 /// information about the layout of the variable.
1570 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1572 /// Used by -fsanitize=nullability-return to determine whether the return
1573 /// value can be checked.
1574 llvm::Value *RetValNullabilityPrecondition = nullptr;
1576 /// Check if -fsanitize=nullability-return instrumentation is required for
1578 bool requiresReturnValueNullabilityCheck() const {
1579 return RetValNullabilityPrecondition;
1582 /// Used to store precise source locations for return statements by the
1583 /// runtime return value checks.
1584 Address ReturnLocation = Address::invalid();
1586 /// Check if the return value of this function requires sanitization.
1587 bool requiresReturnValueCheck() const {
1588 return requiresReturnValueNullabilityCheck() ||
1589 (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
1590 CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>());
1593 llvm::BasicBlock *TerminateLandingPad = nullptr;
1594 llvm::BasicBlock *TerminateHandler = nullptr;
1595 llvm::BasicBlock *TrapBB = nullptr;
1597 /// Terminate funclets keyed by parent funclet pad.
1598 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets;
1600 /// Largest vector width used in ths function. Will be used to create a
1601 /// function attribute.
1602 unsigned LargestVectorWidth = 0;
1604 /// True if we need emit the life-time markers.
1605 const bool ShouldEmitLifetimeMarkers;
1607 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to
1608 /// the function metadata.
1609 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1610 llvm::Function *Fn);
1613 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1616 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1617 ASTContext &getContext() const { return CGM.getContext(); }
1618 CGDebugInfo *getDebugInfo() {
1619 if (DisableDebugInfo)
1623 void disableDebugInfo() { DisableDebugInfo = true; }
1624 void enableDebugInfo() { DisableDebugInfo = false; }
1626 bool shouldUseFusedARCCalls() {
1627 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1630 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1632 /// Returns a pointer to the function's exception object and selector slot,
1633 /// which is assigned in every landing pad.
1634 Address getExceptionSlot();
1635 Address getEHSelectorSlot();
1637 /// Returns the contents of the function's exception object and selector
1639 llvm::Value *getExceptionFromSlot();
1640 llvm::Value *getSelectorFromSlot();
1642 Address getNormalCleanupDestSlot();
1644 llvm::BasicBlock *getUnreachableBlock() {
1645 if (!UnreachableBlock) {
1646 UnreachableBlock = createBasicBlock("unreachable");
1647 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1649 return UnreachableBlock;
1652 llvm::BasicBlock *getInvokeDest() {
1653 if (!EHStack.requiresLandingPad()) return nullptr;
1654 return getInvokeDestImpl();
1657 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1659 const TargetInfo &getTarget() const { return Target; }
1660 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1661 const TargetCodeGenInfo &getTargetHooks() const {
1662 return CGM.getTargetCodeGenInfo();
1665 //===--------------------------------------------------------------------===//
1667 //===--------------------------------------------------------------------===//
1669 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1671 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1672 Address arrayEndPointer,
1673 QualType elementType,
1674 CharUnits elementAlignment,
1675 Destroyer *destroyer);
1676 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1677 llvm::Value *arrayEnd,
1678 QualType elementType,
1679 CharUnits elementAlignment,
1680 Destroyer *destroyer);
1682 void pushDestroy(QualType::DestructionKind dtorKind,
1683 Address addr, QualType type);
1684 void pushEHDestroy(QualType::DestructionKind dtorKind,
1685 Address addr, QualType type);
1686 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1687 Destroyer *destroyer, bool useEHCleanupForArray);
1688 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1689 QualType type, Destroyer *destroyer,
1690 bool useEHCleanupForArray);
1691 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1692 llvm::Value *CompletePtr,
1693 QualType ElementType);
1694 void pushStackRestore(CleanupKind kind, Address SPMem);
1695 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1696 bool useEHCleanupForArray);
1697 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1698 Destroyer *destroyer,
1699 bool useEHCleanupForArray,
1701 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1702 QualType elementType, CharUnits elementAlign,
1703 Destroyer *destroyer,
1704 bool checkZeroLength, bool useEHCleanup);
1706 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1708 /// Determines whether an EH cleanup is required to destroy a type
1709 /// with the given destruction kind.
1710 bool needsEHCleanup(QualType::DestructionKind kind) {
1712 case QualType::DK_none:
1714 case QualType::DK_cxx_destructor:
1715 case QualType::DK_objc_weak_lifetime:
1716 case QualType::DK_nontrivial_c_struct:
1717 return getLangOpts().Exceptions;
1718 case QualType::DK_objc_strong_lifetime:
1719 return getLangOpts().Exceptions &&
1720 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1722 llvm_unreachable("bad destruction kind");
1725 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1726 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1729 //===--------------------------------------------------------------------===//
1731 //===--------------------------------------------------------------------===//
1733 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1735 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1737 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1738 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1739 const ObjCPropertyImplDecl *PID);
1740 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1741 const ObjCPropertyImplDecl *propImpl,
1742 const ObjCMethodDecl *GetterMothodDecl,
1743 llvm::Constant *AtomicHelperFn);
1745 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1746 ObjCMethodDecl *MD, bool ctor);
1748 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1749 /// for the given property.
1750 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1751 const ObjCPropertyImplDecl *PID);
1752 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1753 const ObjCPropertyImplDecl *propImpl,
1754 llvm::Constant *AtomicHelperFn);
1756 //===--------------------------------------------------------------------===//
1758 //===--------------------------------------------------------------------===//
1760 /// Emit block literal.
1761 /// \return an LLVM value which is a pointer to a struct which contains
1762 /// information about the block, including the block invoke function, the
1763 /// captured variables, etc.
1764 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1765 static void destroyBlockInfos(CGBlockInfo *info);
1767 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1768 const CGBlockInfo &Info,
1769 const DeclMapTy &ldm,
1770 bool IsLambdaConversionToBlock,
1771 bool BuildGlobalBlock);
1773 /// Check if \p T is a C++ class that has a destructor that can throw.
1774 static bool cxxDestructorCanThrow(QualType T);
1776 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1777 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1778 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1779 const ObjCPropertyImplDecl *PID);
1780 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1781 const ObjCPropertyImplDecl *PID);
1782 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1784 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags,
1787 class AutoVarEmission;
1789 void emitByrefStructureInit(const AutoVarEmission &emission);
1791 /// Enter a cleanup to destroy a __block variable. Note that this
1792 /// cleanup should be a no-op if the variable hasn't left the stack
1793 /// yet; if a cleanup is required for the variable itself, that needs
1794 /// to be done externally.
1796 /// \param Kind Cleanup kind.
1798 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block
1799 /// structure that will be passed to _Block_object_dispose. When
1800 /// \p LoadBlockVarAddr is true, the address of the field of the block
1801 /// structure that holds the address of the __block structure.
1803 /// \param Flags The flag that will be passed to _Block_object_dispose.
1805 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from
1806 /// \p Addr to get the address of the __block structure.
1807 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags,
1808 bool LoadBlockVarAddr, bool CanThrow);
1810 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1813 Address LoadBlockStruct();
1814 Address GetAddrOfBlockDecl(const VarDecl *var);
1816 /// BuildBlockByrefAddress - Computes the location of the
1817 /// data in a variable which is declared as __block.
1818 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1819 bool followForward = true);
1820 Address emitBlockByrefAddress(Address baseAddr,
1821 const BlockByrefInfo &info,
1823 const llvm::Twine &name);
1825 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1827 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1829 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1830 const CGFunctionInfo &FnInfo);
1832 /// Annotate the function with an attribute that disables TSan checking at
1834 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn);
1836 /// Emit code for the start of a function.
1837 /// \param Loc The location to be associated with the function.
1838 /// \param StartLoc The location of the function body.
1839 void StartFunction(GlobalDecl GD,
1842 const CGFunctionInfo &FnInfo,
1843 const FunctionArgList &Args,
1844 SourceLocation Loc = SourceLocation(),
1845 SourceLocation StartLoc = SourceLocation());
1847 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1849 void EmitConstructorBody(FunctionArgList &Args);
1850 void EmitDestructorBody(FunctionArgList &Args);
1851 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1852 void EmitFunctionBody(const Stmt *Body);
1853 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1855 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1856 CallArgList &CallArgs);
1857 void EmitLambdaBlockInvokeBody();
1858 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1859 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD);
1860 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) {
1861 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1863 void EmitAsanPrologueOrEpilogue(bool Prologue);
1865 /// Emit the unified return block, trying to avoid its emission when
1867 /// \return The debug location of the user written return statement if the
1868 /// return block is is avoided.
1869 llvm::DebugLoc EmitReturnBlock();
1871 /// FinishFunction - Complete IR generation of the current function. It is
1872 /// legal to call this function even if there is no current insertion point.
1873 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1875 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1876 const CGFunctionInfo &FnInfo, bool IsUnprototyped);
1878 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee,
1879 const ThunkInfo *Thunk, bool IsUnprototyped);
1883 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1884 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr,
1885 llvm::FunctionCallee Callee);
1887 /// Generate a thunk for the given method.
1888 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1889 GlobalDecl GD, const ThunkInfo &Thunk,
1890 bool IsUnprototyped);
1892 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1893 const CGFunctionInfo &FnInfo,
1894 GlobalDecl GD, const ThunkInfo &Thunk);
1896 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1897 FunctionArgList &Args);
1899 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1901 /// Struct with all information about dynamic [sub]class needed to set vptr.
1904 const CXXRecordDecl *NearestVBase;
1905 CharUnits OffsetFromNearestVBase;
1906 const CXXRecordDecl *VTableClass;
1909 /// Initialize the vtable pointer of the given subobject.
1910 void InitializeVTablePointer(const VPtr &vptr);
1912 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1914 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1915 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1917 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1918 CharUnits OffsetFromNearestVBase,
1919 bool BaseIsNonVirtualPrimaryBase,
1920 const CXXRecordDecl *VTableClass,
1921 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1923 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1925 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1927 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1928 const CXXRecordDecl *VTableClass);
1930 enum CFITypeCheckKind {
1934 CFITCK_UnrelatedCast,
1940 /// Derived is the presumed address of an object of type T after a
1941 /// cast. If T is a polymorphic class type, emit a check that the virtual
1942 /// table for Derived belongs to a class derived from T.
1943 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1944 bool MayBeNull, CFITypeCheckKind TCK,
1945 SourceLocation Loc);
1947 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1948 /// If vptr CFI is enabled, emit a check that VTable is valid.
1949 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1950 CFITypeCheckKind TCK, SourceLocation Loc);
1952 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1953 /// RD using llvm.type.test.
1954 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1955 CFITypeCheckKind TCK, SourceLocation Loc);
1957 /// If whole-program virtual table optimization is enabled, emit an assumption
1958 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1959 /// enabled, emit a check that VTable is a member of RD's type identifier.
1960 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1961 llvm::Value *VTable, SourceLocation Loc);
1963 /// Returns whether we should perform a type checked load when loading a
1964 /// virtual function for virtual calls to members of RD. This is generally
1965 /// true when both vcall CFI and whole-program-vtables are enabled.
1966 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1968 /// Emit a type checked load from the given vtable.
1969 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1970 uint64_t VTableByteOffset);
1972 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1973 /// given phase of destruction for a destructor. The end result
1974 /// should call destructors on members and base classes in reverse
1975 /// order of their construction.
1976 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1978 /// ShouldInstrumentFunction - Return true if the current function should be
1979 /// instrumented with __cyg_profile_func_* calls
1980 bool ShouldInstrumentFunction();
1982 /// ShouldXRayInstrument - Return true if the current function should be
1983 /// instrumented with XRay nop sleds.
1984 bool ShouldXRayInstrumentFunction() const;
1986 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit
1987 /// XRay custom event handling calls.
1988 bool AlwaysEmitXRayCustomEvents() const;
1990 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit
1991 /// XRay typed event handling calls.
1992 bool AlwaysEmitXRayTypedEvents() const;
1994 /// Encode an address into a form suitable for use in a function prologue.
1995 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F,
1996 llvm::Constant *Addr);
1998 /// Decode an address used in a function prologue, encoded by \c
1999 /// EncodeAddrForUseInPrologue.
2000 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F,
2001 llvm::Value *EncodedAddr);
2003 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
2004 /// arguments for the given function. This is also responsible for naming the
2005 /// LLVM function arguments.
2006 void EmitFunctionProlog(const CGFunctionInfo &FI,
2008 const FunctionArgList &Args);
2010 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
2011 /// given temporary.
2012 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
2013 SourceLocation EndLoc);
2015 /// Emit a test that checks if the return value \p RV is nonnull.
2016 void EmitReturnValueCheck(llvm::Value *RV);
2018 /// EmitStartEHSpec - Emit the start of the exception spec.
2019 void EmitStartEHSpec(const Decl *D);
2021 /// EmitEndEHSpec - Emit the end of the exception spec.
2022 void EmitEndEHSpec(const Decl *D);
2024 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
2025 llvm::BasicBlock *getTerminateLandingPad();
2027 /// getTerminateLandingPad - Return a cleanup funclet that just calls
2029 llvm::BasicBlock *getTerminateFunclet();
2031 /// getTerminateHandler - Return a handler (not a landing pad, just
2032 /// a catch handler) that just calls terminate. This is used when
2033 /// a terminate scope encloses a try.
2034 llvm::BasicBlock *getTerminateHandler();
2036 llvm::Type *ConvertTypeForMem(QualType T);
2037 llvm::Type *ConvertType(QualType T);
2038 llvm::Type *ConvertType(const TypeDecl *T) {
2039 return ConvertType(getContext().getTypeDeclType(T));
2042 /// LoadObjCSelf - Load the value of self. This function is only valid while
2043 /// generating code for an Objective-C method.
2044 llvm::Value *LoadObjCSelf();
2046 /// TypeOfSelfObject - Return type of object that this self represents.
2047 QualType TypeOfSelfObject();
2049 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T.
2050 static TypeEvaluationKind getEvaluationKind(QualType T);
2052 static bool hasScalarEvaluationKind(QualType T) {
2053 return getEvaluationKind(T) == TEK_Scalar;
2056 static bool hasAggregateEvaluationKind(QualType T) {
2057 return getEvaluationKind(T) == TEK_Aggregate;
2060 /// createBasicBlock - Create an LLVM basic block.
2061 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
2062 llvm::Function *parent = nullptr,
2063 llvm::BasicBlock *before = nullptr) {
2064 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
2067 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
2069 JumpDest getJumpDestForLabel(const LabelDecl *S);
2071 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
2072 /// another basic block, simplify it. This assumes that no other code could
2073 /// potentially reference the basic block.
2074 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
2076 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
2077 /// adding a fall-through branch from the current insert block if
2078 /// necessary. It is legal to call this function even if there is no current
2079 /// insertion point.
2081 /// IsFinished - If true, indicates that the caller has finished emitting
2082 /// branches to the given block and does not expect to emit code into it. This
2083 /// means the block can be ignored if it is unreachable.
2084 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
2086 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
2087 /// near its uses, and leave the insertion point in it.
2088 void EmitBlockAfterUses(llvm::BasicBlock *BB);
2090 /// EmitBranch - Emit a branch to the specified basic block from the current
2091 /// insert block, taking care to avoid creation of branches from dummy
2092 /// blocks. It is legal to call this function even if there is no current
2093 /// insertion point.
2095 /// This function clears the current insertion point. The caller should follow
2096 /// calls to this function with calls to Emit*Block prior to generation new
2098 void EmitBranch(llvm::BasicBlock *Block);
2100 /// HaveInsertPoint - True if an insertion point is defined. If not, this
2101 /// indicates that the current code being emitted is unreachable.
2102 bool HaveInsertPoint() const {
2103 return Builder.GetInsertBlock() != nullptr;
2106 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
2107 /// emitted IR has a place to go. Note that by definition, if this function
2108 /// creates a block then that block is unreachable; callers may do better to
2109 /// detect when no insertion point is defined and simply skip IR generation.
2110 void EnsureInsertPoint() {
2111 if (!HaveInsertPoint())
2112 EmitBlock(createBasicBlock());
2115 /// ErrorUnsupported - Print out an error that codegen doesn't support the
2116 /// specified stmt yet.
2117 void ErrorUnsupported(const Stmt *S, const char *Type);
2119 //===--------------------------------------------------------------------===//
2121 //===--------------------------------------------------------------------===//
2123 LValue MakeAddrLValue(Address Addr, QualType T,
2124 AlignmentSource Source = AlignmentSource::Type) {
2125 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source),
2126 CGM.getTBAAAccessInfo(T));
2129 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo,
2130 TBAAAccessInfo TBAAInfo) {
2131 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo);
2134 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2135 AlignmentSource Source = AlignmentSource::Type) {
2136 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
2137 LValueBaseInfo(Source), CGM.getTBAAAccessInfo(T));
2140 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
2141 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
2142 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
2143 BaseInfo, TBAAInfo);
2146 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
2147 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
2148 CharUnits getNaturalTypeAlignment(QualType T,
2149 LValueBaseInfo *BaseInfo = nullptr,
2150 TBAAAccessInfo *TBAAInfo = nullptr,
2151 bool forPointeeType = false);
2152 CharUnits getNaturalPointeeTypeAlignment(QualType T,
2153 LValueBaseInfo *BaseInfo = nullptr,
2154 TBAAAccessInfo *TBAAInfo = nullptr);
2156 Address EmitLoadOfReference(LValue RefLVal,
2157 LValueBaseInfo *PointeeBaseInfo = nullptr,
2158 TBAAAccessInfo *PointeeTBAAInfo = nullptr);
2159 LValue EmitLoadOfReferenceLValue(LValue RefLVal);
2160 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy,
2161 AlignmentSource Source =
2162 AlignmentSource::Type) {
2163 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source),
2164 CGM.getTBAAAccessInfo(RefTy));
2165 return EmitLoadOfReferenceLValue(RefLVal);
2168 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
2169 LValueBaseInfo *BaseInfo = nullptr,
2170 TBAAAccessInfo *TBAAInfo = nullptr);
2171 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
2173 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
2174 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
2175 /// insertion point of the builder. The caller is responsible for setting an
2176 /// appropriate alignment on
2179 /// \p ArraySize is the number of array elements to be allocated if it
2182 /// LangAS::Default is the address space of pointers to local variables and
2183 /// temporaries, as exposed in the source language. In certain
2184 /// configurations, this is not the same as the alloca address space, and a
2185 /// cast is needed to lift the pointer from the alloca AS into
2186 /// LangAS::Default. This can happen when the target uses a restricted
2187 /// address space for the stack but the source language requires
2188 /// LangAS::Default to be a generic address space. The latter condition is
2189 /// common for most programming languages; OpenCL is an exception in that
2190 /// LangAS::Default is the private address space, which naturally maps
2193 /// Because the address of a temporary is often exposed to the program in
2194 /// various ways, this function will perform the cast. The original alloca
2195 /// instruction is returned through \p Alloca if it is not nullptr.
2197 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is
2198 /// more efficient if the caller knows that the address will not be exposed.
2199 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp",
2200 llvm::Value *ArraySize = nullptr);
2201 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
2202 const Twine &Name = "tmp",
2203 llvm::Value *ArraySize = nullptr,
2204 Address *Alloca = nullptr);
2205 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align,
2206 const Twine &Name = "tmp",
2207 llvm::Value *ArraySize = nullptr);
2209 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
2210 /// default ABI alignment of the given LLVM type.
2212 /// IMPORTANT NOTE: This is *not* generally the right alignment for
2213 /// any given AST type that happens to have been lowered to the
2214 /// given IR type. This should only ever be used for function-local,
2215 /// IR-driven manipulations like saving and restoring a value. Do
2216 /// not hand this address off to arbitrary IRGen routines, and especially
2217 /// do not pass it as an argument to a function that might expect a
2218 /// properly ABI-aligned value.
2219 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
2220 const Twine &Name = "tmp");
2222 /// InitTempAlloca - Provide an initial value for the given alloca which
2223 /// will be observable at all locations in the function.
2225 /// The address should be something that was returned from one of
2226 /// the CreateTempAlloca or CreateMemTemp routines, and the
2227 /// initializer must be valid in the entry block (i.e. it must
2228 /// either be a constant or an argument value).
2229 void InitTempAlloca(Address Alloca, llvm::Value *Value);
2231 /// CreateIRTemp - Create a temporary IR object of the given type, with
2232 /// appropriate alignment. This routine should only be used when an temporary
2233 /// value needs to be stored into an alloca (for example, to avoid explicit
2234 /// PHI construction), but the type is the IR type, not the type appropriate
2235 /// for storing in memory.
2237 /// That is, this is exactly equivalent to CreateMemTemp, but calling
2238 /// ConvertType instead of ConvertTypeForMem.
2239 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
2241 /// CreateMemTemp - Create a temporary memory object of the given type, with
2242 /// appropriate alignmen and cast it to the default address space. Returns
2243 /// the original alloca instruction by \p Alloca if it is not nullptr.
2244 Address CreateMemTemp(QualType T, const Twine &Name = "tmp",
2245 Address *Alloca = nullptr);
2246 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp",
2247 Address *Alloca = nullptr);
2249 /// CreateMemTemp - Create a temporary memory object of the given type, with
2250 /// appropriate alignmen without casting it to the default address space.
2251 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp");
2252 Address CreateMemTempWithoutCast(QualType T, CharUnits Align,
2253 const Twine &Name = "tmp");
2255 /// CreateAggTemp - Create a temporary memory object for the given
2257 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
2258 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
2260 AggValueSlot::IsNotDestructed,
2261 AggValueSlot::DoesNotNeedGCBarriers,
2262 AggValueSlot::IsNotAliased,
2263 AggValueSlot::DoesNotOverlap);
2266 /// Emit a cast to void* in the appropriate address space.
2267 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
2269 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
2270 /// expression and compare the result against zero, returning an Int1Ty value.
2271 llvm::Value *EvaluateExprAsBool(const Expr *E);
2273 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
2274 void EmitIgnoredExpr(const Expr *E);
2276 /// EmitAnyExpr - Emit code to compute the specified expression which can have
2277 /// any type. The result is returned as an RValue struct. If this is an
2278 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
2279 /// the result should be returned.
2281 /// \param ignoreResult True if the resulting value isn't used.
2282 RValue EmitAnyExpr(const Expr *E,
2283 AggValueSlot aggSlot = AggValueSlot::ignored(),
2284 bool ignoreResult = false);
2286 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
2287 // or the value of the expression, depending on how va_list is defined.
2288 Address EmitVAListRef(const Expr *E);
2290 /// Emit a "reference" to a __builtin_ms_va_list; this is
2291 /// always the value of the expression, because a __builtin_ms_va_list is a
2292 /// pointer to a char.
2293 Address EmitMSVAListRef(const Expr *E);
2295 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2296 /// always be accessible even if no aggregate location is provided.
2297 RValue EmitAnyExprToTemp(const Expr *E);
2299 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2300 /// arbitrary expression into the given memory location.
2301 void EmitAnyExprToMem(const Expr *E, Address Location,
2302 Qualifiers Quals, bool IsInitializer);
2304 void EmitAnyExprToExn(const Expr *E, Address Addr);
2306 /// EmitExprAsInit - Emits the code necessary to initialize a
2307 /// location in memory with the given initializer.
2308 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2309 bool capturedByInit);
2311 /// hasVolatileMember - returns true if aggregate type has a volatile
2313 bool hasVolatileMember(QualType T) {
2314 if (const RecordType *RT = T->getAs<RecordType>()) {
2315 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2316 return RD->hasVolatileMember();
2321 /// Determine whether a return value slot may overlap some other object.
2322 AggValueSlot::Overlap_t getOverlapForReturnValue() {
2323 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base
2324 // class subobjects. These cases may need to be revisited depending on the
2325 // resolution of the relevant core issue.
2326 return AggValueSlot::DoesNotOverlap;
2329 /// Determine whether a field initialization may overlap some other object.
2330 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD);
2332 /// Determine whether a base class initialization may overlap some other
2334 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD,
2335 const CXXRecordDecl *BaseRD,
2338 /// Emit an aggregate assignment.
2339 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) {
2340 bool IsVolatile = hasVolatileMember(EltTy);
2341 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile);
2344 void EmitAggregateCopyCtor(LValue Dest, LValue Src,
2345 AggValueSlot::Overlap_t MayOverlap) {
2346 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap);
2349 /// EmitAggregateCopy - Emit an aggregate copy.
2351 /// \param isVolatile \c true iff either the source or the destination is
2353 /// \param MayOverlap Whether the tail padding of the destination might be
2354 /// occupied by some other object. More efficient code can often be
2355 /// generated if not.
2356 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy,
2357 AggValueSlot::Overlap_t MayOverlap,
2358 bool isVolatile = false);
2360 /// GetAddrOfLocalVar - Return the address of a local variable.
2361 Address GetAddrOfLocalVar(const VarDecl *VD) {
2362 auto it = LocalDeclMap.find(VD);
2363 assert(it != LocalDeclMap.end() &&
2364 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2368 /// Given an opaque value expression, return its LValue mapping if it exists,
2369 /// otherwise create one.
2370 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e);
2372 /// Given an opaque value expression, return its RValue mapping if it exists,
2373 /// otherwise create one.
2374 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e);
2376 /// Get the index of the current ArrayInitLoopExpr, if any.
2377 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2379 /// getAccessedFieldNo - Given an encoded value and a result number, return
2380 /// the input field number being accessed.
2381 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2383 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2384 llvm::BasicBlock *GetIndirectGotoBlock();
2386 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2387 static bool IsWrappedCXXThis(const Expr *E);
2389 /// EmitNullInitialization - Generate code to set a value of the given type to
2390 /// null, If the type contains data member pointers, they will be initialized
2391 /// to -1 in accordance with the Itanium C++ ABI.
2392 void EmitNullInitialization(Address DestPtr, QualType Ty);
2394 /// Emits a call to an LLVM variable-argument intrinsic, either
2395 /// \c llvm.va_start or \c llvm.va_end.
2396 /// \param ArgValue A reference to the \c va_list as emitted by either
2397 /// \c EmitVAListRef or \c EmitMSVAListRef.
2398 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2399 /// calls \c llvm.va_end.
2400 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2402 /// Generate code to get an argument from the passed in pointer
2403 /// and update it accordingly.
2404 /// \param VE The \c VAArgExpr for which to generate code.
2405 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2406 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2407 /// \returns A pointer to the argument.
2408 // FIXME: We should be able to get rid of this method and use the va_arg
2409 // instruction in LLVM instead once it works well enough.
2410 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2412 /// emitArrayLength - Compute the length of an array, even if it's a
2413 /// VLA, and drill down to the base element type.
2414 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2418 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2419 /// the given variably-modified type and store them in the VLASizeMap.
2421 /// This function can be called with a null (unreachable) insert point.
2422 void EmitVariablyModifiedType(QualType Ty);
2424 struct VlaSizePair {
2425 llvm::Value *NumElts;
2428 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {}
2431 /// Return the number of elements for a single dimension
2432 /// for the given array type.
2433 VlaSizePair getVLAElements1D(const VariableArrayType *vla);
2434 VlaSizePair getVLAElements1D(QualType vla);
2436 /// Returns an LLVM value that corresponds to the size,
2437 /// in non-variably-sized elements, of a variable length array type,
2438 /// plus that largest non-variably-sized element type. Assumes that
2439 /// the type has already been emitted with EmitVariablyModifiedType.
2440 VlaSizePair getVLASize(const VariableArrayType *vla);
2441 VlaSizePair getVLASize(QualType vla);
2443 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2444 /// generating code for an C++ member function.
2445 llvm::Value *LoadCXXThis() {
2446 assert(CXXThisValue && "no 'this' value for this function");
2447 return CXXThisValue;
2449 Address LoadCXXThisAddress();
2451 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2453 // FIXME: Every place that calls LoadCXXVTT is something
2454 // that needs to be abstracted properly.
2455 llvm::Value *LoadCXXVTT() {
2456 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2457 return CXXStructorImplicitParamValue;
2460 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2461 /// complete class to the given direct base.
2463 GetAddressOfDirectBaseInCompleteClass(Address Value,
2464 const CXXRecordDecl *Derived,
2465 const CXXRecordDecl *Base,
2466 bool BaseIsVirtual);
2468 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2470 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2471 /// load of 'this' and returns address of the base class.
2472 Address GetAddressOfBaseClass(Address Value,
2473 const CXXRecordDecl *Derived,
2474 CastExpr::path_const_iterator PathBegin,
2475 CastExpr::path_const_iterator PathEnd,
2476 bool NullCheckValue, SourceLocation Loc);
2478 Address GetAddressOfDerivedClass(Address Value,
2479 const CXXRecordDecl *Derived,
2480 CastExpr::path_const_iterator PathBegin,
2481 CastExpr::path_const_iterator PathEnd,
2482 bool NullCheckValue);
2484 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2485 /// base constructor/destructor with virtual bases.
2486 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2487 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2488 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2491 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2492 CXXCtorType CtorType,
2493 const FunctionArgList &Args,
2494 SourceLocation Loc);
2495 // It's important not to confuse this and the previous function. Delegating
2496 // constructors are the C++0x feature. The constructor delegate optimization
2497 // is used to reduce duplication in the base and complete consturctors where
2498 // they are substantially the same.
2499 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2500 const FunctionArgList &Args);
2502 /// Emit a call to an inheriting constructor (that is, one that invokes a
2503 /// constructor inherited from a base class) by inlining its definition. This
2504 /// is necessary if the ABI does not support forwarding the arguments to the
2505 /// base class constructor (because they're variadic or similar).
2506 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2507 CXXCtorType CtorType,
2508 bool ForVirtualBase,
2512 /// Emit a call to a constructor inherited from a base class, passing the
2513 /// current constructor's arguments along unmodified (without even making
2515 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2516 bool ForVirtualBase, Address This,
2517 bool InheritedFromVBase,
2518 const CXXInheritedCtorInitExpr *E);
2520 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2521 bool ForVirtualBase, bool Delegating,
2522 AggValueSlot ThisAVS, const CXXConstructExpr *E);
2524 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2525 bool ForVirtualBase, bool Delegating,
2526 Address This, CallArgList &Args,
2527 AggValueSlot::Overlap_t Overlap,
2528 SourceLocation Loc, bool NewPointerIsChecked);
2530 /// Emit assumption load for all bases. Requires to be be called only on
2531 /// most-derived class and not under construction of the object.
2532 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2534 /// Emit assumption that vptr load == global vtable.
2535 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2537 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2538 Address This, Address Src,
2539 const CXXConstructExpr *E);
2541 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2542 const ArrayType *ArrayTy,
2544 const CXXConstructExpr *E,
2545 bool NewPointerIsChecked,
2546 bool ZeroInitialization = false);
2548 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2549 llvm::Value *NumElements,
2551 const CXXConstructExpr *E,
2552 bool NewPointerIsChecked,
2553 bool ZeroInitialization = false);
2555 static Destroyer destroyCXXObject;
2557 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2558 bool ForVirtualBase, bool Delegating, Address This,
2561 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2562 llvm::Type *ElementTy, Address NewPtr,
2563 llvm::Value *NumElements,
2564 llvm::Value *AllocSizeWithoutCookie);
2566 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2569 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2570 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2572 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2573 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2575 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2576 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2577 CharUnits CookieSize = CharUnits());
2579 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2580 const CallExpr *TheCallExpr, bool IsDelete);
2582 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2583 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2584 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2586 /// Situations in which we might emit a check for the suitability of a
2587 /// pointer or glvalue.
2588 enum TypeCheckKind {
2589 /// Checking the operand of a load. Must be suitably sized and aligned.
2591 /// Checking the destination of a store. Must be suitably sized and aligned.
2593 /// Checking the bound value in a reference binding. Must be suitably sized
2594 /// and aligned, but is not required to refer to an object (until the
2595 /// reference is used), per core issue 453.
2596 TCK_ReferenceBinding,
2597 /// Checking the object expression in a non-static data member access. Must
2598 /// be an object within its lifetime.
2600 /// Checking the 'this' pointer for a call to a non-static member function.
2601 /// Must be an object within its lifetime.
2603 /// Checking the 'this' pointer for a constructor call.
2604 TCK_ConstructorCall,
2605 /// Checking the operand of a static_cast to a derived pointer type. Must be
2606 /// null or an object within its lifetime.
2607 TCK_DowncastPointer,
2608 /// Checking the operand of a static_cast to a derived reference type. Must
2609 /// be an object within its lifetime.
2610 TCK_DowncastReference,
2611 /// Checking the operand of a cast to a base object. Must be suitably sized
2614 /// Checking the operand of a cast to a virtual base object. Must be an
2615 /// object within its lifetime.
2616 TCK_UpcastToVirtualBase,
2617 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2619 /// Checking the operand of a dynamic_cast or a typeid expression. Must be
2620 /// null or an object within its lifetime.
2621 TCK_DynamicOperation
2624 /// Determine whether the pointer type check \p TCK permits null pointers.
2625 static bool isNullPointerAllowed(TypeCheckKind TCK);
2627 /// Determine whether the pointer type check \p TCK requires a vptr check.
2628 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty);
2630 /// Whether any type-checking sanitizers are enabled. If \c false,
2631 /// calls to EmitTypeCheck can be skipped.
2632 bool sanitizePerformTypeCheck() const;
2634 /// Emit a check that \p V is the address of storage of the
2635 /// appropriate size and alignment for an object of type \p Type
2636 /// (or if ArraySize is provided, for an array of that bound).
2637 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2638 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2639 SanitizerSet SkippedChecks = SanitizerSet(),
2640 llvm::Value *ArraySize = nullptr);
2642 /// Emit a check that \p Base points into an array object, which
2643 /// we can access at index \p Index. \p Accessed should be \c false if we
2644 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2645 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2646 QualType IndexType, bool Accessed);
2648 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2649 bool isInc, bool isPre);
2650 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2651 bool isInc, bool isPre);
2653 /// Converts Location to a DebugLoc, if debug information is enabled.
2654 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2656 /// Get the record field index as represented in debug info.
2657 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex);
2660 //===--------------------------------------------------------------------===//
2661 // Declaration Emission
2662 //===--------------------------------------------------------------------===//
2664 /// EmitDecl - Emit a declaration.
2666 /// This function can be called with a null (unreachable) insert point.
2667 void EmitDecl(const Decl &D);
2669 /// EmitVarDecl - Emit a local variable declaration.
2671 /// This function can be called with a null (unreachable) insert point.
2672 void EmitVarDecl(const VarDecl &D);
2674 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2675 bool capturedByInit);
2677 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2678 llvm::Value *Address);
2680 /// Determine whether the given initializer is trivial in the sense
2681 /// that it requires no code to be generated.
2682 bool isTrivialInitializer(const Expr *Init);
2684 /// EmitAutoVarDecl - Emit an auto variable declaration.
2686 /// This function can be called with a null (unreachable) insert point.
2687 void EmitAutoVarDecl(const VarDecl &D);
2689 class AutoVarEmission {
2690 friend class CodeGenFunction;
2692 const VarDecl *Variable;
2694 /// The address of the alloca for languages with explicit address space
2695 /// (e.g. OpenCL) or alloca casted to generic pointer for address space
2696 /// agnostic languages (e.g. C++). Invalid if the variable was emitted
2697 /// as a global constant.
2700 llvm::Value *NRVOFlag;
2702 /// True if the variable is a __block variable that is captured by an
2704 bool IsEscapingByRef;
2706 /// True if the variable is of aggregate type and has a constant
2708 bool IsConstantAggregate;
2710 /// Non-null if we should use lifetime annotations.
2711 llvm::Value *SizeForLifetimeMarkers;
2713 /// Address with original alloca instruction. Invalid if the variable was
2714 /// emitted as a global constant.
2718 AutoVarEmission(Invalid)
2719 : Variable(nullptr), Addr(Address::invalid()),
2720 AllocaAddr(Address::invalid()) {}
2722 AutoVarEmission(const VarDecl &variable)
2723 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2724 IsEscapingByRef(false), IsConstantAggregate(false),
2725 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {}
2727 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2730 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2732 bool useLifetimeMarkers() const {
2733 return SizeForLifetimeMarkers != nullptr;
2735 llvm::Value *getSizeForLifetimeMarkers() const {
2736 assert(useLifetimeMarkers());
2737 return SizeForLifetimeMarkers;
2740 /// Returns the raw, allocated address, which is not necessarily
2741 /// the address of the object itself. It is casted to default
2742 /// address space for address space agnostic languages.
2743 Address getAllocatedAddress() const {
2747 /// Returns the address for the original alloca instruction.
2748 Address getOriginalAllocatedAddress() const { return AllocaAddr; }
2750 /// Returns the address of the object within this declaration.
2751 /// Note that this does not chase the forwarding pointer for
2753 Address getObjectAddress(CodeGenFunction &CGF) const {
2754 if (!IsEscapingByRef) return Addr;
2756 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2759 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2760 void EmitAutoVarInit(const AutoVarEmission &emission);
2761 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2762 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2763 QualType::DestructionKind dtorKind);
2765 /// Emits the alloca and debug information for the size expressions for each
2766 /// dimension of an array. It registers the association of its (1-dimensional)
2767 /// QualTypes and size expression's debug node, so that CGDebugInfo can
2768 /// reference this node when creating the DISubrange object to describe the
2770 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI,
2772 bool EmitDebugInfo);
2774 void EmitStaticVarDecl(const VarDecl &D,
2775 llvm::GlobalValue::LinkageTypes Linkage);
2780 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2782 static ParamValue forDirect(llvm::Value *value) {
2783 return ParamValue(value, 0);
2785 static ParamValue forIndirect(Address addr) {
2786 assert(!addr.getAlignment().isZero());
2787 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2790 bool isIndirect() const { return Alignment != 0; }
2791 llvm::Value *getAnyValue() const { return Value; }
2793 llvm::Value *getDirectValue() const {
2794 assert(!isIndirect());
2798 Address getIndirectAddress() const {
2799 assert(isIndirect());
2800 return Address(Value, CharUnits::fromQuantity(Alignment));
2804 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2805 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2807 /// protectFromPeepholes - Protect a value that we're intending to
2808 /// store to the side, but which will probably be used later, from
2809 /// aggressive peepholing optimizations that might delete it.
2811 /// Pass the result to unprotectFromPeepholes to declare that
2812 /// protection is no longer required.
2814 /// There's no particular reason why this shouldn't apply to
2815 /// l-values, it's just that no existing peepholes work on pointers.
2816 PeepholeProtection protectFromPeepholes(RValue rvalue);
2817 void unprotectFromPeepholes(PeepholeProtection protection);
2819 void EmitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty,
2821 SourceLocation AssumptionLoc,
2822 llvm::Value *Alignment,
2823 llvm::Value *OffsetValue,
2824 llvm::Value *TheCheck,
2825 llvm::Instruction *Assumption);
2827 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
2828 SourceLocation Loc, SourceLocation AssumptionLoc,
2829 llvm::Value *Alignment,
2830 llvm::Value *OffsetValue = nullptr);
2832 void EmitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty,
2833 SourceLocation Loc, SourceLocation AssumptionLoc,
2835 llvm::Value *OffsetValue = nullptr);
2837 void EmitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E,
2838 SourceLocation AssumptionLoc, unsigned Alignment,
2839 llvm::Value *OffsetValue = nullptr);
2841 //===--------------------------------------------------------------------===//
2842 // Statement Emission
2843 //===--------------------------------------------------------------------===//
2845 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2846 void EmitStopPoint(const Stmt *S);
2848 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2849 /// this function even if there is no current insertion point.
2851 /// This function may clear the current insertion point; callers should use
2852 /// EnsureInsertPoint if they wish to subsequently generate code without first
2853 /// calling EmitBlock, EmitBranch, or EmitStmt.
2854 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None);
2856 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2857 /// necessarily require an insertion point or debug information; typically
2858 /// because the statement amounts to a jump or a container of other
2861 /// \return True if the statement was handled.
2862 bool EmitSimpleStmt(const Stmt *S);
2864 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2865 AggValueSlot AVS = AggValueSlot::ignored());
2866 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2867 bool GetLast = false,
2869 AggValueSlot::ignored());
2871 /// EmitLabel - Emit the block for the given label. It is legal to call this
2872 /// function even if there is no current insertion point.
2873 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2875 void EmitLabelStmt(const LabelStmt &S);
2876 void EmitAttributedStmt(const AttributedStmt &S);
2877 void EmitGotoStmt(const GotoStmt &S);
2878 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2879 void EmitIfStmt(const IfStmt &S);
2881 void EmitWhileStmt(const WhileStmt &S,
2882 ArrayRef<const Attr *> Attrs = None);
2883 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2884 void EmitForStmt(const ForStmt &S,
2885 ArrayRef<const Attr *> Attrs = None);
2886 void EmitReturnStmt(const ReturnStmt &S);
2887 void EmitDeclStmt(const DeclStmt &S);
2888 void EmitBreakStmt(const BreakStmt &S);
2889 void EmitContinueStmt(const ContinueStmt &S);
2890 void EmitSwitchStmt(const SwitchStmt &S);
2891 void EmitDefaultStmt(const DefaultStmt &S);
2892 void EmitCaseStmt(const CaseStmt &S);
2893 void EmitCaseStmtRange(const CaseStmt &S);
2894 void EmitAsmStmt(const AsmStmt &S);
2896 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2897 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2898 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2899 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2900 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2902 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2903 void EmitCoreturnStmt(const CoreturnStmt &S);
2904 RValue EmitCoawaitExpr(const CoawaitExpr &E,
2905 AggValueSlot aggSlot = AggValueSlot::ignored(),
2906 bool ignoreResult = false);
2907 LValue EmitCoawaitLValue(const CoawaitExpr *E);
2908 RValue EmitCoyieldExpr(const CoyieldExpr &E,
2909 AggValueSlot aggSlot = AggValueSlot::ignored(),
2910 bool ignoreResult = false);
2911 LValue EmitCoyieldLValue(const CoyieldExpr *E);
2912 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2914 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2915 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2917 void EmitCXXTryStmt(const CXXTryStmt &S);
2918 void EmitSEHTryStmt(const SEHTryStmt &S);
2919 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2920 void EnterSEHTryStmt(const SEHTryStmt &S);
2921 void ExitSEHTryStmt(const SEHTryStmt &S);
2923 void pushSEHCleanup(CleanupKind kind,
2924 llvm::Function *FinallyFunc);
2925 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2926 const Stmt *OutlinedStmt);
2928 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2929 const SEHExceptStmt &Except);
2931 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2932 const SEHFinallyStmt &Finally);
2934 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2935 llvm::Value *ParentFP,
2936 llvm::Value *EntryEBP);
2937 llvm::Value *EmitSEHExceptionCode();
2938 llvm::Value *EmitSEHExceptionInfo();
2939 llvm::Value *EmitSEHAbnormalTermination();
2941 /// Emit simple code for OpenMP directives in Simd-only mode.
2942 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D);
2944 /// Scan the outlined statement for captures from the parent function. For
2945 /// each capture, mark the capture as escaped and emit a call to
2946 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2947 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2950 /// Recovers the address of a local in a parent function. ParentVar is the
2951 /// address of the variable used in the immediate parent function. It can
2952 /// either be an alloca or a call to llvm.localrecover if there are nested
2953 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2955 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2957 llvm::Value *ParentFP);
2959 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2960 ArrayRef<const Attr *> Attrs = None);
2962 /// Controls insertion of cancellation exit blocks in worksharing constructs.
2963 class OMPCancelStackRAII {
2964 CodeGenFunction &CGF;
2967 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
2970 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
2972 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
2975 /// Returns calculated size of the specified type.
2976 llvm::Value *getTypeSize(QualType Ty);
2977 LValue InitCapturedStruct(const CapturedStmt &S);
2978 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2979 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2980 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2981 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2982 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2983 SmallVectorImpl<llvm::Value *> &CapturedVars);
2984 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2985 SourceLocation Loc);
2986 /// Perform element by element copying of arrays with type \a
2987 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2988 /// generated by \a CopyGen.
2990 /// \param DestAddr Address of the destination array.
2991 /// \param SrcAddr Address of the source array.
2992 /// \param OriginalType Type of destination and source arrays.
2993 /// \param CopyGen Copying procedure that copies value of single array element
2994 /// to another single array element.
2995 void EmitOMPAggregateAssign(
2996 Address DestAddr, Address SrcAddr, QualType OriginalType,
2997 const llvm::function_ref<void(Address, Address)> CopyGen);
2998 /// Emit proper copying of data from one variable to another.
3000 /// \param OriginalType Original type of the copied variables.
3001 /// \param DestAddr Destination address.
3002 /// \param SrcAddr Source address.
3003 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
3004 /// type of the base array element).
3005 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
3006 /// the base array element).
3007 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
3009 void EmitOMPCopy(QualType OriginalType,
3010 Address DestAddr, Address SrcAddr,
3011 const VarDecl *DestVD, const VarDecl *SrcVD,
3013 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or
3014 /// \a X = \a E \a BO \a E.
3016 /// \param X Value to be updated.
3017 /// \param E Update value.
3018 /// \param BO Binary operation for update operation.
3019 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
3020 /// expression, false otherwise.
3021 /// \param AO Atomic ordering of the generated atomic instructions.
3022 /// \param CommonGen Code generator for complex expressions that cannot be
3023 /// expressed through atomicrmw instruction.
3024 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
3025 /// generated, <false, RValue::get(nullptr)> otherwise.
3026 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
3027 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
3028 llvm::AtomicOrdering AO, SourceLocation Loc,
3029 const llvm::function_ref<RValue(RValue)> CommonGen);
3030 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
3031 OMPPrivateScope &PrivateScope);
3032 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
3033 OMPPrivateScope &PrivateScope);
3034 void EmitOMPUseDevicePtrClause(
3035 const OMPClause &C, OMPPrivateScope &PrivateScope,
3036 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
3037 /// Emit code for copyin clause in \a D directive. The next code is
3038 /// generated at the start of outlined functions for directives:
3040 /// threadprivate_var1 = master_threadprivate_var1;
3041 /// operator=(threadprivate_var2, master_threadprivate_var2);
3043 /// __kmpc_barrier(&loc, global_tid);
3046 /// \param D OpenMP directive possibly with 'copyin' clause(s).
3047 /// \returns true if at least one copyin variable is found, false otherwise.
3048 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
3049 /// Emit initial code for lastprivate variables. If some variable is
3050 /// not also firstprivate, then the default initialization is used. Otherwise
3051 /// initialization of this variable is performed by EmitOMPFirstprivateClause
3054 /// \param D Directive that may have 'lastprivate' directives.
3055 /// \param PrivateScope Private scope for capturing lastprivate variables for
3056 /// proper codegen in internal captured statement.
3058 /// \returns true if there is at least one lastprivate variable, false
3060 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
3061 OMPPrivateScope &PrivateScope);
3062 /// Emit final copying of lastprivate values to original variables at
3063 /// the end of the worksharing or simd directive.
3065 /// \param D Directive that has at least one 'lastprivate' directives.
3066 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
3067 /// it is the last iteration of the loop code in associated directive, or to
3068 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
3069 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
3071 llvm::Value *IsLastIterCond = nullptr);
3072 /// Emit initial code for linear clauses.
3073 void EmitOMPLinearClause(const OMPLoopDirective &D,
3074 CodeGenFunction::OMPPrivateScope &PrivateScope);
3075 /// Emit final code for linear clauses.
3076 /// \param CondGen Optional conditional code for final part of codegen for
3078 void EmitOMPLinearClauseFinal(
3079 const OMPLoopDirective &D,
3080 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3081 /// Emit initial code for reduction variables. Creates reduction copies
3082 /// and initializes them with the values according to OpenMP standard.
3084 /// \param D Directive (possibly) with the 'reduction' clause.
3085 /// \param PrivateScope Private scope for capturing reduction variables for
3086 /// proper codegen in internal captured statement.
3088 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
3089 OMPPrivateScope &PrivateScope);
3090 /// Emit final update of reduction values to original variables at
3091 /// the end of the directive.
3093 /// \param D Directive that has at least one 'reduction' directives.
3094 /// \param ReductionKind The kind of reduction to perform.
3095 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
3096 const OpenMPDirectiveKind ReductionKind);
3097 /// Emit initial code for linear variables. Creates private copies
3098 /// and initializes them with the values according to OpenMP standard.
3100 /// \param D Directive (possibly) with the 'linear' clause.
3101 /// \return true if at least one linear variable is found that should be
3102 /// initialized with the value of the original variable, false otherwise.
3103 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D);
3105 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
3106 llvm::Function * /*OutlinedFn*/,
3107 const OMPTaskDataTy & /*Data*/)>
3109 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
3110 const OpenMPDirectiveKind CapturedRegion,
3111 const RegionCodeGenTy &BodyGen,
3112 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
3113 struct OMPTargetDataInfo {
3114 Address BasePointersArray = Address::invalid();
3115 Address PointersArray = Address::invalid();
3116 Address SizesArray = Address::invalid();
3117 unsigned NumberOfTargetItems = 0;
3118 explicit OMPTargetDataInfo() = default;
3119 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray,
3120 Address SizesArray, unsigned NumberOfTargetItems)
3121 : BasePointersArray(BasePointersArray), PointersArray(PointersArray),
3122 SizesArray(SizesArray), NumberOfTargetItems(NumberOfTargetItems) {}
3124 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S,
3125 const RegionCodeGenTy &BodyGen,
3126 OMPTargetDataInfo &InputInfo);
3128 void EmitOMPParallelDirective(const OMPParallelDirective &S);
3129 void EmitOMPSimdDirective(const OMPSimdDirective &S);
3130 void EmitOMPForDirective(const OMPForDirective &S);
3131 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
3132 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
3133 void EmitOMPSectionDirective(const OMPSectionDirective &S);
3134 void EmitOMPSingleDirective(const OMPSingleDirective &S);
3135 void EmitOMPMasterDirective(const OMPMasterDirective &S);
3136 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
3137 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
3138 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
3139 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
3140 void EmitOMPTaskDirective(const OMPTaskDirective &S);
3141 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
3142 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
3143 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
3144 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
3145 void EmitOMPFlushDirective(const OMPFlushDirective &S);
3146 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
3147 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
3148 void EmitOMPTargetDirective(const OMPTargetDirective &S);
3149 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
3150 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
3151 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
3152 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
3153 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
3155 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
3156 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
3158 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
3159 void EmitOMPCancelDirective(const OMPCancelDirective &S);
3160 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
3161 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
3162 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
3163 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
3164 void EmitOMPDistributeParallelForDirective(
3165 const OMPDistributeParallelForDirective &S);
3166 void EmitOMPDistributeParallelForSimdDirective(
3167 const OMPDistributeParallelForSimdDirective &S);
3168 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
3169 void EmitOMPTargetParallelForSimdDirective(
3170 const OMPTargetParallelForSimdDirective &S);
3171 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
3172 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
3174 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
3175 void EmitOMPTeamsDistributeParallelForSimdDirective(
3176 const OMPTeamsDistributeParallelForSimdDirective &S);
3177 void EmitOMPTeamsDistributeParallelForDirective(
3178 const OMPTeamsDistributeParallelForDirective &S);
3179 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
3180 void EmitOMPTargetTeamsDistributeDirective(
3181 const OMPTargetTeamsDistributeDirective &S);
3182 void EmitOMPTargetTeamsDistributeParallelForDirective(
3183 const OMPTargetTeamsDistributeParallelForDirective &S);
3184 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
3185 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3186 void EmitOMPTargetTeamsDistributeSimdDirective(
3187 const OMPTargetTeamsDistributeSimdDirective &S);
3189 /// Emit device code for the target directive.
3190 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
3191 StringRef ParentName,
3192 const OMPTargetDirective &S);
3194 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3195 const OMPTargetParallelDirective &S);
3196 /// Emit device code for the target parallel for directive.
3197 static void EmitOMPTargetParallelForDeviceFunction(
3198 CodeGenModule &CGM, StringRef ParentName,
3199 const OMPTargetParallelForDirective &S);
3200 /// Emit device code for the target parallel for simd directive.
3201 static void EmitOMPTargetParallelForSimdDeviceFunction(
3202 CodeGenModule &CGM, StringRef ParentName,
3203 const OMPTargetParallelForSimdDirective &S);
3204 /// Emit device code for the target teams directive.
3206 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
3207 const OMPTargetTeamsDirective &S);
3208 /// Emit device code for the target teams distribute directive.
3209 static void EmitOMPTargetTeamsDistributeDeviceFunction(
3210 CodeGenModule &CGM, StringRef ParentName,
3211 const OMPTargetTeamsDistributeDirective &S);
3212 /// Emit device code for the target teams distribute simd directive.
3213 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
3214 CodeGenModule &CGM, StringRef ParentName,
3215 const OMPTargetTeamsDistributeSimdDirective &S);
3216 /// Emit device code for the target simd directive.
3217 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
3218 StringRef ParentName,
3219 const OMPTargetSimdDirective &S);
3220 /// Emit device code for the target teams distribute parallel for simd
3222 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
3223 CodeGenModule &CGM, StringRef ParentName,
3224 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
3226 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
3227 CodeGenModule &CGM, StringRef ParentName,
3228 const OMPTargetTeamsDistributeParallelForDirective &S);
3229 /// Emit inner loop of the worksharing/simd construct.
3231 /// \param S Directive, for which the inner loop must be emitted.
3232 /// \param RequiresCleanup true, if directive has some associated private
3234 /// \param LoopCond Bollean condition for loop continuation.
3235 /// \param IncExpr Increment expression for loop control variable.
3236 /// \param BodyGen Generator for the inner body of the inner loop.
3237 /// \param PostIncGen Genrator for post-increment code (required for ordered
3238 /// loop directvies).
3239 void EmitOMPInnerLoop(
3240 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
3241 const Expr *IncExpr,
3242 const llvm::function_ref<void(CodeGenFunction &)> BodyGen,
3243 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen);
3245 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
3246 /// Emit initial code for loop counters of loop-based directives.
3247 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
3248 OMPPrivateScope &LoopScope);
3250 /// Helper for the OpenMP loop directives.
3251 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
3253 /// Emit code for the worksharing loop-based directive.
3254 /// \return true, if this construct has any lastprivate clause, false -
3256 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
3257 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
3258 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3260 /// Emit code for the distribute loop-based directive.
3261 void EmitOMPDistributeLoop(const OMPLoopDirective &S,
3262 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
3264 /// Helpers for the OpenMP loop directives.
3265 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
3266 void EmitOMPSimdFinal(
3267 const OMPLoopDirective &D,
3268 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen);
3270 /// Emits the lvalue for the expression with possibly captured variable.
3271 LValue EmitOMPSharedLValue(const Expr *E);
3274 /// Helpers for blocks.
3275 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
3277 /// struct with the values to be passed to the OpenMP loop-related functions
3278 struct OMPLoopArguments {
3279 /// loop lower bound
3280 Address LB = Address::invalid();
3281 /// loop upper bound
3282 Address UB = Address::invalid();
3284 Address ST = Address::invalid();
3285 /// isLastIteration argument for runtime functions
3286 Address IL = Address::invalid();
3287 /// Chunk value generated by sema
3288 llvm::Value *Chunk = nullptr;
3289 /// EnsureUpperBound
3290 Expr *EUB = nullptr;
3291 /// IncrementExpression
3292 Expr *IncExpr = nullptr;
3293 /// Loop initialization
3294 Expr *Init = nullptr;
3295 /// Loop exit condition
3296 Expr *Cond = nullptr;
3297 /// Update of LB after a whole chunk has been executed
3298 Expr *NextLB = nullptr;
3299 /// Update of UB after a whole chunk has been executed
3300 Expr *NextUB = nullptr;
3301 OMPLoopArguments() = default;
3302 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
3303 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
3304 Expr *IncExpr = nullptr, Expr *Init = nullptr,
3305 Expr *Cond = nullptr, Expr *NextLB = nullptr,
3306 Expr *NextUB = nullptr)
3307 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
3308 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
3311 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
3312 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
3313 const OMPLoopArguments &LoopArgs,
3314 const CodeGenLoopTy &CodeGenLoop,
3315 const CodeGenOrderedTy &CodeGenOrdered);
3316 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
3317 bool IsMonotonic, const OMPLoopDirective &S,
3318 OMPPrivateScope &LoopScope, bool Ordered,
3319 const OMPLoopArguments &LoopArgs,
3320 const CodeGenDispatchBoundsTy &CGDispatchBounds);
3321 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
3322 const OMPLoopDirective &S,
3323 OMPPrivateScope &LoopScope,
3324 const OMPLoopArguments &LoopArgs,
3325 const CodeGenLoopTy &CodeGenLoopContent);
3326 /// Emit code for sections directive.
3327 void EmitSections(const OMPExecutableDirective &S);
3331 //===--------------------------------------------------------------------===//
3332 // LValue Expression Emission
3333 //===--------------------------------------------------------------------===//
3335 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
3336 RValue GetUndefRValue(QualType Ty);
3338 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
3339 /// and issue an ErrorUnsupported style diagnostic (using the
3341 RValue EmitUnsupportedRValue(const Expr *E,
3344 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
3345 /// an ErrorUnsupported style diagnostic (using the provided Name).
3346 LValue EmitUnsupportedLValue(const Expr *E,
3349 /// EmitLValue - Emit code to compute a designator that specifies the location
3350 /// of the expression.
3352 /// This can return one of two things: a simple address or a bitfield
3353 /// reference. In either case, the LLVM Value* in the LValue structure is
3354 /// guaranteed to be an LLVM pointer type.
3356 /// If this returns a bitfield reference, nothing about the pointee type of
3357 /// the LLVM value is known: For example, it may not be a pointer to an
3360 /// If this returns a normal address, and if the lvalue's C type is fixed
3361 /// size, this method guarantees that the returned pointer type will point to
3362 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
3363 /// variable length type, this is not possible.
3365 LValue EmitLValue(const Expr *E);
3367 /// Same as EmitLValue but additionally we generate checking code to
3368 /// guard against undefined behavior. This is only suitable when we know
3369 /// that the address will be used to access the object.
3370 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
3372 RValue convertTempToRValue(Address addr, QualType type,
3373 SourceLocation Loc);
3375 void EmitAtomicInit(Expr *E, LValue lvalue);
3377 bool LValueIsSuitableForInlineAtomic(LValue Src);
3379 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
3380 AggValueSlot Slot = AggValueSlot::ignored());
3382 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
3383 llvm::AtomicOrdering AO, bool IsVolatile = false,
3384 AggValueSlot slot = AggValueSlot::ignored());
3386 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
3388 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
3389 bool IsVolatile, bool isInit);
3391 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
3392 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
3393 llvm::AtomicOrdering Success =
3394 llvm::AtomicOrdering::SequentiallyConsistent,
3395 llvm::AtomicOrdering Failure =
3396 llvm::AtomicOrdering::SequentiallyConsistent,
3397 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
3399 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
3400 const llvm::function_ref<RValue(RValue)> &UpdateOp,
3403 /// EmitToMemory - Change a scalar value from its value
3404 /// representation to its in-memory representation.
3405 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
3407 /// EmitFromMemory - Change a scalar value from its memory
3408 /// representation to its value representation.
3409 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
3411 /// Check if the scalar \p Value is within the valid range for the given
3414 /// Returns true if a check is needed (even if the range is unknown).
3415 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
3416 SourceLocation Loc);
3418 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3419 /// care to appropriately convert from the memory representation to
3420 /// the LLVM value representation.
3421 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3423 AlignmentSource Source = AlignmentSource::Type,
3424 bool isNontemporal = false) {
3425 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source),
3426 CGM.getTBAAAccessInfo(Ty), isNontemporal);
3429 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
3430 SourceLocation Loc, LValueBaseInfo BaseInfo,
3431 TBAAAccessInfo TBAAInfo,
3432 bool isNontemporal = false);
3434 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3435 /// care to appropriately convert from the memory representation to
3436 /// the LLVM value representation. The l-value must be a simple
3438 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3440 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3441 /// care to appropriately convert from the memory representation to
3442 /// the LLVM value representation.
3443 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3444 bool Volatile, QualType Ty,
3445 AlignmentSource Source = AlignmentSource::Type,
3446 bool isInit = false, bool isNontemporal = false) {
3447 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source),
3448 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal);
3451 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3452 bool Volatile, QualType Ty,
3453 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo,
3454 bool isInit = false, bool isNontemporal = false);
3456 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3457 /// care to appropriately convert from the memory representation to
3458 /// the LLVM value representation. The l-value must be a simple
3459 /// l-value. The isInit flag indicates whether this is an initialization.
3460 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3461 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3463 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3464 /// this method emits the address of the lvalue, then loads the result as an
3465 /// rvalue, returning the rvalue.
3466 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3467 RValue EmitLoadOfExtVectorElementLValue(LValue V);
3468 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3469 RValue EmitLoadOfGlobalRegLValue(LValue LV);
3471 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3472 /// lvalue, where both are guaranteed to the have the same type, and that type
3474 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3475 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3476 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3478 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3479 /// as EmitStoreThroughLValue.
3481 /// \param Result [out] - If non-null, this will be set to a Value* for the
3482 /// bit-field contents after the store, appropriate for use as the result of
3483 /// an assignment to the bit-field.
3484 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3485 llvm::Value **Result=nullptr);
3487 /// Emit an l-value for an assignment (simple or compound) of complex type.
3488 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3489 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3490 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3491 llvm::Value *&Result);
3493 // Note: only available for agg return types
3494 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3495 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3496 // Note: only available for agg return types
3497 LValue EmitCallExprLValue(const CallExpr *E);
3498 // Note: only available for agg return types
3499 LValue EmitVAArgExprLValue(const VAArgExpr *E);
3500 LValue EmitDeclRefLValue(const DeclRefExpr *E);
3501 LValue EmitStringLiteralLValue(const StringLiteral *E);
3502 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3503 LValue EmitPredefinedLValue(const PredefinedExpr *E);
3504 LValue EmitUnaryOpLValue(const UnaryOperator *E);
3505 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3506 bool Accessed = false);
3507 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3508 bool IsLowerBound = true);
3509 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3510 LValue EmitMemberExpr(const MemberExpr *E);
3511 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3512 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3513 LValue EmitInitListLValue(const InitListExpr *E);
3514 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3515 LValue EmitCastLValue(const CastExpr *E);
3516 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3517 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3519 Address EmitExtVectorElementLValue(LValue V);
3521 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3523 Address EmitArrayToPointerDecay(const Expr *Array,
3524 LValueBaseInfo *BaseInfo = nullptr,
3525 TBAAAccessInfo *TBAAInfo = nullptr);
3527 class ConstantEmission {
3528 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3529 ConstantEmission(llvm::Constant *C, bool isReference)
3530 : ValueAndIsReference(C, isReference) {}
3532 ConstantEmission() {}
3533 static ConstantEmission forReference(llvm::Constant *C) {
3534 return ConstantEmission(C, true);
3536 static ConstantEmission forValue(llvm::Constant *C) {
3537 return ConstantEmission(C, false);
3540 explicit operator bool() const {
3541 return ValueAndIsReference.getOpaqueValue() != nullptr;
3544 bool isReference() const { return ValueAndIsReference.getInt(); }
3545 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3546 assert(isReference());
3547 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3548 refExpr->getType());
3551 llvm::Constant *getValue() const {
3552 assert(!isReference());
3553 return ValueAndIsReference.getPointer();
3557 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3558 ConstantEmission tryEmitAsConstant(const MemberExpr *ME);
3559 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E);
3561 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3562 AggValueSlot slot = AggValueSlot::ignored());
3563 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3565 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3566 const ObjCIvarDecl *Ivar);
3567 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3568 LValue EmitLValueForLambdaField(const FieldDecl *Field);
3570 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3571 /// if the Field is a reference, this will return the address of the reference
3572 /// and not the address of the value stored in the reference.
3573 LValue EmitLValueForFieldInitialization(LValue Base,
3574 const FieldDecl* Field);
3576 LValue EmitLValueForIvar(QualType ObjectTy,
3577 llvm::Value* Base, const ObjCIvarDecl *Ivar,
3578 unsigned CVRQualifiers);
3580 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3581 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3582 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3583 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3585 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3586 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3587 LValue EmitStmtExprLValue(const StmtExpr *E);
3588 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3589 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3590 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3592 //===--------------------------------------------------------------------===//
3593 // Scalar Expression Emission
3594 //===--------------------------------------------------------------------===//
3596 /// EmitCall - Generate a call of the given function, expecting the given
3597 /// result type, and using the given argument list which specifies both the
3598 /// LLVM arguments and the types they were derived from.
3599 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3600 ReturnValueSlot ReturnValue, const CallArgList &Args,
3601 llvm::CallBase **callOrInvoke, SourceLocation Loc);
3602 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3603 ReturnValueSlot ReturnValue, const CallArgList &Args,
3604 llvm::CallBase **callOrInvoke = nullptr) {
3605 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke,
3608 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3609 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr);
3610 RValue EmitCallExpr(const CallExpr *E,
3611 ReturnValueSlot ReturnValue = ReturnValueSlot());
3612 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3613 CGCallee EmitCallee(const Expr *E);
3615 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3616 void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl);
3618 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
3619 const Twine &name = "");
3620 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee,
3621 ArrayRef<llvm::Value *> args,
3622 const Twine &name = "");
3623 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
3624 const Twine &name = "");
3625 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
3626 ArrayRef<llvm::Value *> args,
3627 const Twine &name = "");
3629 SmallVector<llvm::OperandBundleDef, 1>
3630 getBundlesForFunclet(llvm::Value *Callee);
3632 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee,
3633 ArrayRef<llvm::Value *> Args,
3634 const Twine &Name = "");
3635 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3636 ArrayRef<llvm::Value *> args,
3637 const Twine &name = "");
3638 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3639 const Twine &name = "");
3640 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,
3641 ArrayRef<llvm::Value *> args);
3643 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3644 NestedNameSpecifier *Qual,
3647 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3649 const CXXRecordDecl *RD);
3651 // Return the copy constructor name with the prefix "__copy_constructor_"
3653 static std::string getNonTrivialCopyConstructorStr(QualType QT,
3654 CharUnits Alignment,
3658 // Return the destructor name with the prefix "__destructor_" removed.
3659 static std::string getNonTrivialDestructorStr(QualType QT,
3660 CharUnits Alignment,
3664 // These functions emit calls to the special functions of non-trivial C
3666 void defaultInitNonTrivialCStructVar(LValue Dst);
3667 void callCStructDefaultConstructor(LValue Dst);
3668 void callCStructDestructor(LValue Dst);
3669 void callCStructCopyConstructor(LValue Dst, LValue Src);
3670 void callCStructMoveConstructor(LValue Dst, LValue Src);
3671 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src);
3672 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src);
3675 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3676 const CGCallee &Callee,
3677 ReturnValueSlot ReturnValue, llvm::Value *This,
3678 llvm::Value *ImplicitParam,
3679 QualType ImplicitParamTy, const CallExpr *E,
3680 CallArgList *RtlArgs);
3681 RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee,
3682 llvm::Value *This, QualType ThisTy,
3683 llvm::Value *ImplicitParam,
3684 QualType ImplicitParamTy, const CallExpr *E);
3685 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3686 ReturnValueSlot ReturnValue);
3687 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3688 const CXXMethodDecl *MD,
3689 ReturnValueSlot ReturnValue,
3691 NestedNameSpecifier *Qualifier,
3692 bool IsArrow, const Expr *Base);
3693 // Compute the object pointer.
3694 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3695 llvm::Value *memberPtr,
3696 const MemberPointerType *memberPtrType,
3697 LValueBaseInfo *BaseInfo = nullptr,
3698 TBAAAccessInfo *TBAAInfo = nullptr);
3699 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3700 ReturnValueSlot ReturnValue);
3702 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3703 const CXXMethodDecl *MD,
3704 ReturnValueSlot ReturnValue);
3705 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3707 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3708 ReturnValueSlot ReturnValue);
3710 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3711 ReturnValueSlot ReturnValue);
3713 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
3714 const CallExpr *E, ReturnValueSlot ReturnValue);
3716 RValue emitRotate(const CallExpr *E, bool IsRotateRight);
3718 /// Emit IR for __builtin_os_log_format.
3719 RValue emitBuiltinOSLogFormat(const CallExpr &E);
3721 llvm::Function *generateBuiltinOSLogHelperFunction(
3722 const analyze_os_log::OSLogBufferLayout &Layout,
3723 CharUnits BufferAlignment);
3725 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3727 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3728 /// is unhandled by the current target.
3729 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3731 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3732 const llvm::CmpInst::Predicate Fp,
3733 const llvm::CmpInst::Predicate Ip,
3734 const llvm::Twine &Name = "");
3735 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E,
3736 llvm::Triple::ArchType Arch);
3738 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3739 unsigned LLVMIntrinsic,
3740 unsigned AltLLVMIntrinsic,
3741 const char *NameHint,
3744 SmallVectorImpl<llvm::Value *> &Ops,
3745 Address PtrOp0, Address PtrOp1,
3746 llvm::Triple::ArchType Arch);
3748 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3749 unsigned Modifier, llvm::Type *ArgTy,
3751 llvm::Value *EmitNeonCall(llvm::Function *F,
3752 SmallVectorImpl<llvm::Value*> &O,
3754 unsigned shift = 0, bool rightshift = false);
3755 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3756 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3757 bool negateForRightShift);
3758 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3759 llvm::Type *Ty, bool usgn, const char *name);
3760 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3761 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E,
3762 llvm::Triple::ArchType Arch);
3764 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3765 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3766 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3767 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3768 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3769 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3770 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3772 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3775 enum class MSVCIntrin;
3778 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3780 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3782 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3783 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3784 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3785 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3786 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3787 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3788 const ObjCMethodDecl *MethodWithObjects);
3789 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3790 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3791 ReturnValueSlot Return = ReturnValueSlot());
3793 /// Retrieves the default cleanup kind for an ARC cleanup.
3794 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3795 CleanupKind getARCCleanupKind() {
3796 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3797 ? NormalAndEHCleanup : NormalCleanup;
3801 void EmitARCInitWeak(Address addr, llvm::Value *value);
3802 void EmitARCDestroyWeak(Address addr);
3803 llvm::Value *EmitARCLoadWeak(Address addr);
3804 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3805 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3806 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
3807 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr);
3808 void EmitARCCopyWeak(Address dst, Address src);
3809 void EmitARCMoveWeak(Address dst, Address src);
3810 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3811 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3812 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3813 bool resultIgnored);
3814 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3815 bool resultIgnored);
3816 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3817 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3818 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3819 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3820 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3821 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3822 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3823 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3824 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3825 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3827 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType);
3828 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value,
3829 llvm::Type *returnType);
3830 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3832 std::pair<LValue,llvm::Value*>
3833 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3834 std::pair<LValue,llvm::Value*>
3835 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3836 std::pair<LValue,llvm::Value*>
3837 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3839 llvm::Value *EmitObjCAlloc(llvm::Value *value,
3840 llvm::Type *returnType);
3841 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value,
3842 llvm::Type *returnType);
3843 llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType);
3845 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3846 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3847 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3849 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3850 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3851 bool allowUnsafeClaim);
3852 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3853 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3854 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3856 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3858 static Destroyer destroyARCStrongImprecise;
3859 static Destroyer destroyARCStrongPrecise;
3860 static Destroyer destroyARCWeak;
3861 static Destroyer emitARCIntrinsicUse;
3862 static Destroyer destroyNonTrivialCStruct;
3864 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3865 llvm::Value *EmitObjCAutoreleasePoolPush();
3866 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3867 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3868 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3870 /// Emits a reference binding to the passed in expression.
3871 RValue EmitReferenceBindingToExpr(const Expr *E);
3873 //===--------------------------------------------------------------------===//
3874 // Expression Emission
3875 //===--------------------------------------------------------------------===//
3877 // Expressions are broken into three classes: scalar, complex, aggregate.
3879 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3880 /// scalar type, returning the result.
3881 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3883 /// Emit a conversion from the specified type to the specified destination
3884 /// type, both of which are LLVM scalar types.
3885 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3886 QualType DstTy, SourceLocation Loc);
3888 /// Emit a conversion from the specified complex type to the specified
3889 /// destination type, where the destination type is an LLVM scalar type.
3890 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3892 SourceLocation Loc);
3894 /// EmitAggExpr - Emit the computation of the specified expression
3895 /// of aggregate type. The result is computed into the given slot,
3896 /// which may be null to indicate that the value is not needed.
3897 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3899 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3900 /// aggregate type into a temporary LValue.
3901 LValue EmitAggExprToLValue(const Expr *E);
3903 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3904 /// make sure it survives garbage collection until this point.
3905 void EmitExtendGCLifetime(llvm::Value *object);
3907 /// EmitComplexExpr - Emit the computation of the specified expression of
3908 /// complex type, returning the result.
3909 ComplexPairTy EmitComplexExpr(const Expr *E,
3910 bool IgnoreReal = false,
3911 bool IgnoreImag = false);
3913 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3914 /// type and place its result into the specified l-value.
3915 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3917 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3918 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3920 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3921 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3923 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3924 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3926 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3927 /// global variable that has already been created for it. If the initializer
3928 /// has a different type than GV does, this may free GV and return a different
3929 /// one. Otherwise it just returns GV.
3930 llvm::GlobalVariable *
3931 AddInitializerToStaticVarDecl(const VarDecl &D,
3932 llvm::GlobalVariable *GV);
3934 // Emit an @llvm.invariant.start call for the given memory region.
3935 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size);
3937 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3938 /// variable with global storage.
3939 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3942 llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor,
3943 llvm::Constant *Addr);
3945 /// Call atexit() with a function that passes the given argument to
3946 /// the given function.
3947 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn,
3948 llvm::Constant *addr);
3950 /// Call atexit() with function dtorStub.
3951 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub);
3953 /// Emit code in this function to perform a guarded variable
3954 /// initialization. Guarded initializations are used when it's not
3955 /// possible to prove that an initialization will be done exactly
3956 /// once, e.g. with a static local variable or a static data member
3957 /// of a class template.
3958 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3961 enum class GuardKind { VariableGuard, TlsGuard };
3963 /// Emit a branch to select whether or not to perform guarded initialization.
3964 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
3965 llvm::BasicBlock *InitBlock,
3966 llvm::BasicBlock *NoInitBlock,
3967 GuardKind Kind, const VarDecl *D);
3969 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3972 GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3973 ArrayRef<llvm::Function *> CXXThreadLocals,
3974 ConstantAddress Guard = ConstantAddress::invalid());
3976 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3978 void GenerateCXXGlobalDtorsFunc(
3980 const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
3981 llvm::Constant *>> &DtorsAndObjects);
3983 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3985 llvm::GlobalVariable *Addr,
3988 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3990 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3992 void enterFullExpression(const FullExpr *E) {
3993 if (const auto *EWC = dyn_cast<ExprWithCleanups>(E))
3994 if (EWC->getNumObjects() == 0)
3996 enterNonTrivialFullExpression(E);
3998 void enterNonTrivialFullExpression(const FullExpr *E);
4000 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
4002 RValue EmitAtomicExpr(AtomicExpr *E);
4004 //===--------------------------------------------------------------------===//
4005 // Annotations Emission
4006 //===--------------------------------------------------------------------===//
4008 /// Emit an annotation call (intrinsic).
4009 llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn,
4010 llvm::Value *AnnotatedVal,
4011 StringRef AnnotationStr,
4012 SourceLocation Location);
4014 /// Emit local annotations for the local variable V, declared by D.
4015 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
4017 /// Emit field annotations for the given field & value. Returns the
4018 /// annotation result.
4019 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
4021 //===--------------------------------------------------------------------===//
4023 //===--------------------------------------------------------------------===//
4025 /// ContainsLabel - Return true if the statement contains a label in it. If
4026 /// this statement is not executed normally, it not containing a label means
4027 /// that we can just remove the code.
4028 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
4030 /// containsBreak - Return true if the statement contains a break out of it.
4031 /// If the statement (recursively) contains a switch or loop with a break
4032 /// inside of it, this is fine.
4033 static bool containsBreak(const Stmt *S);
4035 /// Determine if the given statement might introduce a declaration into the
4036 /// current scope, by being a (possibly-labelled) DeclStmt.
4037 static bool mightAddDeclToScope(const Stmt *S);
4039 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4040 /// to a constant, or if it does but contains a label, return false. If it
4041 /// constant folds return true and set the boolean result in Result.
4042 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
4043 bool AllowLabels = false);
4045 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
4046 /// to a constant, or if it does but contains a label, return false. If it
4047 /// constant folds return true and set the folded value.
4048 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
4049 bool AllowLabels = false);
4051 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
4052 /// if statement) to the specified blocks. Based on the condition, this might
4053 /// try to simplify the codegen of the conditional based on the branch.
4054 /// TrueCount should be the number of times we expect the condition to
4055 /// evaluate to true based on PGO data.
4056 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
4057 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
4059 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
4060 /// nonnull, if \p LHS is marked _Nonnull.
4061 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
4063 /// An enumeration which makes it easier to specify whether or not an
4064 /// operation is a subtraction.
4065 enum { NotSubtraction = false, IsSubtraction = true };
4067 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to
4068 /// detect undefined behavior when the pointer overflow sanitizer is enabled.
4069 /// \p SignedIndices indicates whether any of the GEP indices are signed.
4070 /// \p IsSubtraction indicates whether the expression used to form the GEP
4071 /// is a subtraction.
4072 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr,
4073 ArrayRef<llvm::Value *> IdxList,
4077 const Twine &Name = "");
4079 /// Specifies which type of sanitizer check to apply when handling a
4080 /// particular builtin.
4081 enum BuiltinCheckKind {
4086 /// Emits an argument for a call to a builtin. If the builtin sanitizer is
4087 /// enabled, a runtime check specified by \p Kind is also emitted.
4088 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind);
4090 /// Emit a description of a type in a format suitable for passing to
4091 /// a runtime sanitizer handler.
4092 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
4094 /// Convert a value into a format suitable for passing to a runtime
4095 /// sanitizer handler.
4096 llvm::Value *EmitCheckValue(llvm::Value *V);
4098 /// Emit a description of a source location in a format suitable for
4099 /// passing to a runtime sanitizer handler.
4100 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
4102 /// Create a basic block that will either trap or call a handler function in
4103 /// the UBSan runtime with the provided arguments, and create a conditional
4105 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
4106 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
4107 ArrayRef<llvm::Value *> DynamicArgs);
4109 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
4110 /// if Cond if false.
4111 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
4112 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4113 ArrayRef<llvm::Constant *> StaticArgs);
4115 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime
4116 /// checking is enabled. Otherwise, just emit an unreachable instruction.
4117 void EmitUnreachable(SourceLocation Loc);
4119 /// Create a basic block that will call the trap intrinsic, and emit a
4120 /// conditional branch to it, for the -ftrapv checks.
4121 void EmitTrapCheck(llvm::Value *Checked);
4123 /// Emit a call to trap or debugtrap and attach function attribute
4124 /// "trap-func-name" if specified.
4125 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
4127 /// Emit a stub for the cross-DSO CFI check function.
4128 void EmitCfiCheckStub();
4130 /// Emit a cross-DSO CFI failure handling function.
4131 void EmitCfiCheckFail();
4133 /// Create a check for a function parameter that may potentially be
4134 /// declared as non-null.
4135 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
4136 AbstractCallee AC, unsigned ParmNum);
4138 /// EmitCallArg - Emit a single call argument.
4139 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
4141 /// EmitDelegateCallArg - We are performing a delegate call; that
4142 /// is, the current function is delegating to another one. Produce
4143 /// a r-value suitable for passing the given parameter.
4144 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
4145 SourceLocation loc);
4147 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
4148 /// point operation, expressed as the maximum relative error in ulp.
4149 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
4152 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
4153 void EmitReturnOfRValue(RValue RV, QualType Ty);
4155 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
4157 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
4158 DeferredReplacements;
4160 /// Set the address of a local variable.
4161 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
4162 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
4163 LocalDeclMap.insert({VD, Addr});
4166 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
4167 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
4169 /// \param AI - The first function argument of the expansion.
4170 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
4171 SmallVectorImpl<llvm::Value *>::iterator &AI);
4173 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg
4174 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
4175 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
4176 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
4177 SmallVectorImpl<llvm::Value *> &IRCallArgs,
4178 unsigned &IRCallArgPos);
4180 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
4181 const Expr *InputExpr, std::string &ConstraintStr);
4183 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
4184 LValue InputValue, QualType InputType,
4185 std::string &ConstraintStr,
4186 SourceLocation Loc);
4188 /// Attempts to statically evaluate the object size of E. If that
4189 /// fails, emits code to figure the size of E out for us. This is
4190 /// pass_object_size aware.
4192 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
4193 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
4194 llvm::IntegerType *ResType,
4195 llvm::Value *EmittedE,
4198 /// Emits the size of E, as required by __builtin_object_size. This
4199 /// function is aware of pass_object_size parameters, and will act accordingly
4200 /// if E is a parameter with the pass_object_size attribute.
4201 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
4202 llvm::IntegerType *ResType,
4203 llvm::Value *EmittedE,
4206 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D,
4211 // Determine whether the given argument is an Objective-C method
4212 // that may have type parameters in its signature.
4213 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4214 const DeclContext *dc = method->getDeclContext();
4215 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
4216 return classDecl->getTypeParamListAsWritten();
4219 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4220 return catDecl->getTypeParamList();
4226 template<typename T>
4227 static bool isObjCMethodWithTypeParams(const T *) { return false; }
4230 enum class EvaluationOrder {
4231 ///! No language constraints on evaluation order.
4233 ///! Language semantics require left-to-right evaluation.
4235 ///! Language semantics require right-to-left evaluation.
4239 /// EmitCallArgs - Emit call arguments for a function.
4240 template <typename T>
4241 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
4242 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4243 AbstractCallee AC = AbstractCallee(),
4244 unsigned ParamsToSkip = 0,
4245 EvaluationOrder Order = EvaluationOrder::Default) {
4246 SmallVector<QualType, 16> ArgTypes;
4247 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4249 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
4250 "Can't skip parameters if type info is not provided");
4251 if (CallArgTypeInfo) {
4253 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
4256 // First, use the argument types that the type info knows about
4257 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
4258 E = CallArgTypeInfo->param_type_end();
4259 I != E; ++I, ++Arg) {
4260 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4261 assert((isGenericMethod ||
4262 ((*I)->isVariablyModifiedType() ||
4263 (*I).getNonReferenceType()->isObjCRetainableType() ||
4265 .getCanonicalType((*I).getNonReferenceType())
4268 .getCanonicalType((*Arg)->getType())
4270 "type mismatch in call argument!");
4271 ArgTypes.push_back(*I);
4275 // Either we've emitted all the call args, or we have a call to variadic
4277 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
4278 CallArgTypeInfo->isVariadic()) &&
4279 "Extra arguments in non-variadic function!");
4281 // If we still have any arguments, emit them using the type of the argument.
4282 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
4283 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
4285 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
4288 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
4289 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4290 AbstractCallee AC = AbstractCallee(),
4291 unsigned ParamsToSkip = 0,
4292 EvaluationOrder Order = EvaluationOrder::Default);
4294 /// EmitPointerWithAlignment - Given an expression with a pointer type,
4295 /// emit the value and compute our best estimate of the alignment of the
4298 /// \param BaseInfo - If non-null, this will be initialized with
4299 /// information about the source of the alignment and the may-alias
4300 /// attribute. Note that this function will conservatively fall back on
4301 /// the type when it doesn't recognize the expression and may-alias will
4302 /// be set to false.
4304 /// One reasonable way to use this information is when there's a language
4305 /// guarantee that the pointer must be aligned to some stricter value, and
4306 /// we're simply trying to ensure that sufficiently obvious uses of under-
4307 /// aligned objects don't get miscompiled; for example, a placement new
4308 /// into the address of a local variable. In such a case, it's quite
4309 /// reasonable to just ignore the returned alignment when it isn't from an
4310 /// explicit source.
4311 Address EmitPointerWithAlignment(const Expr *Addr,
4312 LValueBaseInfo *BaseInfo = nullptr,
4313 TBAAAccessInfo *TBAAInfo = nullptr);
4315 /// If \p E references a parameter with pass_object_size info or a constant
4316 /// array size modifier, emit the object size divided by the size of \p EltTy.
4317 /// Otherwise return null.
4318 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy);
4320 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
4322 struct MultiVersionResolverOption {
4323 llvm::Function *Function;
4326 StringRef Architecture;
4327 llvm::SmallVector<StringRef, 8> Features;
4329 Conds(StringRef Arch, ArrayRef<StringRef> Feats)
4330 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {}
4333 MultiVersionResolverOption(llvm::Function *F, StringRef Arch,
4334 ArrayRef<StringRef> Feats)
4335 : Function(F), Conditions(Arch, Feats) {}
4338 // Emits the body of a multiversion function's resolver. Assumes that the
4339 // options are already sorted in the proper order, with the 'default' option
4340 // last (if it exists).
4341 void EmitMultiVersionResolver(llvm::Function *Resolver,
4342 ArrayRef<MultiVersionResolverOption> Options);
4344 static uint64_t GetX86CpuSupportsMask(ArrayRef<StringRef> FeatureStrs);
4347 QualType getVarArgType(const Expr *Arg);
4349 void EmitDeclMetadata();
4351 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
4352 const AutoVarEmission &emission);
4354 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
4356 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
4357 llvm::Value *EmitX86CpuIs(const CallExpr *E);
4358 llvm::Value *EmitX86CpuIs(StringRef CPUStr);
4359 llvm::Value *EmitX86CpuSupports(const CallExpr *E);
4360 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs);
4361 llvm::Value *EmitX86CpuSupports(uint64_t Mask);
4362 llvm::Value *EmitX86CpuInit();
4363 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO);
4366 inline DominatingLLVMValue::saved_type
4367 DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) {
4368 if (!needsSaving(value)) return saved_type(value, false);
4370 // Otherwise, we need an alloca.
4371 auto align = CharUnits::fromQuantity(
4372 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
4374 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
4375 CGF.Builder.CreateStore(value, alloca);
4377 return saved_type(alloca.getPointer(), true);
4380 inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF,
4382 // If the value says it wasn't saved, trust that it's still dominating.
4383 if (!value.getInt()) return value.getPointer();
4385 // Otherwise, it should be an alloca instruction, as set up in save().
4386 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
4387 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
4390 } // end namespace CodeGen
4391 } // end namespace clang