1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the internal per-function state used for llvm translation.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
15 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
17 #include "CGBuilder.h"
18 #include "CGDebugInfo.h"
19 #include "CGLoopInfo.h"
21 #include "CodeGenModule.h"
22 #include "CodeGenPGO.h"
23 #include "EHScopeStack.h"
24 #include "VarBypassDetector.h"
25 #include "clang/AST/CharUnits.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/OpenMPKinds.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Frontend/CodeGenOptions.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/IR/ValueHandle.h"
39 #include "llvm/Support/Debug.h"
40 #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;
86 class BlockByrefHelpers;
89 class BlockFieldFlags;
90 class RegionCodeGenTy;
91 class TargetCodeGenInfo;
95 /// The kind of evaluation to perform on values of a particular
96 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
99 /// TODO: should vectors maybe be split out into their own thing?
100 enum TypeEvaluationKind {
106 #define LIST_SANITIZER_CHECKS \
107 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \
108 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \
109 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \
110 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \
111 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \
112 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \
113 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 0) \
114 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \
115 SANITIZER_CHECK(MissingReturn, missing_return, 0) \
116 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \
117 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \
118 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \
119 SANITIZER_CHECK(NullabilityReturn, nullability_return, 0) \
120 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \
121 SANITIZER_CHECK(NonnullReturn, nonnull_return, 0) \
122 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
123 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
124 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
125 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
126 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
128 enum SanitizerHandler {
129 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
130 LIST_SANITIZER_CHECKS
131 #undef SANITIZER_CHECK
134 /// CodeGenFunction - This class organizes the per-function state that is used
135 /// while generating LLVM code.
136 class CodeGenFunction : public CodeGenTypeCache {
137 CodeGenFunction(const CodeGenFunction &) = delete;
138 void operator=(const CodeGenFunction &) = delete;
140 friend class CGCXXABI;
142 /// A jump destination is an abstract label, branching to which may
143 /// require a jump out through normal cleanups.
145 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
146 JumpDest(llvm::BasicBlock *Block,
147 EHScopeStack::stable_iterator Depth,
149 : Block(Block), ScopeDepth(Depth), Index(Index) {}
151 bool isValid() const { return Block != nullptr; }
152 llvm::BasicBlock *getBlock() const { return Block; }
153 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
154 unsigned getDestIndex() const { return Index; }
156 // This should be used cautiously.
157 void setScopeDepth(EHScopeStack::stable_iterator depth) {
162 llvm::BasicBlock *Block;
163 EHScopeStack::stable_iterator ScopeDepth;
167 CodeGenModule &CGM; // Per-module state.
168 const TargetInfo &Target;
170 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
171 LoopInfoStack LoopStack;
174 // Stores variables for which we can't generate correct lifetime markers
176 VarBypassDetector Bypasses;
178 // CodeGen lambda for loops and support for ordered clause
179 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &,
182 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation,
183 const unsigned, const bool)>
186 // Codegen lambda for loop bounds in worksharing loop constructs
187 typedef llvm::function_ref<std::pair<LValue, LValue>(
188 CodeGenFunction &, const OMPExecutableDirective &S)>
191 // Codegen lambda for loop bounds in dispatch-based loop implementation
192 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>(
193 CodeGenFunction &, const OMPExecutableDirective &S, Address LB,
195 CodeGenDispatchBoundsTy;
197 /// \brief CGBuilder insert helper. This function is called after an
198 /// instruction is created using Builder.
199 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
200 llvm::BasicBlock *BB,
201 llvm::BasicBlock::iterator InsertPt) const;
203 /// CurFuncDecl - Holds the Decl for the current outermost
204 /// non-closure context.
205 const Decl *CurFuncDecl;
206 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
207 const Decl *CurCodeDecl;
208 const CGFunctionInfo *CurFnInfo;
210 llvm::Function *CurFn;
212 // Holds coroutine data if the current function is a coroutine. We use a
213 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
216 std::unique_ptr<CGCoroData> Data;
222 /// CurGD - The GlobalDecl for the current function being compiled.
225 /// PrologueCleanupDepth - The cleanup depth enclosing all the
226 /// cleanups associated with the parameters.
227 EHScopeStack::stable_iterator PrologueCleanupDepth;
229 /// ReturnBlock - Unified return block.
230 JumpDest ReturnBlock;
232 /// ReturnValue - The temporary alloca to hold the return
233 /// value. This is invalid iff the function has no return value.
236 /// Return true if a label was seen in the current scope.
237 bool hasLabelBeenSeenInCurrentScope() const {
239 return CurLexicalScope->hasLabels();
240 return !LabelMap.empty();
243 /// AllocaInsertPoint - This is an instruction in the entry block before which
244 /// we prefer to insert allocas.
245 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
247 /// \brief API for captured statement code generation.
248 class CGCapturedStmtInfo {
250 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
251 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
252 explicit CGCapturedStmtInfo(const CapturedStmt &S,
253 CapturedRegionKind K = CR_Default)
254 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
256 RecordDecl::field_iterator Field =
257 S.getCapturedRecordDecl()->field_begin();
258 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
260 I != E; ++I, ++Field) {
261 if (I->capturesThis())
262 CXXThisFieldDecl = *Field;
263 else if (I->capturesVariable())
264 CaptureFields[I->getCapturedVar()] = *Field;
265 else if (I->capturesVariableByCopy())
266 CaptureFields[I->getCapturedVar()] = *Field;
270 virtual ~CGCapturedStmtInfo();
272 CapturedRegionKind getKind() const { return Kind; }
274 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
275 // \brief Retrieve the value of the context parameter.
276 virtual llvm::Value *getContextValue() const { return ThisValue; }
278 /// \brief Lookup the captured field decl for a variable.
279 virtual const FieldDecl *lookup(const VarDecl *VD) const {
280 return CaptureFields.lookup(VD);
283 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
284 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
286 static bool classof(const CGCapturedStmtInfo *) {
290 /// \brief Emit the captured statement body.
291 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
292 CGF.incrementProfileCounter(S);
296 /// \brief Get the name of the capture helper.
297 virtual StringRef getHelperName() const { return "__captured_stmt"; }
300 /// \brief The kind of captured statement being generated.
301 CapturedRegionKind Kind;
303 /// \brief Keep the map between VarDecl and FieldDecl.
304 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
306 /// \brief The base address of the captured record, passed in as the first
307 /// argument of the parallel region function.
308 llvm::Value *ThisValue;
310 /// \brief Captured 'this' type.
311 FieldDecl *CXXThisFieldDecl;
313 CGCapturedStmtInfo *CapturedStmtInfo;
315 /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
316 class CGCapturedStmtRAII {
318 CodeGenFunction &CGF;
319 CGCapturedStmtInfo *PrevCapturedStmtInfo;
321 CGCapturedStmtRAII(CodeGenFunction &CGF,
322 CGCapturedStmtInfo *NewCapturedStmtInfo)
323 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
324 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
326 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
329 /// An abstract representation of regular/ObjC call/message targets.
330 class AbstractCallee {
331 /// The function declaration of the callee.
332 const Decl *CalleeDecl;
335 AbstractCallee() : CalleeDecl(nullptr) {}
336 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {}
337 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {}
338 bool hasFunctionDecl() const {
339 return dyn_cast_or_null<FunctionDecl>(CalleeDecl);
341 const Decl *getDecl() const { return CalleeDecl; }
342 unsigned getNumParams() const {
343 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
344 return FD->getNumParams();
345 return cast<ObjCMethodDecl>(CalleeDecl)->param_size();
347 const ParmVarDecl *getParamDecl(unsigned I) const {
348 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl))
349 return FD->getParamDecl(I);
350 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I);
354 /// \brief Sanitizers enabled for this function.
355 SanitizerSet SanOpts;
357 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
358 bool IsSanitizerScope;
360 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
361 class SanitizerScope {
362 CodeGenFunction *CGF;
364 SanitizerScope(CodeGenFunction *CGF);
368 /// In C++, whether we are code generating a thunk. This controls whether we
369 /// should emit cleanups.
372 /// In ARC, whether we should autorelease the return value.
373 bool AutoreleaseResult;
375 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
376 /// potentially set the return value.
379 const FunctionDecl *CurSEHParent = nullptr;
381 /// True if the current function is an outlined SEH helper. This can be a
382 /// finally block or filter expression.
383 bool IsOutlinedSEHHelper;
385 const CodeGen::CGBlockInfo *BlockInfo;
386 llvm::Value *BlockPointer;
388 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
389 FieldDecl *LambdaThisCaptureField;
391 /// \brief A mapping from NRVO variables to the flags used to indicate
392 /// when the NRVO has been applied to this variable.
393 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
395 EHScopeStack EHStack;
396 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
397 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
399 llvm::Instruction *CurrentFuncletPad = nullptr;
401 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
406 CallLifetimeEnd(Address addr, llvm::Value *size)
407 : Addr(addr.getPointer()), Size(size) {}
409 void Emit(CodeGenFunction &CGF, Flags flags) override {
410 CGF.EmitLifetimeEnd(Size, Addr);
414 /// Header for data within LifetimeExtendedCleanupStack.
415 struct LifetimeExtendedCleanupHeader {
416 /// The size of the following cleanup object.
418 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
421 size_t getSize() const { return Size; }
422 CleanupKind getKind() const { return Kind; }
425 /// i32s containing the indexes of the cleanup destinations.
426 llvm::AllocaInst *NormalCleanupDest;
428 unsigned NextCleanupDestIndex;
430 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
431 CGBlockInfo *FirstBlockInfo;
433 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
434 llvm::BasicBlock *EHResumeBlock;
436 /// The exception slot. All landing pads write the current exception pointer
437 /// into this alloca.
438 llvm::Value *ExceptionSlot;
440 /// The selector slot. Under the MandatoryCleanup model, all landing pads
441 /// write the current selector value into this alloca.
442 llvm::AllocaInst *EHSelectorSlot;
444 /// A stack of exception code slots. Entering an __except block pushes a slot
445 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
446 /// a value from the top of the stack.
447 SmallVector<Address, 1> SEHCodeSlotStack;
449 /// Value returned by __exception_info intrinsic.
450 llvm::Value *SEHInfo = nullptr;
452 /// Emits a landing pad for the current EH stack.
453 llvm::BasicBlock *EmitLandingPad();
455 llvm::BasicBlock *getInvokeDestImpl();
458 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
459 return DominatingValue<T>::save(*this, value);
463 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
465 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
467 /// A class controlling the emission of a finally block.
469 /// Where the catchall's edge through the cleanup should go.
470 JumpDest RethrowDest;
472 /// A function to call to enter the catch.
473 llvm::Constant *BeginCatchFn;
475 /// An i1 variable indicating whether or not the @finally is
476 /// running for an exception.
477 llvm::AllocaInst *ForEHVar;
479 /// An i8* variable into which the exception pointer to rethrow
481 llvm::AllocaInst *SavedExnVar;
484 void enter(CodeGenFunction &CGF, const Stmt *Finally,
485 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
486 llvm::Constant *rethrowFn);
487 void exit(CodeGenFunction &CGF);
490 /// Returns true inside SEH __try blocks.
491 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
493 /// Returns true while emitting a cleanuppad.
494 bool isCleanupPadScope() const {
495 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
498 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
499 /// current full-expression. Safe against the possibility that
500 /// we're currently inside a conditionally-evaluated expression.
501 template <class T, class... As>
502 void pushFullExprCleanup(CleanupKind kind, As... A) {
503 // If we're not in a conditional branch, or if none of the
504 // arguments requires saving, then use the unconditional cleanup.
505 if (!isInConditionalBranch())
506 return EHStack.pushCleanup<T>(kind, A...);
508 // Stash values in a tuple so we can guarantee the order of saves.
509 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
510 SavedTuple Saved{saveValueInCond(A)...};
512 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
513 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
514 initFullExprCleanup();
517 /// \brief Queue a cleanup to be pushed after finishing the current
519 template <class T, class... As>
520 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
521 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
523 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
525 size_t OldSize = LifetimeExtendedCleanupStack.size();
526 LifetimeExtendedCleanupStack.resize(
527 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
529 static_assert(sizeof(Header) % alignof(T) == 0,
530 "Cleanup will be allocated on misaligned address");
531 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
532 new (Buffer) LifetimeExtendedCleanupHeader(Header);
533 new (Buffer + sizeof(Header)) T(A...);
536 /// Set up the last cleaup that was pushed as a conditional
537 /// full-expression cleanup.
538 void initFullExprCleanup();
540 /// PushDestructorCleanup - Push a cleanup to call the
541 /// complete-object destructor of an object of the given type at the
542 /// given address. Does nothing if T is not a C++ class type with a
543 /// non-trivial destructor.
544 void PushDestructorCleanup(QualType T, Address Addr);
546 /// PushDestructorCleanup - Push a cleanup to call the
547 /// complete-object variant of the given destructor on the object at
548 /// the given address.
549 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
551 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
552 /// process all branch fixups.
553 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
555 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
556 /// The block cannot be reactivated. Pops it if it's the top of the
559 /// \param DominatingIP - An instruction which is known to
560 /// dominate the current IP (if set) and which lies along
561 /// all paths of execution between the current IP and the
562 /// the point at which the cleanup comes into scope.
563 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
564 llvm::Instruction *DominatingIP);
566 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
567 /// Cannot be used to resurrect a deactivated cleanup.
569 /// \param DominatingIP - An instruction which is known to
570 /// dominate the current IP (if set) and which lies along
571 /// all paths of execution between the current IP and the
572 /// the point at which the cleanup comes into scope.
573 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
574 llvm::Instruction *DominatingIP);
576 /// \brief Enters a new scope for capturing cleanups, all of which
577 /// will be executed once the scope is exited.
578 class RunCleanupsScope {
579 EHScopeStack::stable_iterator CleanupStackDepth;
580 size_t LifetimeExtendedCleanupStackSize;
581 bool OldDidCallStackSave;
586 RunCleanupsScope(const RunCleanupsScope &) = delete;
587 void operator=(const RunCleanupsScope &) = delete;
590 CodeGenFunction& CGF;
593 /// \brief Enter a new cleanup scope.
594 explicit RunCleanupsScope(CodeGenFunction &CGF)
595 : PerformCleanup(true), CGF(CGF)
597 CleanupStackDepth = CGF.EHStack.stable_begin();
598 LifetimeExtendedCleanupStackSize =
599 CGF.LifetimeExtendedCleanupStack.size();
600 OldDidCallStackSave = CGF.DidCallStackSave;
601 CGF.DidCallStackSave = false;
604 /// \brief Exit this cleanup scope, emitting any accumulated cleanups.
605 ~RunCleanupsScope() {
610 /// \brief Determine whether this scope requires any cleanups.
611 bool requiresCleanups() const {
612 return CGF.EHStack.stable_begin() != CleanupStackDepth;
615 /// \brief Force the emission of cleanups now, instead of waiting
616 /// until this object is destroyed.
617 /// \param ValuesToReload - A list of values that need to be available at
618 /// the insertion point after cleanup emission. If cleanup emission created
619 /// a shared cleanup block, these value pointers will be rewritten.
620 /// Otherwise, they not will be modified.
621 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) {
622 assert(PerformCleanup && "Already forced cleanup");
623 CGF.DidCallStackSave = OldDidCallStackSave;
624 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize,
626 PerformCleanup = false;
630 class LexicalScope : public RunCleanupsScope {
632 SmallVector<const LabelDecl*, 4> Labels;
633 LexicalScope *ParentScope;
635 LexicalScope(const LexicalScope &) = delete;
636 void operator=(const LexicalScope &) = delete;
639 /// \brief Enter a new cleanup scope.
640 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
641 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
642 CGF.CurLexicalScope = this;
643 if (CGDebugInfo *DI = CGF.getDebugInfo())
644 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
647 void addLabel(const LabelDecl *label) {
648 assert(PerformCleanup && "adding label to dead scope?");
649 Labels.push_back(label);
652 /// \brief Exit this cleanup scope, emitting any accumulated
655 if (CGDebugInfo *DI = CGF.getDebugInfo())
656 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
658 // If we should perform a cleanup, force them now. Note that
659 // this ends the cleanup scope before rescoping any labels.
660 if (PerformCleanup) {
661 ApplyDebugLocation DL(CGF, Range.getEnd());
666 /// \brief Force the emission of cleanups now, instead of waiting
667 /// until this object is destroyed.
668 void ForceCleanup() {
669 CGF.CurLexicalScope = ParentScope;
670 RunCleanupsScope::ForceCleanup();
676 bool hasLabels() const {
677 return !Labels.empty();
680 void rescopeLabels();
683 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
685 /// \brief The scope used to remap some variables as private in the OpenMP
686 /// loop body (or other captured region emitted without outlining), and to
687 /// restore old vars back on exit.
688 class OMPPrivateScope : public RunCleanupsScope {
689 DeclMapTy SavedLocals;
690 DeclMapTy SavedPrivates;
693 OMPPrivateScope(const OMPPrivateScope &) = delete;
694 void operator=(const OMPPrivateScope &) = delete;
697 /// \brief Enter a new OpenMP private scope.
698 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
700 /// \brief Registers \a LocalVD variable as a private and apply \a
701 /// PrivateGen function for it to generate corresponding private variable.
702 /// \a PrivateGen returns an address of the generated private variable.
703 /// \return true if the variable is registered as private, false if it has
704 /// been privatized already.
706 addPrivate(const VarDecl *LocalVD,
707 llvm::function_ref<Address()> PrivateGen) {
708 assert(PerformCleanup && "adding private to dead scope");
710 // Only save it once.
711 if (SavedLocals.count(LocalVD)) return false;
713 // Copy the existing local entry to SavedLocals.
714 auto it = CGF.LocalDeclMap.find(LocalVD);
715 if (it != CGF.LocalDeclMap.end()) {
716 SavedLocals.insert({LocalVD, it->second});
718 SavedLocals.insert({LocalVD, Address::invalid()});
721 // Generate the private entry.
722 Address Addr = PrivateGen();
723 QualType VarTy = LocalVD->getType();
724 if (VarTy->isReferenceType()) {
725 Address Temp = CGF.CreateMemTemp(VarTy);
726 CGF.Builder.CreateStore(Addr.getPointer(), Temp);
729 SavedPrivates.insert({LocalVD, Addr});
734 /// \brief Privatizes local variables previously registered as private.
735 /// Registration is separate from the actual privatization to allow
736 /// initializers use values of the original variables, not the private one.
737 /// This is important, for example, if the private variable is a class
738 /// variable initialized by a constructor that references other private
739 /// variables. But at initialization original variables must be used, not
741 /// \return true if at least one variable was privatized, false otherwise.
743 copyInto(SavedPrivates, CGF.LocalDeclMap);
744 SavedPrivates.clear();
745 return !SavedLocals.empty();
748 void ForceCleanup() {
749 RunCleanupsScope::ForceCleanup();
750 copyInto(SavedLocals, CGF.LocalDeclMap);
754 /// \brief Exit scope - all the mapped variables are restored.
760 /// Checks if the global variable is captured in current function.
761 bool isGlobalVarCaptured(const VarDecl *VD) const {
762 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
766 /// Copy all the entries in the source map over the corresponding
767 /// entries in the destination, which must exist.
768 static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
769 for (auto &pair : src) {
770 if (!pair.second.isValid()) {
771 dest.erase(pair.first);
775 auto it = dest.find(pair.first);
776 if (it != dest.end()) {
777 it->second = pair.second;
785 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
786 /// that have been added.
788 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
789 std::initializer_list<llvm::Value **> ValuesToReload = {});
791 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
792 /// that have been added, then adds all lifetime-extended cleanups from
793 /// the given position to the stack.
795 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
796 size_t OldLifetimeExtendedStackSize,
797 std::initializer_list<llvm::Value **> ValuesToReload = {});
799 void ResolveBranchFixups(llvm::BasicBlock *Target);
801 /// The given basic block lies in the current EH scope, but may be a
802 /// target of a potentially scope-crossing jump; get a stable handle
803 /// to which we can perform this jump later.
804 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
805 return JumpDest(Target,
806 EHStack.getInnermostNormalCleanup(),
807 NextCleanupDestIndex++);
810 /// The given basic block lies in the current EH scope, but may be a
811 /// target of a potentially scope-crossing jump; get a stable handle
812 /// to which we can perform this jump later.
813 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
814 return getJumpDestInCurrentScope(createBasicBlock(Name));
817 /// EmitBranchThroughCleanup - Emit a branch from the current insert
818 /// block through the normal cleanup handling code (if any) and then
820 void EmitBranchThroughCleanup(JumpDest Dest);
822 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
823 /// specified destination obviously has no cleanups to run. 'false' is always
824 /// a conservatively correct answer for this method.
825 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
827 /// popCatchScope - Pops the catch scope at the top of the EHScope
828 /// stack, emitting any required code (other than the catch handlers
830 void popCatchScope();
832 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
833 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
834 llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
836 /// An object to manage conditionally-evaluated expressions.
837 class ConditionalEvaluation {
838 llvm::BasicBlock *StartBB;
841 ConditionalEvaluation(CodeGenFunction &CGF)
842 : StartBB(CGF.Builder.GetInsertBlock()) {}
844 void begin(CodeGenFunction &CGF) {
845 assert(CGF.OutermostConditional != this);
846 if (!CGF.OutermostConditional)
847 CGF.OutermostConditional = this;
850 void end(CodeGenFunction &CGF) {
851 assert(CGF.OutermostConditional != nullptr);
852 if (CGF.OutermostConditional == this)
853 CGF.OutermostConditional = nullptr;
856 /// Returns a block which will be executed prior to each
857 /// evaluation of the conditional code.
858 llvm::BasicBlock *getStartingBlock() const {
863 /// isInConditionalBranch - Return true if we're currently emitting
864 /// one branch or the other of a conditional expression.
865 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
867 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
868 assert(isInConditionalBranch());
869 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
870 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
871 store->setAlignment(addr.getAlignment().getQuantity());
874 /// An RAII object to record that we're evaluating a statement
876 class StmtExprEvaluation {
877 CodeGenFunction &CGF;
879 /// We have to save the outermost conditional: cleanups in a
880 /// statement expression aren't conditional just because the
882 ConditionalEvaluation *SavedOutermostConditional;
885 StmtExprEvaluation(CodeGenFunction &CGF)
886 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
887 CGF.OutermostConditional = nullptr;
890 ~StmtExprEvaluation() {
891 CGF.OutermostConditional = SavedOutermostConditional;
892 CGF.EnsureInsertPoint();
896 /// An object which temporarily prevents a value from being
897 /// destroyed by aggressive peephole optimizations that assume that
898 /// all uses of a value have been realized in the IR.
899 class PeepholeProtection {
900 llvm::Instruction *Inst;
901 friend class CodeGenFunction;
904 PeepholeProtection() : Inst(nullptr) {}
907 /// A non-RAII class containing all the information about a bound
908 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
909 /// this which makes individual mappings very simple; using this
910 /// class directly is useful when you have a variable number of
911 /// opaque values or don't want the RAII functionality for some
913 class OpaqueValueMappingData {
914 const OpaqueValueExpr *OpaqueValue;
916 CodeGenFunction::PeepholeProtection Protection;
918 OpaqueValueMappingData(const OpaqueValueExpr *ov,
920 : OpaqueValue(ov), BoundLValue(boundLValue) {}
922 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
924 static bool shouldBindAsLValue(const Expr *expr) {
925 // gl-values should be bound as l-values for obvious reasons.
926 // Records should be bound as l-values because IR generation
927 // always keeps them in memory. Expressions of function type
928 // act exactly like l-values but are formally required to be
930 return expr->isGLValue() ||
931 expr->getType()->isFunctionType() ||
932 hasAggregateEvaluationKind(expr->getType());
935 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
936 const OpaqueValueExpr *ov,
938 if (shouldBindAsLValue(ov))
939 return bind(CGF, ov, CGF.EmitLValue(e));
940 return bind(CGF, ov, CGF.EmitAnyExpr(e));
943 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
944 const OpaqueValueExpr *ov,
946 assert(shouldBindAsLValue(ov));
947 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
948 return OpaqueValueMappingData(ov, true);
951 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
952 const OpaqueValueExpr *ov,
954 assert(!shouldBindAsLValue(ov));
955 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
957 OpaqueValueMappingData data(ov, false);
959 // Work around an extremely aggressive peephole optimization in
960 // EmitScalarConversion which assumes that all other uses of a
962 data.Protection = CGF.protectFromPeepholes(rv);
967 bool isValid() const { return OpaqueValue != nullptr; }
968 void clear() { OpaqueValue = nullptr; }
970 void unbind(CodeGenFunction &CGF) {
971 assert(OpaqueValue && "no data to unbind!");
974 CGF.OpaqueLValues.erase(OpaqueValue);
976 CGF.OpaqueRValues.erase(OpaqueValue);
977 CGF.unprotectFromPeepholes(Protection);
982 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
983 class OpaqueValueMapping {
984 CodeGenFunction &CGF;
985 OpaqueValueMappingData Data;
988 static bool shouldBindAsLValue(const Expr *expr) {
989 return OpaqueValueMappingData::shouldBindAsLValue(expr);
992 /// Build the opaque value mapping for the given conditional
993 /// operator if it's the GNU ?: extension. This is a common
994 /// enough pattern that the convenience operator is really
997 OpaqueValueMapping(CodeGenFunction &CGF,
998 const AbstractConditionalOperator *op) : CGF(CGF) {
999 if (isa<ConditionalOperator>(op))
1000 // Leave Data empty.
1003 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
1004 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
1008 /// Build the opaque value mapping for an OpaqueValueExpr whose source
1009 /// expression is set to the expression the OVE represents.
1010 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
1013 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
1014 "for OVE with no source expression");
1015 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
1019 OpaqueValueMapping(CodeGenFunction &CGF,
1020 const OpaqueValueExpr *opaqueValue,
1022 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
1025 OpaqueValueMapping(CodeGenFunction &CGF,
1026 const OpaqueValueExpr *opaqueValue,
1028 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
1036 ~OpaqueValueMapping() {
1037 if (Data.isValid()) Data.unbind(CGF);
1042 CGDebugInfo *DebugInfo;
1043 bool DisableDebugInfo;
1045 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
1046 /// calling llvm.stacksave for multiple VLAs in the same scope.
1047 bool DidCallStackSave;
1049 /// IndirectBranch - The first time an indirect goto is seen we create a block
1050 /// with an indirect branch. Every time we see the address of a label taken,
1051 /// we add the label to the indirect goto. Every subsequent indirect goto is
1052 /// codegen'd as a jump to the IndirectBranch's basic block.
1053 llvm::IndirectBrInst *IndirectBranch;
1055 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
1057 DeclMapTy LocalDeclMap;
1059 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
1060 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1062 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1065 /// Track escaped local variables with auto storage. Used during SEH
1066 /// outlining to produce a call to llvm.localescape.
1067 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1069 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1070 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1072 // BreakContinueStack - This keeps track of where break and continue
1073 // statements should jump to.
1074 struct BreakContinue {
1075 BreakContinue(JumpDest Break, JumpDest Continue)
1076 : BreakBlock(Break), ContinueBlock(Continue) {}
1078 JumpDest BreakBlock;
1079 JumpDest ContinueBlock;
1081 SmallVector<BreakContinue, 8> BreakContinueStack;
1083 /// Handles cancellation exit points in OpenMP-related constructs.
1084 class OpenMPCancelExitStack {
1085 /// Tracks cancellation exit point and join point for cancel-related exit
1086 /// and normal exit.
1088 CancelExit() = default;
1089 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1091 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1092 OpenMPDirectiveKind Kind = OMPD_unknown;
1093 /// true if the exit block has been emitted already by the special
1094 /// emitExit() call, false if the default codegen is used.
1095 bool HasBeenEmitted = false;
1100 SmallVector<CancelExit, 8> Stack;
1103 OpenMPCancelExitStack() : Stack(1) {}
1104 ~OpenMPCancelExitStack() = default;
1105 /// Fetches the exit block for the current OpenMP construct.
1106 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1107 /// Emits exit block with special codegen procedure specific for the related
1108 /// OpenMP construct + emits code for normal construct cleanup.
1109 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1110 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1111 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1112 assert(CGF.getOMPCancelDestination(Kind).isValid());
1113 assert(CGF.HaveInsertPoint());
1114 assert(!Stack.back().HasBeenEmitted);
1115 auto IP = CGF.Builder.saveAndClearIP();
1116 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1118 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1119 CGF.Builder.restoreIP(IP);
1120 Stack.back().HasBeenEmitted = true;
1124 /// Enter the cancel supporting \a Kind construct.
1125 /// \param Kind OpenMP directive that supports cancel constructs.
1126 /// \param HasCancel true, if the construct has inner cancel directive,
1127 /// false otherwise.
1128 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1129 Stack.push_back({Kind,
1130 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1132 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1135 /// Emits default exit point for the cancel construct (if the special one
1136 /// has not be used) + join point for cancel/normal exits.
1137 void exit(CodeGenFunction &CGF) {
1138 if (getExitBlock().isValid()) {
1139 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1140 bool HaveIP = CGF.HaveInsertPoint();
1141 if (!Stack.back().HasBeenEmitted) {
1143 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1144 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1145 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1147 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1149 CGF.Builder.CreateUnreachable();
1150 CGF.Builder.ClearInsertionPoint();
1156 OpenMPCancelExitStack OMPCancelStack;
1158 /// Controls insertion of cancellation exit blocks in worksharing constructs.
1159 class OMPCancelStackRAII {
1160 CodeGenFunction &CGF;
1163 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1166 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1168 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1173 /// Calculate branch weights appropriate for PGO data
1174 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1175 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1176 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1177 uint64_t LoopCount);
1180 /// Increment the profiler's counter for the given statement by \p StepV.
1181 /// If \p StepV is null, the default increment is 1.
1182 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) {
1183 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1184 PGO.emitCounterIncrement(Builder, S, StepV);
1185 PGO.setCurrentStmt(S);
1188 /// Get the profiler's count for the given statement.
1189 uint64_t getProfileCount(const Stmt *S) {
1190 Optional<uint64_t> Count = PGO.getStmtCount(S);
1191 if (!Count.hasValue())
1196 /// Set the profiler's current count.
1197 void setCurrentProfileCount(uint64_t Count) {
1198 PGO.setCurrentRegionCount(Count);
1201 /// Get the profiler's current count. This is generally the count for the most
1202 /// recently incremented counter.
1203 uint64_t getCurrentProfileCount() {
1204 return PGO.getCurrentRegionCount();
1209 /// SwitchInsn - This is nearest current switch instruction. It is null if
1210 /// current context is not in a switch.
1211 llvm::SwitchInst *SwitchInsn;
1212 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1213 SmallVector<uint64_t, 16> *SwitchWeights;
1215 /// CaseRangeBlock - This block holds if condition check for last case
1216 /// statement range in current switch instruction.
1217 llvm::BasicBlock *CaseRangeBlock;
1219 /// OpaqueLValues - Keeps track of the current set of opaque value
1221 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1222 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1224 // VLASizeMap - This keeps track of the associated size for each VLA type.
1225 // We track this by the size expression rather than the type itself because
1226 // in certain situations, like a const qualifier applied to an VLA typedef,
1227 // multiple VLA types can share the same size expression.
1228 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1229 // enter/leave scopes.
1230 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1232 /// A block containing a single 'unreachable' instruction. Created
1233 /// lazily by getUnreachableBlock().
1234 llvm::BasicBlock *UnreachableBlock;
1236 /// Counts of the number return expressions in the function.
1237 unsigned NumReturnExprs;
1239 /// Count the number of simple (constant) return expressions in the function.
1240 unsigned NumSimpleReturnExprs;
1242 /// The last regular (non-return) debug location (breakpoint) in the function.
1243 SourceLocation LastStopPoint;
1246 /// A scope within which we are constructing the fields of an object which
1247 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1248 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1249 class FieldConstructionScope {
1251 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1252 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1253 CGF.CXXDefaultInitExprThis = This;
1255 ~FieldConstructionScope() {
1256 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1260 CodeGenFunction &CGF;
1261 Address OldCXXDefaultInitExprThis;
1264 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1265 /// is overridden to be the object under construction.
1266 class CXXDefaultInitExprScope {
1268 CXXDefaultInitExprScope(CodeGenFunction &CGF)
1269 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1270 OldCXXThisAlignment(CGF.CXXThisAlignment) {
1271 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1272 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1274 ~CXXDefaultInitExprScope() {
1275 CGF.CXXThisValue = OldCXXThisValue;
1276 CGF.CXXThisAlignment = OldCXXThisAlignment;
1280 CodeGenFunction &CGF;
1281 llvm::Value *OldCXXThisValue;
1282 CharUnits OldCXXThisAlignment;
1285 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1286 /// current loop index is overridden.
1287 class ArrayInitLoopExprScope {
1289 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1290 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1291 CGF.ArrayInitIndex = Index;
1293 ~ArrayInitLoopExprScope() {
1294 CGF.ArrayInitIndex = OldArrayInitIndex;
1298 CodeGenFunction &CGF;
1299 llvm::Value *OldArrayInitIndex;
1302 class InlinedInheritingConstructorScope {
1304 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1305 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1306 OldCurCodeDecl(CGF.CurCodeDecl),
1307 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1308 OldCXXABIThisValue(CGF.CXXABIThisValue),
1309 OldCXXThisValue(CGF.CXXThisValue),
1310 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1311 OldCXXThisAlignment(CGF.CXXThisAlignment),
1312 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1313 OldCXXInheritedCtorInitExprArgs(
1314 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1316 CGF.CurFuncDecl = CGF.CurCodeDecl =
1317 cast<CXXConstructorDecl>(GD.getDecl());
1318 CGF.CXXABIThisDecl = nullptr;
1319 CGF.CXXABIThisValue = nullptr;
1320 CGF.CXXThisValue = nullptr;
1321 CGF.CXXABIThisAlignment = CharUnits();
1322 CGF.CXXThisAlignment = CharUnits();
1323 CGF.ReturnValue = Address::invalid();
1324 CGF.FnRetTy = QualType();
1325 CGF.CXXInheritedCtorInitExprArgs.clear();
1327 ~InlinedInheritingConstructorScope() {
1328 CGF.CurGD = OldCurGD;
1329 CGF.CurFuncDecl = OldCurFuncDecl;
1330 CGF.CurCodeDecl = OldCurCodeDecl;
1331 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1332 CGF.CXXABIThisValue = OldCXXABIThisValue;
1333 CGF.CXXThisValue = OldCXXThisValue;
1334 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1335 CGF.CXXThisAlignment = OldCXXThisAlignment;
1336 CGF.ReturnValue = OldReturnValue;
1337 CGF.FnRetTy = OldFnRetTy;
1338 CGF.CXXInheritedCtorInitExprArgs =
1339 std::move(OldCXXInheritedCtorInitExprArgs);
1343 CodeGenFunction &CGF;
1344 GlobalDecl OldCurGD;
1345 const Decl *OldCurFuncDecl;
1346 const Decl *OldCurCodeDecl;
1347 ImplicitParamDecl *OldCXXABIThisDecl;
1348 llvm::Value *OldCXXABIThisValue;
1349 llvm::Value *OldCXXThisValue;
1350 CharUnits OldCXXABIThisAlignment;
1351 CharUnits OldCXXThisAlignment;
1352 Address OldReturnValue;
1353 QualType OldFnRetTy;
1354 CallArgList OldCXXInheritedCtorInitExprArgs;
1358 /// CXXThisDecl - When generating code for a C++ member function,
1359 /// this will hold the implicit 'this' declaration.
1360 ImplicitParamDecl *CXXABIThisDecl;
1361 llvm::Value *CXXABIThisValue;
1362 llvm::Value *CXXThisValue;
1363 CharUnits CXXABIThisAlignment;
1364 CharUnits CXXThisAlignment;
1366 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1367 /// this expression.
1368 Address CXXDefaultInitExprThis = Address::invalid();
1370 /// The current array initialization index when evaluating an
1371 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1372 llvm::Value *ArrayInitIndex = nullptr;
1374 /// The values of function arguments to use when evaluating
1375 /// CXXInheritedCtorInitExprs within this context.
1376 CallArgList CXXInheritedCtorInitExprArgs;
1378 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1379 /// destructor, this will hold the implicit argument (e.g. VTT).
1380 ImplicitParamDecl *CXXStructorImplicitParamDecl;
1381 llvm::Value *CXXStructorImplicitParamValue;
1383 /// OutermostConditional - Points to the outermost active
1384 /// conditional control. This is used so that we know if a
1385 /// temporary should be destroyed conditionally.
1386 ConditionalEvaluation *OutermostConditional;
1388 /// The current lexical scope.
1389 LexicalScope *CurLexicalScope;
1391 /// The current source location that should be used for exception
1393 SourceLocation CurEHLocation;
1395 /// BlockByrefInfos - For each __block variable, contains
1396 /// information about the layout of the variable.
1397 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1399 /// Used by -fsanitize=nullability-return to determine whether the return
1400 /// value can be checked.
1401 llvm::Value *RetValNullabilityPrecondition = nullptr;
1403 /// Check if -fsanitize=nullability-return instrumentation is required for
1405 bool requiresReturnValueNullabilityCheck() const {
1406 return RetValNullabilityPrecondition;
1409 llvm::BasicBlock *TerminateLandingPad;
1410 llvm::BasicBlock *TerminateHandler;
1411 llvm::BasicBlock *TrapBB;
1413 /// True if we need emit the life-time markers.
1414 const bool ShouldEmitLifetimeMarkers;
1416 /// Add OpenCL kernel arg metadata and the kernel attribute meatadata to
1417 /// the function metadata.
1418 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1419 llvm::Function *Fn);
1422 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1425 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1426 ASTContext &getContext() const { return CGM.getContext(); }
1427 CGDebugInfo *getDebugInfo() {
1428 if (DisableDebugInfo)
1432 void disableDebugInfo() { DisableDebugInfo = true; }
1433 void enableDebugInfo() { DisableDebugInfo = false; }
1435 bool shouldUseFusedARCCalls() {
1436 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1439 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1441 /// Returns a pointer to the function's exception object and selector slot,
1442 /// which is assigned in every landing pad.
1443 Address getExceptionSlot();
1444 Address getEHSelectorSlot();
1446 /// Returns the contents of the function's exception object and selector
1448 llvm::Value *getExceptionFromSlot();
1449 llvm::Value *getSelectorFromSlot();
1451 Address getNormalCleanupDestSlot();
1453 llvm::BasicBlock *getUnreachableBlock() {
1454 if (!UnreachableBlock) {
1455 UnreachableBlock = createBasicBlock("unreachable");
1456 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1458 return UnreachableBlock;
1461 llvm::BasicBlock *getInvokeDest() {
1462 if (!EHStack.requiresLandingPad()) return nullptr;
1463 return getInvokeDestImpl();
1466 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1468 const TargetInfo &getTarget() const { return Target; }
1469 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1471 //===--------------------------------------------------------------------===//
1473 //===--------------------------------------------------------------------===//
1475 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1477 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1478 Address arrayEndPointer,
1479 QualType elementType,
1480 CharUnits elementAlignment,
1481 Destroyer *destroyer);
1482 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1483 llvm::Value *arrayEnd,
1484 QualType elementType,
1485 CharUnits elementAlignment,
1486 Destroyer *destroyer);
1488 void pushDestroy(QualType::DestructionKind dtorKind,
1489 Address addr, QualType type);
1490 void pushEHDestroy(QualType::DestructionKind dtorKind,
1491 Address addr, QualType type);
1492 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1493 Destroyer *destroyer, bool useEHCleanupForArray);
1494 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1495 QualType type, Destroyer *destroyer,
1496 bool useEHCleanupForArray);
1497 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1498 llvm::Value *CompletePtr,
1499 QualType ElementType);
1500 void pushStackRestore(CleanupKind kind, Address SPMem);
1501 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1502 bool useEHCleanupForArray);
1503 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1504 Destroyer *destroyer,
1505 bool useEHCleanupForArray,
1507 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1508 QualType elementType, CharUnits elementAlign,
1509 Destroyer *destroyer,
1510 bool checkZeroLength, bool useEHCleanup);
1512 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1514 /// Determines whether an EH cleanup is required to destroy a type
1515 /// with the given destruction kind.
1516 bool needsEHCleanup(QualType::DestructionKind kind) {
1518 case QualType::DK_none:
1520 case QualType::DK_cxx_destructor:
1521 case QualType::DK_objc_weak_lifetime:
1522 return getLangOpts().Exceptions;
1523 case QualType::DK_objc_strong_lifetime:
1524 return getLangOpts().Exceptions &&
1525 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1527 llvm_unreachable("bad destruction kind");
1530 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1531 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1534 //===--------------------------------------------------------------------===//
1536 //===--------------------------------------------------------------------===//
1538 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1540 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1542 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1543 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1544 const ObjCPropertyImplDecl *PID);
1545 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1546 const ObjCPropertyImplDecl *propImpl,
1547 const ObjCMethodDecl *GetterMothodDecl,
1548 llvm::Constant *AtomicHelperFn);
1550 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1551 ObjCMethodDecl *MD, bool ctor);
1553 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1554 /// for the given property.
1555 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1556 const ObjCPropertyImplDecl *PID);
1557 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1558 const ObjCPropertyImplDecl *propImpl,
1559 llvm::Constant *AtomicHelperFn);
1561 //===--------------------------------------------------------------------===//
1563 //===--------------------------------------------------------------------===//
1565 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1566 static void destroyBlockInfos(CGBlockInfo *info);
1568 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1569 const CGBlockInfo &Info,
1570 const DeclMapTy &ldm,
1571 bool IsLambdaConversionToBlock);
1573 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1574 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1575 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1576 const ObjCPropertyImplDecl *PID);
1577 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1578 const ObjCPropertyImplDecl *PID);
1579 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1581 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1583 class AutoVarEmission;
1585 void emitByrefStructureInit(const AutoVarEmission &emission);
1586 void enterByrefCleanup(const AutoVarEmission &emission);
1588 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1591 Address LoadBlockStruct();
1592 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1594 /// BuildBlockByrefAddress - Computes the location of the
1595 /// data in a variable which is declared as __block.
1596 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1597 bool followForward = true);
1598 Address emitBlockByrefAddress(Address baseAddr,
1599 const BlockByrefInfo &info,
1601 const llvm::Twine &name);
1603 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1605 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1607 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1608 const CGFunctionInfo &FnInfo);
1609 /// \brief Emit code for the start of a function.
1610 /// \param Loc The location to be associated with the function.
1611 /// \param StartLoc The location of the function body.
1612 void StartFunction(GlobalDecl GD,
1615 const CGFunctionInfo &FnInfo,
1616 const FunctionArgList &Args,
1617 SourceLocation Loc = SourceLocation(),
1618 SourceLocation StartLoc = SourceLocation());
1620 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor);
1622 void EmitConstructorBody(FunctionArgList &Args);
1623 void EmitDestructorBody(FunctionArgList &Args);
1624 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1625 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1626 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1628 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1629 CallArgList &CallArgs);
1630 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1631 void EmitLambdaBlockInvokeBody();
1632 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1633 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1634 void EmitAsanPrologueOrEpilogue(bool Prologue);
1636 /// \brief Emit the unified return block, trying to avoid its emission when
1638 /// \return The debug location of the user written return statement if the
1639 /// return block is is avoided.
1640 llvm::DebugLoc EmitReturnBlock();
1642 /// FinishFunction - Complete IR generation of the current function. It is
1643 /// legal to call this function even if there is no current insertion point.
1644 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1646 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1647 const CGFunctionInfo &FnInfo);
1649 void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1650 const ThunkInfo *Thunk);
1654 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1655 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1656 llvm::Value *Callee);
1658 /// Generate a thunk for the given method.
1659 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1660 GlobalDecl GD, const ThunkInfo &Thunk);
1662 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1663 const CGFunctionInfo &FnInfo,
1664 GlobalDecl GD, const ThunkInfo &Thunk);
1666 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1667 FunctionArgList &Args);
1669 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1671 /// Struct with all informations about dynamic [sub]class needed to set vptr.
1674 const CXXRecordDecl *NearestVBase;
1675 CharUnits OffsetFromNearestVBase;
1676 const CXXRecordDecl *VTableClass;
1679 /// Initialize the vtable pointer of the given subobject.
1680 void InitializeVTablePointer(const VPtr &vptr);
1682 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1684 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1685 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1687 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1688 CharUnits OffsetFromNearestVBase,
1689 bool BaseIsNonVirtualPrimaryBase,
1690 const CXXRecordDecl *VTableClass,
1691 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1693 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1695 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1697 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1698 const CXXRecordDecl *VTableClass);
1700 enum CFITypeCheckKind {
1704 CFITCK_UnrelatedCast,
1708 /// \brief Derived is the presumed address of an object of type T after a
1709 /// cast. If T is a polymorphic class type, emit a check that the virtual
1710 /// table for Derived belongs to a class derived from T.
1711 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1712 bool MayBeNull, CFITypeCheckKind TCK,
1713 SourceLocation Loc);
1715 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1716 /// If vptr CFI is enabled, emit a check that VTable is valid.
1717 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1718 CFITypeCheckKind TCK, SourceLocation Loc);
1720 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1721 /// RD using llvm.type.test.
1722 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1723 CFITypeCheckKind TCK, SourceLocation Loc);
1725 /// If whole-program virtual table optimization is enabled, emit an assumption
1726 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1727 /// enabled, emit a check that VTable is a member of RD's type identifier.
1728 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1729 llvm::Value *VTable, SourceLocation Loc);
1731 /// Returns whether we should perform a type checked load when loading a
1732 /// virtual function for virtual calls to members of RD. This is generally
1733 /// true when both vcall CFI and whole-program-vtables are enabled.
1734 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1736 /// Emit a type checked load from the given vtable.
1737 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1738 uint64_t VTableByteOffset);
1740 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1741 /// expr can be devirtualized.
1742 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1743 const CXXMethodDecl *MD);
1745 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1746 /// given phase of destruction for a destructor. The end result
1747 /// should call destructors on members and base classes in reverse
1748 /// order of their construction.
1749 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1751 /// ShouldInstrumentFunction - Return true if the current function should be
1752 /// instrumented with __cyg_profile_func_* calls
1753 bool ShouldInstrumentFunction();
1755 /// ShouldXRayInstrument - Return true if the current function should be
1756 /// instrumented with XRay nop sleds.
1757 bool ShouldXRayInstrumentFunction() const;
1759 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1760 /// instrumentation function with the current function and the call site, if
1761 /// function instrumentation is enabled.
1762 void EmitFunctionInstrumentation(const char *Fn);
1764 /// EmitMCountInstrumentation - Emit call to .mcount.
1765 void EmitMCountInstrumentation();
1767 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1768 /// arguments for the given function. This is also responsible for naming the
1769 /// LLVM function arguments.
1770 void EmitFunctionProlog(const CGFunctionInfo &FI,
1772 const FunctionArgList &Args);
1774 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1775 /// given temporary.
1776 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1777 SourceLocation EndLoc);
1779 /// Emit a test that checks if the return value \p RV is nonnull.
1780 void EmitReturnValueCheck(llvm::Value *RV, SourceLocation EndLoc);
1782 /// EmitStartEHSpec - Emit the start of the exception spec.
1783 void EmitStartEHSpec(const Decl *D);
1785 /// EmitEndEHSpec - Emit the end of the exception spec.
1786 void EmitEndEHSpec(const Decl *D);
1788 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1789 llvm::BasicBlock *getTerminateLandingPad();
1791 /// getTerminateHandler - Return a handler (not a landing pad, just
1792 /// a catch handler) that just calls terminate. This is used when
1793 /// a terminate scope encloses a try.
1794 llvm::BasicBlock *getTerminateHandler();
1796 llvm::Type *ConvertTypeForMem(QualType T);
1797 llvm::Type *ConvertType(QualType T);
1798 llvm::Type *ConvertType(const TypeDecl *T) {
1799 return ConvertType(getContext().getTypeDeclType(T));
1802 /// LoadObjCSelf - Load the value of self. This function is only valid while
1803 /// generating code for an Objective-C method.
1804 llvm::Value *LoadObjCSelf();
1806 /// TypeOfSelfObject - Return type of object that this self represents.
1807 QualType TypeOfSelfObject();
1809 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1810 /// an aggregate LLVM type or is void.
1811 static TypeEvaluationKind getEvaluationKind(QualType T);
1813 static bool hasScalarEvaluationKind(QualType T) {
1814 return getEvaluationKind(T) == TEK_Scalar;
1817 static bool hasAggregateEvaluationKind(QualType T) {
1818 return getEvaluationKind(T) == TEK_Aggregate;
1821 /// createBasicBlock - Create an LLVM basic block.
1822 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1823 llvm::Function *parent = nullptr,
1824 llvm::BasicBlock *before = nullptr) {
1826 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1828 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1832 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1834 JumpDest getJumpDestForLabel(const LabelDecl *S);
1836 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1837 /// another basic block, simplify it. This assumes that no other code could
1838 /// potentially reference the basic block.
1839 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1841 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1842 /// adding a fall-through branch from the current insert block if
1843 /// necessary. It is legal to call this function even if there is no current
1844 /// insertion point.
1846 /// IsFinished - If true, indicates that the caller has finished emitting
1847 /// branches to the given block and does not expect to emit code into it. This
1848 /// means the block can be ignored if it is unreachable.
1849 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1851 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1852 /// near its uses, and leave the insertion point in it.
1853 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1855 /// EmitBranch - Emit a branch to the specified basic block from the current
1856 /// insert block, taking care to avoid creation of branches from dummy
1857 /// blocks. It is legal to call this function even if there is no current
1858 /// insertion point.
1860 /// This function clears the current insertion point. The caller should follow
1861 /// calls to this function with calls to Emit*Block prior to generation new
1863 void EmitBranch(llvm::BasicBlock *Block);
1865 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1866 /// indicates that the current code being emitted is unreachable.
1867 bool HaveInsertPoint() const {
1868 return Builder.GetInsertBlock() != nullptr;
1871 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1872 /// emitted IR has a place to go. Note that by definition, if this function
1873 /// creates a block then that block is unreachable; callers may do better to
1874 /// detect when no insertion point is defined and simply skip IR generation.
1875 void EnsureInsertPoint() {
1876 if (!HaveInsertPoint())
1877 EmitBlock(createBasicBlock());
1880 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1881 /// specified stmt yet.
1882 void ErrorUnsupported(const Stmt *S, const char *Type);
1884 //===--------------------------------------------------------------------===//
1886 //===--------------------------------------------------------------------===//
1888 LValue MakeAddrLValue(Address Addr, QualType T,
1889 LValueBaseInfo BaseInfo =
1890 LValueBaseInfo(AlignmentSource::Type)) {
1891 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo,
1892 CGM.getTBAAInfo(T));
1895 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1896 LValueBaseInfo BaseInfo =
1897 LValueBaseInfo(AlignmentSource::Type)) {
1898 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1899 BaseInfo, CGM.getTBAAInfo(T));
1902 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1903 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1904 CharUnits getNaturalTypeAlignment(QualType T,
1905 LValueBaseInfo *BaseInfo = nullptr,
1906 bool forPointeeType = false);
1907 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1908 LValueBaseInfo *BaseInfo = nullptr);
1910 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1911 LValueBaseInfo *BaseInfo = nullptr);
1912 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1914 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1915 LValueBaseInfo *BaseInfo = nullptr);
1916 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1918 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1919 /// block. The caller is responsible for setting an appropriate alignment on
1921 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1922 const Twine &Name = "tmp");
1923 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1924 const Twine &Name = "tmp");
1926 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1927 /// default ABI alignment of the given LLVM type.
1929 /// IMPORTANT NOTE: This is *not* generally the right alignment for
1930 /// any given AST type that happens to have been lowered to the
1931 /// given IR type. This should only ever be used for function-local,
1932 /// IR-driven manipulations like saving and restoring a value. Do
1933 /// not hand this address off to arbitrary IRGen routines, and especially
1934 /// do not pass it as an argument to a function that might expect a
1935 /// properly ABI-aligned value.
1936 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1937 const Twine &Name = "tmp");
1939 /// InitTempAlloca - Provide an initial value for the given alloca which
1940 /// will be observable at all locations in the function.
1942 /// The address should be something that was returned from one of
1943 /// the CreateTempAlloca or CreateMemTemp routines, and the
1944 /// initializer must be valid in the entry block (i.e. it must
1945 /// either be a constant or an argument value).
1946 void InitTempAlloca(Address Alloca, llvm::Value *Value);
1948 /// CreateIRTemp - Create a temporary IR object of the given type, with
1949 /// appropriate alignment. This routine should only be used when an temporary
1950 /// value needs to be stored into an alloca (for example, to avoid explicit
1951 /// PHI construction), but the type is the IR type, not the type appropriate
1952 /// for storing in memory.
1954 /// That is, this is exactly equivalent to CreateMemTemp, but calling
1955 /// ConvertType instead of ConvertTypeForMem.
1956 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1958 /// CreateMemTemp - Create a temporary memory object of the given type, with
1959 /// appropriate alignment.
1960 Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1961 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1963 /// CreateAggTemp - Create a temporary memory object for the given
1965 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1966 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1968 AggValueSlot::IsNotDestructed,
1969 AggValueSlot::DoesNotNeedGCBarriers,
1970 AggValueSlot::IsNotAliased);
1973 /// Emit a cast to void* in the appropriate address space.
1974 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1976 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1977 /// expression and compare the result against zero, returning an Int1Ty value.
1978 llvm::Value *EvaluateExprAsBool(const Expr *E);
1980 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1981 void EmitIgnoredExpr(const Expr *E);
1983 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1984 /// any type. The result is returned as an RValue struct. If this is an
1985 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1986 /// the result should be returned.
1988 /// \param ignoreResult True if the resulting value isn't used.
1989 RValue EmitAnyExpr(const Expr *E,
1990 AggValueSlot aggSlot = AggValueSlot::ignored(),
1991 bool ignoreResult = false);
1993 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1994 // or the value of the expression, depending on how va_list is defined.
1995 Address EmitVAListRef(const Expr *E);
1997 /// Emit a "reference" to a __builtin_ms_va_list; this is
1998 /// always the value of the expression, because a __builtin_ms_va_list is a
1999 /// pointer to a char.
2000 Address EmitMSVAListRef(const Expr *E);
2002 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will
2003 /// always be accessible even if no aggregate location is provided.
2004 RValue EmitAnyExprToTemp(const Expr *E);
2006 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
2007 /// arbitrary expression into the given memory location.
2008 void EmitAnyExprToMem(const Expr *E, Address Location,
2009 Qualifiers Quals, bool IsInitializer);
2011 void EmitAnyExprToExn(const Expr *E, Address Addr);
2013 /// EmitExprAsInit - Emits the code necessary to initialize a
2014 /// location in memory with the given initializer.
2015 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2016 bool capturedByInit);
2018 /// hasVolatileMember - returns true if aggregate type has a volatile
2020 bool hasVolatileMember(QualType T) {
2021 if (const RecordType *RT = T->getAs<RecordType>()) {
2022 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2023 return RD->hasVolatileMember();
2027 /// EmitAggregateCopy - Emit an aggregate assignment.
2029 /// The difference to EmitAggregateCopy is that tail padding is not copied.
2030 /// This is required for correctness when assigning non-POD structures in C++.
2031 void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
2033 bool IsVolatile = hasVolatileMember(EltTy);
2034 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
2037 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
2038 QualType DestTy, QualType SrcTy) {
2039 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
2040 /*IsAssignment=*/false);
2043 /// EmitAggregateCopy - Emit an aggregate copy.
2045 /// \param isVolatile - True iff either the source or the destination is
2047 /// \param isAssignment - If false, allow padding to be copied. This often
2048 /// yields more efficient.
2049 void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
2050 QualType EltTy, bool isVolatile=false,
2051 bool isAssignment = false);
2053 /// GetAddrOfLocalVar - Return the address of a local variable.
2054 Address GetAddrOfLocalVar(const VarDecl *VD) {
2055 auto it = LocalDeclMap.find(VD);
2056 assert(it != LocalDeclMap.end() &&
2057 "Invalid argument to GetAddrOfLocalVar(), no decl!");
2061 /// getOpaqueLValueMapping - Given an opaque value expression (which
2062 /// must be mapped to an l-value), return its mapping.
2063 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
2064 assert(OpaqueValueMapping::shouldBindAsLValue(e));
2066 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
2067 it = OpaqueLValues.find(e);
2068 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2072 /// getOpaqueRValueMapping - Given an opaque value expression (which
2073 /// must be mapped to an r-value), return its mapping.
2074 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2075 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2077 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2078 it = OpaqueRValues.find(e);
2079 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2083 /// Get the index of the current ArrayInitLoopExpr, if any.
2084 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2086 /// getAccessedFieldNo - Given an encoded value and a result number, return
2087 /// the input field number being accessed.
2088 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2090 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2091 llvm::BasicBlock *GetIndirectGotoBlock();
2093 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts.
2094 static bool IsWrappedCXXThis(const Expr *E);
2096 /// EmitNullInitialization - Generate code to set a value of the given type to
2097 /// null, If the type contains data member pointers, they will be initialized
2098 /// to -1 in accordance with the Itanium C++ ABI.
2099 void EmitNullInitialization(Address DestPtr, QualType Ty);
2101 /// Emits a call to an LLVM variable-argument intrinsic, either
2102 /// \c llvm.va_start or \c llvm.va_end.
2103 /// \param ArgValue A reference to the \c va_list as emitted by either
2104 /// \c EmitVAListRef or \c EmitMSVAListRef.
2105 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2106 /// calls \c llvm.va_end.
2107 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2109 /// Generate code to get an argument from the passed in pointer
2110 /// and update it accordingly.
2111 /// \param VE The \c VAArgExpr for which to generate code.
2112 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2113 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2114 /// \returns A pointer to the argument.
2115 // FIXME: We should be able to get rid of this method and use the va_arg
2116 // instruction in LLVM instead once it works well enough.
2117 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2119 /// emitArrayLength - Compute the length of an array, even if it's a
2120 /// VLA, and drill down to the base element type.
2121 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2125 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2126 /// the given variably-modified type and store them in the VLASizeMap.
2128 /// This function can be called with a null (unreachable) insert point.
2129 void EmitVariablyModifiedType(QualType Ty);
2131 /// getVLASize - Returns an LLVM value that corresponds to the size,
2132 /// in non-variably-sized elements, of a variable length array type,
2133 /// plus that largest non-variably-sized element type. Assumes that
2134 /// the type has already been emitted with EmitVariablyModifiedType.
2135 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2136 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2138 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2139 /// generating code for an C++ member function.
2140 llvm::Value *LoadCXXThis() {
2141 assert(CXXThisValue && "no 'this' value for this function");
2142 return CXXThisValue;
2144 Address LoadCXXThisAddress();
2146 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2148 // FIXME: Every place that calls LoadCXXVTT is something
2149 // that needs to be abstracted properly.
2150 llvm::Value *LoadCXXVTT() {
2151 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2152 return CXXStructorImplicitParamValue;
2155 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2156 /// complete class to the given direct base.
2158 GetAddressOfDirectBaseInCompleteClass(Address Value,
2159 const CXXRecordDecl *Derived,
2160 const CXXRecordDecl *Base,
2161 bool BaseIsVirtual);
2163 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2165 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2166 /// load of 'this' and returns address of the base class.
2167 Address GetAddressOfBaseClass(Address Value,
2168 const CXXRecordDecl *Derived,
2169 CastExpr::path_const_iterator PathBegin,
2170 CastExpr::path_const_iterator PathEnd,
2171 bool NullCheckValue, SourceLocation Loc);
2173 Address GetAddressOfDerivedClass(Address Value,
2174 const CXXRecordDecl *Derived,
2175 CastExpr::path_const_iterator PathBegin,
2176 CastExpr::path_const_iterator PathEnd,
2177 bool NullCheckValue);
2179 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2180 /// base constructor/destructor with virtual bases.
2181 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2182 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2183 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2186 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2187 CXXCtorType CtorType,
2188 const FunctionArgList &Args,
2189 SourceLocation Loc);
2190 // It's important not to confuse this and the previous function. Delegating
2191 // constructors are the C++0x feature. The constructor delegate optimization
2192 // is used to reduce duplication in the base and complete consturctors where
2193 // they are substantially the same.
2194 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2195 const FunctionArgList &Args);
2197 /// Emit a call to an inheriting constructor (that is, one that invokes a
2198 /// constructor inherited from a base class) by inlining its definition. This
2199 /// is necessary if the ABI does not support forwarding the arguments to the
2200 /// base class constructor (because they're variadic or similar).
2201 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2202 CXXCtorType CtorType,
2203 bool ForVirtualBase,
2207 /// Emit a call to a constructor inherited from a base class, passing the
2208 /// current constructor's arguments along unmodified (without even making
2210 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2211 bool ForVirtualBase, Address This,
2212 bool InheritedFromVBase,
2213 const CXXInheritedCtorInitExpr *E);
2215 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2216 bool ForVirtualBase, bool Delegating,
2217 Address This, const CXXConstructExpr *E);
2219 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2220 bool ForVirtualBase, bool Delegating,
2221 Address This, CallArgList &Args);
2223 /// Emit assumption load for all bases. Requires to be be called only on
2224 /// most-derived class and not under construction of the object.
2225 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2227 /// Emit assumption that vptr load == global vtable.
2228 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2230 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2231 Address This, Address Src,
2232 const CXXConstructExpr *E);
2234 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2235 const ArrayType *ArrayTy,
2237 const CXXConstructExpr *E,
2238 bool ZeroInitialization = false);
2240 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2241 llvm::Value *NumElements,
2243 const CXXConstructExpr *E,
2244 bool ZeroInitialization = false);
2246 static Destroyer destroyCXXObject;
2248 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2249 bool ForVirtualBase, bool Delegating,
2252 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2253 llvm::Type *ElementTy, Address NewPtr,
2254 llvm::Value *NumElements,
2255 llvm::Value *AllocSizeWithoutCookie);
2257 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2260 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2261 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2263 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2264 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2266 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2267 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2268 CharUnits CookieSize = CharUnits());
2270 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2271 const Expr *Arg, bool IsDelete);
2273 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2274 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2275 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2277 /// \brief Situations in which we might emit a check for the suitability of a
2278 /// pointer or glvalue.
2279 enum TypeCheckKind {
2280 /// Checking the operand of a load. Must be suitably sized and aligned.
2282 /// Checking the destination of a store. Must be suitably sized and aligned.
2284 /// Checking the bound value in a reference binding. Must be suitably sized
2285 /// and aligned, but is not required to refer to an object (until the
2286 /// reference is used), per core issue 453.
2287 TCK_ReferenceBinding,
2288 /// Checking the object expression in a non-static data member access. Must
2289 /// be an object within its lifetime.
2291 /// Checking the 'this' pointer for a call to a non-static member function.
2292 /// Must be an object within its lifetime.
2294 /// Checking the 'this' pointer for a constructor call.
2295 TCK_ConstructorCall,
2296 /// Checking the operand of a static_cast to a derived pointer type. Must be
2297 /// null or an object within its lifetime.
2298 TCK_DowncastPointer,
2299 /// Checking the operand of a static_cast to a derived reference type. Must
2300 /// be an object within its lifetime.
2301 TCK_DowncastReference,
2302 /// Checking the operand of a cast to a base object. Must be suitably sized
2305 /// Checking the operand of a cast to a virtual base object. Must be an
2306 /// object within its lifetime.
2307 TCK_UpcastToVirtualBase,
2308 /// Checking the value assigned to a _Nonnull pointer. Must not be null.
2312 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2313 /// calls to EmitTypeCheck can be skipped.
2314 bool sanitizePerformTypeCheck() const;
2316 /// \brief Emit a check that \p V is the address of storage of the
2317 /// appropriate size and alignment for an object of type \p Type.
2318 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2319 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2320 SanitizerSet SkippedChecks = SanitizerSet());
2322 /// \brief Emit a check that \p Base points into an array object, which
2323 /// we can access at index \p Index. \p Accessed should be \c false if we
2324 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2325 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2326 QualType IndexType, bool Accessed);
2328 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2329 bool isInc, bool isPre);
2330 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2331 bool isInc, bool isPre);
2333 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2334 llvm::Value *OffsetValue = nullptr) {
2335 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2339 /// Converts Location to a DebugLoc, if debug information is enabled.
2340 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2343 //===--------------------------------------------------------------------===//
2344 // Declaration Emission
2345 //===--------------------------------------------------------------------===//
2347 /// EmitDecl - Emit a declaration.
2349 /// This function can be called with a null (unreachable) insert point.
2350 void EmitDecl(const Decl &D);
2352 /// EmitVarDecl - Emit a local variable declaration.
2354 /// This function can be called with a null (unreachable) insert point.
2355 void EmitVarDecl(const VarDecl &D);
2357 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2358 bool capturedByInit);
2360 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2361 llvm::Value *Address);
2363 /// \brief Determine whether the given initializer is trivial in the sense
2364 /// that it requires no code to be generated.
2365 bool isTrivialInitializer(const Expr *Init);
2367 /// EmitAutoVarDecl - Emit an auto variable declaration.
2369 /// This function can be called with a null (unreachable) insert point.
2370 void EmitAutoVarDecl(const VarDecl &D);
2372 class AutoVarEmission {
2373 friend class CodeGenFunction;
2375 const VarDecl *Variable;
2377 /// The address of the alloca. Invalid if the variable was emitted
2378 /// as a global constant.
2381 llvm::Value *NRVOFlag;
2383 /// True if the variable is a __block variable.
2386 /// True if the variable is of aggregate type and has a constant
2388 bool IsConstantAggregate;
2390 /// Non-null if we should use lifetime annotations.
2391 llvm::Value *SizeForLifetimeMarkers;
2394 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2396 AutoVarEmission(const VarDecl &variable)
2397 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2398 IsByRef(false), IsConstantAggregate(false),
2399 SizeForLifetimeMarkers(nullptr) {}
2401 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2404 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2406 bool useLifetimeMarkers() const {
2407 return SizeForLifetimeMarkers != nullptr;
2409 llvm::Value *getSizeForLifetimeMarkers() const {
2410 assert(useLifetimeMarkers());
2411 return SizeForLifetimeMarkers;
2414 /// Returns the raw, allocated address, which is not necessarily
2415 /// the address of the object itself.
2416 Address getAllocatedAddress() const {
2420 /// Returns the address of the object within this declaration.
2421 /// Note that this does not chase the forwarding pointer for
2423 Address getObjectAddress(CodeGenFunction &CGF) const {
2424 if (!IsByRef) return Addr;
2426 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2429 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2430 void EmitAutoVarInit(const AutoVarEmission &emission);
2431 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2432 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2433 QualType::DestructionKind dtorKind);
2435 void EmitStaticVarDecl(const VarDecl &D,
2436 llvm::GlobalValue::LinkageTypes Linkage);
2441 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2443 static ParamValue forDirect(llvm::Value *value) {
2444 return ParamValue(value, 0);
2446 static ParamValue forIndirect(Address addr) {
2447 assert(!addr.getAlignment().isZero());
2448 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2451 bool isIndirect() const { return Alignment != 0; }
2452 llvm::Value *getAnyValue() const { return Value; }
2454 llvm::Value *getDirectValue() const {
2455 assert(!isIndirect());
2459 Address getIndirectAddress() const {
2460 assert(isIndirect());
2461 return Address(Value, CharUnits::fromQuantity(Alignment));
2465 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2466 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2468 /// protectFromPeepholes - Protect a value that we're intending to
2469 /// store to the side, but which will probably be used later, from
2470 /// aggressive peepholing optimizations that might delete it.
2472 /// Pass the result to unprotectFromPeepholes to declare that
2473 /// protection is no longer required.
2475 /// There's no particular reason why this shouldn't apply to
2476 /// l-values, it's just that no existing peepholes work on pointers.
2477 PeepholeProtection protectFromPeepholes(RValue rvalue);
2478 void unprotectFromPeepholes(PeepholeProtection protection);
2480 void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment,
2481 llvm::Value *OffsetValue = nullptr) {
2482 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2486 //===--------------------------------------------------------------------===//
2487 // Statement Emission
2488 //===--------------------------------------------------------------------===//
2490 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2491 void EmitStopPoint(const Stmt *S);
2493 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2494 /// this function even if there is no current insertion point.
2496 /// This function may clear the current insertion point; callers should use
2497 /// EnsureInsertPoint if they wish to subsequently generate code without first
2498 /// calling EmitBlock, EmitBranch, or EmitStmt.
2499 void EmitStmt(const Stmt *S);
2501 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2502 /// necessarily require an insertion point or debug information; typically
2503 /// because the statement amounts to a jump or a container of other
2506 /// \return True if the statement was handled.
2507 bool EmitSimpleStmt(const Stmt *S);
2509 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2510 AggValueSlot AVS = AggValueSlot::ignored());
2511 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2512 bool GetLast = false,
2514 AggValueSlot::ignored());
2516 /// EmitLabel - Emit the block for the given label. It is legal to call this
2517 /// function even if there is no current insertion point.
2518 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2520 void EmitLabelStmt(const LabelStmt &S);
2521 void EmitAttributedStmt(const AttributedStmt &S);
2522 void EmitGotoStmt(const GotoStmt &S);
2523 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2524 void EmitIfStmt(const IfStmt &S);
2526 void EmitWhileStmt(const WhileStmt &S,
2527 ArrayRef<const Attr *> Attrs = None);
2528 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2529 void EmitForStmt(const ForStmt &S,
2530 ArrayRef<const Attr *> Attrs = None);
2531 void EmitReturnStmt(const ReturnStmt &S);
2532 void EmitDeclStmt(const DeclStmt &S);
2533 void EmitBreakStmt(const BreakStmt &S);
2534 void EmitContinueStmt(const ContinueStmt &S);
2535 void EmitSwitchStmt(const SwitchStmt &S);
2536 void EmitDefaultStmt(const DefaultStmt &S);
2537 void EmitCaseStmt(const CaseStmt &S);
2538 void EmitCaseStmtRange(const CaseStmt &S);
2539 void EmitAsmStmt(const AsmStmt &S);
2541 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2542 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2543 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2544 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2545 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2547 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2548 void EmitCoreturnStmt(const CoreturnStmt &S);
2549 RValue EmitCoawaitExpr(const CoawaitExpr &E,
2550 AggValueSlot aggSlot = AggValueSlot::ignored(),
2551 bool ignoreResult = false);
2552 RValue EmitCoyieldExpr(const CoyieldExpr &E,
2553 AggValueSlot aggSlot = AggValueSlot::ignored(),
2554 bool ignoreResult = false);
2555 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2557 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2558 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2560 void EmitCXXTryStmt(const CXXTryStmt &S);
2561 void EmitSEHTryStmt(const SEHTryStmt &S);
2562 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2563 void EnterSEHTryStmt(const SEHTryStmt &S);
2564 void ExitSEHTryStmt(const SEHTryStmt &S);
2566 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2567 const Stmt *OutlinedStmt);
2569 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2570 const SEHExceptStmt &Except);
2572 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2573 const SEHFinallyStmt &Finally);
2575 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2576 llvm::Value *ParentFP,
2577 llvm::Value *EntryEBP);
2578 llvm::Value *EmitSEHExceptionCode();
2579 llvm::Value *EmitSEHExceptionInfo();
2580 llvm::Value *EmitSEHAbnormalTermination();
2582 /// Scan the outlined statement for captures from the parent function. For
2583 /// each capture, mark the capture as escaped and emit a call to
2584 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2585 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2588 /// Recovers the address of a local in a parent function. ParentVar is the
2589 /// address of the variable used in the immediate parent function. It can
2590 /// either be an alloca or a call to llvm.localrecover if there are nested
2591 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2593 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2595 llvm::Value *ParentFP);
2597 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2598 ArrayRef<const Attr *> Attrs = None);
2600 /// Returns calculated size of the specified type.
2601 llvm::Value *getTypeSize(QualType Ty);
2602 LValue InitCapturedStruct(const CapturedStmt &S);
2603 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2604 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2605 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2606 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2607 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2608 SmallVectorImpl<llvm::Value *> &CapturedVars);
2609 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2610 SourceLocation Loc);
2611 /// \brief Perform element by element copying of arrays with type \a
2612 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2613 /// generated by \a CopyGen.
2615 /// \param DestAddr Address of the destination array.
2616 /// \param SrcAddr Address of the source array.
2617 /// \param OriginalType Type of destination and source arrays.
2618 /// \param CopyGen Copying procedure that copies value of single array element
2619 /// to another single array element.
2620 void EmitOMPAggregateAssign(
2621 Address DestAddr, Address SrcAddr, QualType OriginalType,
2622 const llvm::function_ref<void(Address, Address)> &CopyGen);
2623 /// \brief Emit proper copying of data from one variable to another.
2625 /// \param OriginalType Original type of the copied variables.
2626 /// \param DestAddr Destination address.
2627 /// \param SrcAddr Source address.
2628 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2629 /// type of the base array element).
2630 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2631 /// the base array element).
2632 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2634 void EmitOMPCopy(QualType OriginalType,
2635 Address DestAddr, Address SrcAddr,
2636 const VarDecl *DestVD, const VarDecl *SrcVD,
2638 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2639 /// \a X = \a E \a BO \a E.
2641 /// \param X Value to be updated.
2642 /// \param E Update value.
2643 /// \param BO Binary operation for update operation.
2644 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2645 /// expression, false otherwise.
2646 /// \param AO Atomic ordering of the generated atomic instructions.
2647 /// \param CommonGen Code generator for complex expressions that cannot be
2648 /// expressed through atomicrmw instruction.
2649 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2650 /// generated, <false, RValue::get(nullptr)> otherwise.
2651 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2652 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2653 llvm::AtomicOrdering AO, SourceLocation Loc,
2654 const llvm::function_ref<RValue(RValue)> &CommonGen);
2655 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2656 OMPPrivateScope &PrivateScope);
2657 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2658 OMPPrivateScope &PrivateScope);
2659 void EmitOMPUseDevicePtrClause(
2660 const OMPClause &C, OMPPrivateScope &PrivateScope,
2661 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2662 /// \brief Emit code for copyin clause in \a D directive. The next code is
2663 /// generated at the start of outlined functions for directives:
2665 /// threadprivate_var1 = master_threadprivate_var1;
2666 /// operator=(threadprivate_var2, master_threadprivate_var2);
2668 /// __kmpc_barrier(&loc, global_tid);
2671 /// \param D OpenMP directive possibly with 'copyin' clause(s).
2672 /// \returns true if at least one copyin variable is found, false otherwise.
2673 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2674 /// \brief Emit initial code for lastprivate variables. If some variable is
2675 /// not also firstprivate, then the default initialization is used. Otherwise
2676 /// initialization of this variable is performed by EmitOMPFirstprivateClause
2679 /// \param D Directive that may have 'lastprivate' directives.
2680 /// \param PrivateScope Private scope for capturing lastprivate variables for
2681 /// proper codegen in internal captured statement.
2683 /// \returns true if there is at least one lastprivate variable, false
2685 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2686 OMPPrivateScope &PrivateScope);
2687 /// \brief Emit final copying of lastprivate values to original variables at
2688 /// the end of the worksharing or simd directive.
2690 /// \param D Directive that has at least one 'lastprivate' directives.
2691 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2692 /// it is the last iteration of the loop code in associated directive, or to
2693 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2694 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2696 llvm::Value *IsLastIterCond = nullptr);
2697 /// Emit initial code for linear clauses.
2698 void EmitOMPLinearClause(const OMPLoopDirective &D,
2699 CodeGenFunction::OMPPrivateScope &PrivateScope);
2700 /// Emit final code for linear clauses.
2701 /// \param CondGen Optional conditional code for final part of codegen for
2703 void EmitOMPLinearClauseFinal(
2704 const OMPLoopDirective &D,
2705 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2706 /// \brief Emit initial code for reduction variables. Creates reduction copies
2707 /// and initializes them with the values according to OpenMP standard.
2709 /// \param D Directive (possibly) with the 'reduction' clause.
2710 /// \param PrivateScope Private scope for capturing reduction variables for
2711 /// proper codegen in internal captured statement.
2713 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2714 OMPPrivateScope &PrivateScope);
2715 /// \brief Emit final update of reduction values to original variables at
2716 /// the end of the directive.
2718 /// \param D Directive that has at least one 'reduction' directives.
2719 /// \param ReductionKind The kind of reduction to perform.
2720 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D,
2721 const OpenMPDirectiveKind ReductionKind);
2722 /// \brief Emit initial code for linear variables. Creates private copies
2723 /// and initializes them with the values according to OpenMP standard.
2725 /// \param D Directive (possibly) with the 'linear' clause.
2726 void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2728 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2729 llvm::Value * /*OutlinedFn*/,
2730 const OMPTaskDataTy & /*Data*/)>
2732 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2733 const RegionCodeGenTy &BodyGen,
2734 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2736 void EmitOMPParallelDirective(const OMPParallelDirective &S);
2737 void EmitOMPSimdDirective(const OMPSimdDirective &S);
2738 void EmitOMPForDirective(const OMPForDirective &S);
2739 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2740 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2741 void EmitOMPSectionDirective(const OMPSectionDirective &S);
2742 void EmitOMPSingleDirective(const OMPSingleDirective &S);
2743 void EmitOMPMasterDirective(const OMPMasterDirective &S);
2744 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2745 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2746 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2747 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2748 void EmitOMPTaskDirective(const OMPTaskDirective &S);
2749 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2750 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2751 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2752 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2753 void EmitOMPFlushDirective(const OMPFlushDirective &S);
2754 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2755 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2756 void EmitOMPTargetDirective(const OMPTargetDirective &S);
2757 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2758 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2759 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2760 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2761 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2763 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2764 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2766 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2767 void EmitOMPCancelDirective(const OMPCancelDirective &S);
2768 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2769 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2770 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2771 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2772 void EmitOMPDistributeParallelForDirective(
2773 const OMPDistributeParallelForDirective &S);
2774 void EmitOMPDistributeParallelForSimdDirective(
2775 const OMPDistributeParallelForSimdDirective &S);
2776 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2777 void EmitOMPTargetParallelForSimdDirective(
2778 const OMPTargetParallelForSimdDirective &S);
2779 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2780 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2782 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2783 void EmitOMPTeamsDistributeParallelForSimdDirective(
2784 const OMPTeamsDistributeParallelForSimdDirective &S);
2785 void EmitOMPTeamsDistributeParallelForDirective(
2786 const OMPTeamsDistributeParallelForDirective &S);
2787 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
2788 void EmitOMPTargetTeamsDistributeDirective(
2789 const OMPTargetTeamsDistributeDirective &S);
2790 void EmitOMPTargetTeamsDistributeParallelForDirective(
2791 const OMPTargetTeamsDistributeParallelForDirective &S);
2792 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2793 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
2794 void EmitOMPTargetTeamsDistributeSimdDirective(
2795 const OMPTargetTeamsDistributeSimdDirective &S);
2797 /// Emit device code for the target directive.
2798 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM,
2799 StringRef ParentName,
2800 const OMPTargetDirective &S);
2802 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2803 const OMPTargetParallelDirective &S);
2805 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName,
2806 const OMPTargetTeamsDirective &S);
2807 /// \brief Emit inner loop of the worksharing/simd construct.
2809 /// \param S Directive, for which the inner loop must be emitted.
2810 /// \param RequiresCleanup true, if directive has some associated private
2812 /// \param LoopCond Bollean condition for loop continuation.
2813 /// \param IncExpr Increment expression for loop control variable.
2814 /// \param BodyGen Generator for the inner body of the inner loop.
2815 /// \param PostIncGen Genrator for post-increment code (required for ordered
2816 /// loop directvies).
2817 void EmitOMPInnerLoop(
2818 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2819 const Expr *IncExpr,
2820 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2821 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2823 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2824 /// Emit initial code for loop counters of loop-based directives.
2825 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2826 OMPPrivateScope &LoopScope);
2828 /// Helper for the OpenMP loop directives.
2829 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2831 /// \brief Emit code for the worksharing loop-based directive.
2832 /// \return true, if this construct has any lastprivate clause, false -
2834 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB,
2835 const CodeGenLoopBoundsTy &CodeGenLoopBounds,
2836 const CodeGenDispatchBoundsTy &CGDispatchBounds);
2839 /// Helpers for blocks
2840 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2842 /// Helpers for the OpenMP loop directives.
2843 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2844 void EmitOMPSimdFinal(
2845 const OMPLoopDirective &D,
2846 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2848 void EmitOMPDistributeLoop(const OMPLoopDirective &S,
2849 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr);
2851 /// struct with the values to be passed to the OpenMP loop-related functions
2852 struct OMPLoopArguments {
2853 /// loop lower bound
2854 Address LB = Address::invalid();
2855 /// loop upper bound
2856 Address UB = Address::invalid();
2858 Address ST = Address::invalid();
2859 /// isLastIteration argument for runtime functions
2860 Address IL = Address::invalid();
2861 /// Chunk value generated by sema
2862 llvm::Value *Chunk = nullptr;
2863 /// EnsureUpperBound
2864 Expr *EUB = nullptr;
2865 /// IncrementExpression
2866 Expr *IncExpr = nullptr;
2867 /// Loop initialization
2868 Expr *Init = nullptr;
2869 /// Loop exit condition
2870 Expr *Cond = nullptr;
2871 /// Update of LB after a whole chunk has been executed
2872 Expr *NextLB = nullptr;
2873 /// Update of UB after a whole chunk has been executed
2874 Expr *NextUB = nullptr;
2875 OMPLoopArguments() = default;
2876 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL,
2877 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr,
2878 Expr *IncExpr = nullptr, Expr *Init = nullptr,
2879 Expr *Cond = nullptr, Expr *NextLB = nullptr,
2880 Expr *NextUB = nullptr)
2881 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB),
2882 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB),
2885 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic,
2886 const OMPLoopDirective &S, OMPPrivateScope &LoopScope,
2887 const OMPLoopArguments &LoopArgs,
2888 const CodeGenLoopTy &CodeGenLoop,
2889 const CodeGenOrderedTy &CodeGenOrdered);
2890 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2891 bool IsMonotonic, const OMPLoopDirective &S,
2892 OMPPrivateScope &LoopScope, bool Ordered,
2893 const OMPLoopArguments &LoopArgs,
2894 const CodeGenDispatchBoundsTy &CGDispatchBounds);
2895 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind,
2896 const OMPLoopDirective &S,
2897 OMPPrivateScope &LoopScope,
2898 const OMPLoopArguments &LoopArgs,
2899 const CodeGenLoopTy &CodeGenLoopContent);
2900 /// \brief Emit code for sections directive.
2901 void EmitSections(const OMPExecutableDirective &S);
2905 //===--------------------------------------------------------------------===//
2906 // LValue Expression Emission
2907 //===--------------------------------------------------------------------===//
2909 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2910 RValue GetUndefRValue(QualType Ty);
2912 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2913 /// and issue an ErrorUnsupported style diagnostic (using the
2915 RValue EmitUnsupportedRValue(const Expr *E,
2918 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2919 /// an ErrorUnsupported style diagnostic (using the provided Name).
2920 LValue EmitUnsupportedLValue(const Expr *E,
2923 /// EmitLValue - Emit code to compute a designator that specifies the location
2924 /// of the expression.
2926 /// This can return one of two things: a simple address or a bitfield
2927 /// reference. In either case, the LLVM Value* in the LValue structure is
2928 /// guaranteed to be an LLVM pointer type.
2930 /// If this returns a bitfield reference, nothing about the pointee type of
2931 /// the LLVM value is known: For example, it may not be a pointer to an
2934 /// If this returns a normal address, and if the lvalue's C type is fixed
2935 /// size, this method guarantees that the returned pointer type will point to
2936 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
2937 /// variable length type, this is not possible.
2939 LValue EmitLValue(const Expr *E);
2941 /// \brief Same as EmitLValue but additionally we generate checking code to
2942 /// guard against undefined behavior. This is only suitable when we know
2943 /// that the address will be used to access the object.
2944 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2946 RValue convertTempToRValue(Address addr, QualType type,
2947 SourceLocation Loc);
2949 void EmitAtomicInit(Expr *E, LValue lvalue);
2951 bool LValueIsSuitableForInlineAtomic(LValue Src);
2953 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2954 AggValueSlot Slot = AggValueSlot::ignored());
2956 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2957 llvm::AtomicOrdering AO, bool IsVolatile = false,
2958 AggValueSlot slot = AggValueSlot::ignored());
2960 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2962 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2963 bool IsVolatile, bool isInit);
2965 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2966 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2967 llvm::AtomicOrdering Success =
2968 llvm::AtomicOrdering::SequentiallyConsistent,
2969 llvm::AtomicOrdering Failure =
2970 llvm::AtomicOrdering::SequentiallyConsistent,
2971 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2973 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2974 const llvm::function_ref<RValue(RValue)> &UpdateOp,
2977 /// EmitToMemory - Change a scalar value from its value
2978 /// representation to its in-memory representation.
2979 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2981 /// EmitFromMemory - Change a scalar value from its memory
2982 /// representation to its value representation.
2983 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2985 /// Check if the scalar \p Value is within the valid range for the given
2988 /// Returns true if a check is needed (even if the range is unknown).
2989 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
2990 SourceLocation Loc);
2992 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2993 /// care to appropriately convert from the memory representation to
2994 /// the LLVM value representation.
2995 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2997 LValueBaseInfo BaseInfo =
2998 LValueBaseInfo(AlignmentSource::Type),
2999 llvm::MDNode *TBAAInfo = nullptr,
3000 QualType TBAABaseTy = QualType(),
3001 uint64_t TBAAOffset = 0,
3002 bool isNontemporal = false);
3004 /// EmitLoadOfScalar - Load a scalar value from an address, taking
3005 /// care to appropriately convert from the memory representation to
3006 /// the LLVM value representation. The l-value must be a simple
3008 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
3010 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3011 /// care to appropriately convert from the memory representation to
3012 /// the LLVM value representation.
3013 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
3014 bool Volatile, QualType Ty,
3015 LValueBaseInfo BaseInfo =
3016 LValueBaseInfo(AlignmentSource::Type),
3017 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
3018 QualType TBAABaseTy = QualType(),
3019 uint64_t TBAAOffset = 0, bool isNontemporal = false);
3021 /// EmitStoreOfScalar - Store a scalar value to an address, taking
3022 /// care to appropriately convert from the memory representation to
3023 /// the LLVM value representation. The l-value must be a simple
3024 /// l-value. The isInit flag indicates whether this is an initialization.
3025 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
3026 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
3028 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
3029 /// this method emits the address of the lvalue, then loads the result as an
3030 /// rvalue, returning the rvalue.
3031 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
3032 RValue EmitLoadOfExtVectorElementLValue(LValue V);
3033 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc);
3034 RValue EmitLoadOfGlobalRegLValue(LValue LV);
3036 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
3037 /// lvalue, where both are guaranteed to the have the same type, and that type
3039 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
3040 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
3041 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
3043 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
3044 /// as EmitStoreThroughLValue.
3046 /// \param Result [out] - If non-null, this will be set to a Value* for the
3047 /// bit-field contents after the store, appropriate for use as the result of
3048 /// an assignment to the bit-field.
3049 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
3050 llvm::Value **Result=nullptr);
3052 /// Emit an l-value for an assignment (simple or compound) of complex type.
3053 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
3054 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
3055 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
3056 llvm::Value *&Result);
3058 // Note: only available for agg return types
3059 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
3060 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
3061 // Note: only available for agg return types
3062 LValue EmitCallExprLValue(const CallExpr *E);
3063 // Note: only available for agg return types
3064 LValue EmitVAArgExprLValue(const VAArgExpr *E);
3065 LValue EmitDeclRefLValue(const DeclRefExpr *E);
3066 LValue EmitStringLiteralLValue(const StringLiteral *E);
3067 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
3068 LValue EmitPredefinedLValue(const PredefinedExpr *E);
3069 LValue EmitUnaryOpLValue(const UnaryOperator *E);
3070 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3071 bool Accessed = false);
3072 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3073 bool IsLowerBound = true);
3074 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
3075 LValue EmitMemberExpr(const MemberExpr *E);
3076 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
3077 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
3078 LValue EmitInitListLValue(const InitListExpr *E);
3079 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
3080 LValue EmitCastLValue(const CastExpr *E);
3081 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3082 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
3084 Address EmitExtVectorElementLValue(LValue V);
3086 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
3088 Address EmitArrayToPointerDecay(const Expr *Array,
3089 LValueBaseInfo *BaseInfo = nullptr);
3091 class ConstantEmission {
3092 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
3093 ConstantEmission(llvm::Constant *C, bool isReference)
3094 : ValueAndIsReference(C, isReference) {}
3096 ConstantEmission() {}
3097 static ConstantEmission forReference(llvm::Constant *C) {
3098 return ConstantEmission(C, true);
3100 static ConstantEmission forValue(llvm::Constant *C) {
3101 return ConstantEmission(C, false);
3104 explicit operator bool() const {
3105 return ValueAndIsReference.getOpaqueValue() != nullptr;
3108 bool isReference() const { return ValueAndIsReference.getInt(); }
3109 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
3110 assert(isReference());
3111 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
3112 refExpr->getType());
3115 llvm::Constant *getValue() const {
3116 assert(!isReference());
3117 return ValueAndIsReference.getPointer();
3121 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
3123 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
3124 AggValueSlot slot = AggValueSlot::ignored());
3125 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
3127 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3128 const ObjCIvarDecl *Ivar);
3129 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
3130 LValue EmitLValueForLambdaField(const FieldDecl *Field);
3132 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
3133 /// if the Field is a reference, this will return the address of the reference
3134 /// and not the address of the value stored in the reference.
3135 LValue EmitLValueForFieldInitialization(LValue Base,
3136 const FieldDecl* Field);
3138 LValue EmitLValueForIvar(QualType ObjectTy,
3139 llvm::Value* Base, const ObjCIvarDecl *Ivar,
3140 unsigned CVRQualifiers);
3142 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
3143 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
3144 LValue EmitLambdaLValue(const LambdaExpr *E);
3145 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
3146 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3148 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3149 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3150 LValue EmitStmtExprLValue(const StmtExpr *E);
3151 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3152 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3153 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3155 //===--------------------------------------------------------------------===//
3156 // Scalar Expression Emission
3157 //===--------------------------------------------------------------------===//
3159 /// EmitCall - Generate a call of the given function, expecting the given
3160 /// result type, and using the given argument list which specifies both the
3161 /// LLVM arguments and the types they were derived from.
3162 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3163 ReturnValueSlot ReturnValue, const CallArgList &Args,
3164 llvm::Instruction **callOrInvoke = nullptr);
3166 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3167 ReturnValueSlot ReturnValue,
3168 llvm::Value *Chain = nullptr);
3169 RValue EmitCallExpr(const CallExpr *E,
3170 ReturnValueSlot ReturnValue = ReturnValueSlot());
3171 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3172 CGCallee EmitCallee(const Expr *E);
3174 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3176 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3177 const Twine &name = "");
3178 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3179 ArrayRef<llvm::Value*> args,
3180 const Twine &name = "");
3181 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3182 const Twine &name = "");
3183 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3184 ArrayRef<llvm::Value*> args,
3185 const Twine &name = "");
3187 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3188 ArrayRef<llvm::Value *> Args,
3189 const Twine &Name = "");
3190 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3191 ArrayRef<llvm::Value*> args,
3192 const Twine &name = "");
3193 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3194 const Twine &name = "");
3195 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3196 ArrayRef<llvm::Value*> args);
3198 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3199 NestedNameSpecifier *Qual,
3202 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3204 const CXXRecordDecl *RD);
3207 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3208 const CGCallee &Callee,
3209 ReturnValueSlot ReturnValue, llvm::Value *This,
3210 llvm::Value *ImplicitParam,
3211 QualType ImplicitParamTy, const CallExpr *E,
3212 CallArgList *RtlArgs);
3213 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3214 const CGCallee &Callee,
3215 llvm::Value *This, llvm::Value *ImplicitParam,
3216 QualType ImplicitParamTy, const CallExpr *E,
3218 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3219 ReturnValueSlot ReturnValue);
3220 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3221 const CXXMethodDecl *MD,
3222 ReturnValueSlot ReturnValue,
3224 NestedNameSpecifier *Qualifier,
3225 bool IsArrow, const Expr *Base);
3226 // Compute the object pointer.
3227 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3228 llvm::Value *memberPtr,
3229 const MemberPointerType *memberPtrType,
3230 LValueBaseInfo *BaseInfo = nullptr);
3231 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3232 ReturnValueSlot ReturnValue);
3234 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3235 const CXXMethodDecl *MD,
3236 ReturnValueSlot ReturnValue);
3237 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3239 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3240 ReturnValueSlot ReturnValue);
3242 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E,
3243 ReturnValueSlot ReturnValue);
3245 RValue EmitBuiltinExpr(const FunctionDecl *FD,
3246 unsigned BuiltinID, const CallExpr *E,
3247 ReturnValueSlot ReturnValue);
3249 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3251 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3252 /// is unhandled by the current target.
3253 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3255 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3256 const llvm::CmpInst::Predicate Fp,
3257 const llvm::CmpInst::Predicate Ip,
3258 const llvm::Twine &Name = "");
3259 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3261 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3262 unsigned LLVMIntrinsic,
3263 unsigned AltLLVMIntrinsic,
3264 const char *NameHint,
3267 SmallVectorImpl<llvm::Value *> &Ops,
3268 Address PtrOp0, Address PtrOp1);
3269 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3270 unsigned Modifier, llvm::Type *ArgTy,
3272 llvm::Value *EmitNeonCall(llvm::Function *F,
3273 SmallVectorImpl<llvm::Value*> &O,
3275 unsigned shift = 0, bool rightshift = false);
3276 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3277 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3278 bool negateForRightShift);
3279 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3280 llvm::Type *Ty, bool usgn, const char *name);
3281 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3282 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3284 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3285 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3286 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3287 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3288 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3289 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3290 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3294 enum class MSVCIntrin;
3297 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3299 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args);
3301 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3302 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3303 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3304 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3305 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3306 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3307 const ObjCMethodDecl *MethodWithObjects);
3308 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3309 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3310 ReturnValueSlot Return = ReturnValueSlot());
3312 /// Retrieves the default cleanup kind for an ARC cleanup.
3313 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3314 CleanupKind getARCCleanupKind() {
3315 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3316 ? NormalAndEHCleanup : NormalCleanup;
3320 void EmitARCInitWeak(Address addr, llvm::Value *value);
3321 void EmitARCDestroyWeak(Address addr);
3322 llvm::Value *EmitARCLoadWeak(Address addr);
3323 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3324 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3325 void EmitARCCopyWeak(Address dst, Address src);
3326 void EmitARCMoveWeak(Address dst, Address src);
3327 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3328 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3329 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3330 bool resultIgnored);
3331 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3332 bool resultIgnored);
3333 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3334 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3335 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3336 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3337 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3338 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3339 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3340 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3341 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3342 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3344 std::pair<LValue,llvm::Value*>
3345 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3346 std::pair<LValue,llvm::Value*>
3347 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3348 std::pair<LValue,llvm::Value*>
3349 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3351 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3352 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3353 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3355 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3356 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3357 bool allowUnsafeClaim);
3358 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3359 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3360 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3362 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3364 static Destroyer destroyARCStrongImprecise;
3365 static Destroyer destroyARCStrongPrecise;
3366 static Destroyer destroyARCWeak;
3367 static Destroyer emitARCIntrinsicUse;
3369 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3370 llvm::Value *EmitObjCAutoreleasePoolPush();
3371 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3372 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3373 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3375 /// \brief Emits a reference binding to the passed in expression.
3376 RValue EmitReferenceBindingToExpr(const Expr *E);
3378 //===--------------------------------------------------------------------===//
3379 // Expression Emission
3380 //===--------------------------------------------------------------------===//
3382 // Expressions are broken into three classes: scalar, complex, aggregate.
3384 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3385 /// scalar type, returning the result.
3386 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3388 /// Emit a conversion from the specified type to the specified destination
3389 /// type, both of which are LLVM scalar types.
3390 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3391 QualType DstTy, SourceLocation Loc);
3393 /// Emit a conversion from the specified complex type to the specified
3394 /// destination type, where the destination type is an LLVM scalar type.
3395 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3397 SourceLocation Loc);
3399 /// EmitAggExpr - Emit the computation of the specified expression
3400 /// of aggregate type. The result is computed into the given slot,
3401 /// which may be null to indicate that the value is not needed.
3402 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3404 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3405 /// aggregate type into a temporary LValue.
3406 LValue EmitAggExprToLValue(const Expr *E);
3408 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3409 /// make sure it survives garbage collection until this point.
3410 void EmitExtendGCLifetime(llvm::Value *object);
3412 /// EmitComplexExpr - Emit the computation of the specified expression of
3413 /// complex type, returning the result.
3414 ComplexPairTy EmitComplexExpr(const Expr *E,
3415 bool IgnoreReal = false,
3416 bool IgnoreImag = false);
3418 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3419 /// type and place its result into the specified l-value.
3420 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3422 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3423 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3425 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3426 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3428 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3429 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3431 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3432 /// global variable that has already been created for it. If the initializer
3433 /// has a different type than GV does, this may free GV and return a different
3434 /// one. Otherwise it just returns GV.
3435 llvm::GlobalVariable *
3436 AddInitializerToStaticVarDecl(const VarDecl &D,
3437 llvm::GlobalVariable *GV);
3440 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3441 /// variable with global storage.
3442 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3445 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3446 llvm::Constant *Addr);
3448 /// Call atexit() with a function that passes the given argument to
3449 /// the given function.
3450 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3451 llvm::Constant *addr);
3453 /// Emit code in this function to perform a guarded variable
3454 /// initialization. Guarded initializations are used when it's not
3455 /// possible to prove that an initialization will be done exactly
3456 /// once, e.g. with a static local variable or a static data member
3457 /// of a class template.
3458 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3461 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3463 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3464 ArrayRef<llvm::Function *> CXXThreadLocals,
3465 Address Guard = Address::invalid());
3467 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3469 void GenerateCXXGlobalDtorsFunc(
3471 const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>>
3474 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3476 llvm::GlobalVariable *Addr,
3479 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3481 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3483 void enterFullExpression(const ExprWithCleanups *E) {
3484 if (E->getNumObjects() == 0) return;
3485 enterNonTrivialFullExpression(E);
3487 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3489 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3491 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3493 RValue EmitAtomicExpr(AtomicExpr *E);
3495 //===--------------------------------------------------------------------===//
3496 // Annotations Emission
3497 //===--------------------------------------------------------------------===//
3499 /// Emit an annotation call (intrinsic or builtin).
3500 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3501 llvm::Value *AnnotatedVal,
3502 StringRef AnnotationStr,
3503 SourceLocation Location);
3505 /// Emit local annotations for the local variable V, declared by D.
3506 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3508 /// Emit field annotations for the given field & value. Returns the
3509 /// annotation result.
3510 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3512 //===--------------------------------------------------------------------===//
3514 //===--------------------------------------------------------------------===//
3516 /// ContainsLabel - Return true if the statement contains a label in it. If
3517 /// this statement is not executed normally, it not containing a label means
3518 /// that we can just remove the code.
3519 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3521 /// containsBreak - Return true if the statement contains a break out of it.
3522 /// If the statement (recursively) contains a switch or loop with a break
3523 /// inside of it, this is fine.
3524 static bool containsBreak(const Stmt *S);
3526 /// Determine if the given statement might introduce a declaration into the
3527 /// current scope, by being a (possibly-labelled) DeclStmt.
3528 static bool mightAddDeclToScope(const Stmt *S);
3530 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3531 /// to a constant, or if it does but contains a label, return false. If it
3532 /// constant folds return true and set the boolean result in Result.
3533 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3534 bool AllowLabels = false);
3536 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3537 /// to a constant, or if it does but contains a label, return false. If it
3538 /// constant folds return true and set the folded value.
3539 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3540 bool AllowLabels = false);
3542 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3543 /// if statement) to the specified blocks. Based on the condition, this might
3544 /// try to simplify the codegen of the conditional based on the branch.
3545 /// TrueCount should be the number of times we expect the condition to
3546 /// evaluate to true based on PGO data.
3547 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3548 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3550 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is
3551 /// nonnull, if \p LHS is marked _Nonnull.
3552 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc);
3554 /// \brief Emit a description of a type in a format suitable for passing to
3555 /// a runtime sanitizer handler.
3556 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3558 /// \brief Convert a value into a format suitable for passing to a runtime
3559 /// sanitizer handler.
3560 llvm::Value *EmitCheckValue(llvm::Value *V);
3562 /// \brief Emit a description of a source location in a format suitable for
3563 /// passing to a runtime sanitizer handler.
3564 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3566 /// \brief Create a basic block that will call a handler function in a
3567 /// sanitizer runtime with the provided arguments, and create a conditional
3569 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3570 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3571 ArrayRef<llvm::Value *> DynamicArgs);
3573 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3574 /// if Cond if false.
3575 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3576 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3577 ArrayRef<llvm::Constant *> StaticArgs);
3579 /// \brief Create a basic block that will call the trap intrinsic, and emit a
3580 /// conditional branch to it, for the -ftrapv checks.
3581 void EmitTrapCheck(llvm::Value *Checked);
3583 /// \brief Emit a call to trap or debugtrap and attach function attribute
3584 /// "trap-func-name" if specified.
3585 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3587 /// \brief Emit a stub for the cross-DSO CFI check function.
3588 void EmitCfiCheckStub();
3590 /// \brief Emit a cross-DSO CFI failure handling function.
3591 void EmitCfiCheckFail();
3593 /// \brief Create a check for a function parameter that may potentially be
3594 /// declared as non-null.
3595 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3596 AbstractCallee AC, unsigned ParmNum);
3598 /// EmitCallArg - Emit a single call argument.
3599 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3601 /// EmitDelegateCallArg - We are performing a delegate call; that
3602 /// is, the current function is delegating to another one. Produce
3603 /// a r-value suitable for passing the given parameter.
3604 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3605 SourceLocation loc);
3607 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3608 /// point operation, expressed as the maximum relative error in ulp.
3609 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3612 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3613 void EmitReturnOfRValue(RValue RV, QualType Ty);
3615 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3617 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3618 DeferredReplacements;
3620 /// Set the address of a local variable.
3621 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3622 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3623 LocalDeclMap.insert({VD, Addr});
3626 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3627 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3629 /// \param AI - The first function argument of the expansion.
3630 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3631 SmallVectorImpl<llvm::Value *>::iterator &AI);
3633 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3634 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3635 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3636 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3637 SmallVectorImpl<llvm::Value *> &IRCallArgs,
3638 unsigned &IRCallArgPos);
3640 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3641 const Expr *InputExpr, std::string &ConstraintStr);
3643 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3644 LValue InputValue, QualType InputType,
3645 std::string &ConstraintStr,
3646 SourceLocation Loc);
3648 /// \brief Attempts to statically evaluate the object size of E. If that
3649 /// fails, emits code to figure the size of E out for us. This is
3650 /// pass_object_size aware.
3652 /// If EmittedExpr is non-null, this will use that instead of re-emitting E.
3653 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3654 llvm::IntegerType *ResType,
3655 llvm::Value *EmittedE);
3657 /// \brief Emits the size of E, as required by __builtin_object_size. This
3658 /// function is aware of pass_object_size parameters, and will act accordingly
3659 /// if E is a parameter with the pass_object_size attribute.
3660 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3661 llvm::IntegerType *ResType,
3662 llvm::Value *EmittedE);
3666 // Determine whether the given argument is an Objective-C method
3667 // that may have type parameters in its signature.
3668 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3669 const DeclContext *dc = method->getDeclContext();
3670 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3671 return classDecl->getTypeParamListAsWritten();
3674 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3675 return catDecl->getTypeParamList();
3681 template<typename T>
3682 static bool isObjCMethodWithTypeParams(const T *) { return false; }
3685 enum class EvaluationOrder {
3686 ///! No language constraints on evaluation order.
3688 ///! Language semantics require left-to-right evaluation.
3690 ///! Language semantics require right-to-left evaluation.
3694 /// EmitCallArgs - Emit call arguments for a function.
3695 template <typename T>
3696 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3697 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3698 AbstractCallee AC = AbstractCallee(),
3699 unsigned ParamsToSkip = 0,
3700 EvaluationOrder Order = EvaluationOrder::Default) {
3701 SmallVector<QualType, 16> ArgTypes;
3702 CallExpr::const_arg_iterator Arg = ArgRange.begin();
3704 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3705 "Can't skip parameters if type info is not provided");
3706 if (CallArgTypeInfo) {
3708 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3711 // First, use the argument types that the type info knows about
3712 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3713 E = CallArgTypeInfo->param_type_end();
3714 I != E; ++I, ++Arg) {
3715 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3716 assert((isGenericMethod ||
3717 ((*I)->isVariablyModifiedType() ||
3718 (*I).getNonReferenceType()->isObjCRetainableType() ||
3720 .getCanonicalType((*I).getNonReferenceType())
3723 .getCanonicalType((*Arg)->getType())
3725 "type mismatch in call argument!");
3726 ArgTypes.push_back(*I);
3730 // Either we've emitted all the call args, or we have a call to variadic
3732 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3733 CallArgTypeInfo->isVariadic()) &&
3734 "Extra arguments in non-variadic function!");
3736 // If we still have any arguments, emit them using the type of the argument.
3737 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3738 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
3740 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order);
3743 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3744 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3745 AbstractCallee AC = AbstractCallee(),
3746 unsigned ParamsToSkip = 0,
3747 EvaluationOrder Order = EvaluationOrder::Default);
3749 /// EmitPointerWithAlignment - Given an expression with a pointer type,
3750 /// emit the value and compute our best estimate of the alignment of the
3753 /// \param BaseInfo - If non-null, this will be initialized with
3754 /// information about the source of the alignment and the may-alias
3755 /// attribute. Note that this function will conservatively fall back on
3756 /// the type when it doesn't recognize the expression and may-alias will
3757 /// be set to false.
3759 /// One reasonable way to use this information is when there's a language
3760 /// guarantee that the pointer must be aligned to some stricter value, and
3761 /// we're simply trying to ensure that sufficiently obvious uses of under-
3762 /// aligned objects don't get miscompiled; for example, a placement new
3763 /// into the address of a local variable. In such a case, it's quite
3764 /// reasonable to just ignore the returned alignment when it isn't from an
3765 /// explicit source.
3766 Address EmitPointerWithAlignment(const Expr *Addr,
3767 LValueBaseInfo *BaseInfo = nullptr);
3769 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3772 QualType getVarArgType(const Expr *Arg);
3774 const TargetCodeGenInfo &getTargetHooks() const {
3775 return CGM.getTargetCodeGenInfo();
3778 void EmitDeclMetadata();
3780 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3781 const AutoVarEmission &emission);
3783 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3785 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3788 /// Helper class with most of the code for saving a value for a
3789 /// conditional expression cleanup.
3790 struct DominatingLLVMValue {
3791 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3793 /// Answer whether the given value needs extra work to be saved.
3794 static bool needsSaving(llvm::Value *value) {
3795 // If it's not an instruction, we don't need to save.
3796 if (!isa<llvm::Instruction>(value)) return false;
3798 // If it's an instruction in the entry block, we don't need to save.
3799 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3800 return (block != &block->getParent()->getEntryBlock());
3803 /// Try to save the given value.
3804 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3805 if (!needsSaving(value)) return saved_type(value, false);
3807 // Otherwise, we need an alloca.
3808 auto align = CharUnits::fromQuantity(
3809 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3811 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3812 CGF.Builder.CreateStore(value, alloca);
3814 return saved_type(alloca.getPointer(), true);
3817 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3818 // If the value says it wasn't saved, trust that it's still dominating.
3819 if (!value.getInt()) return value.getPointer();
3821 // Otherwise, it should be an alloca instruction, as set up in save().
3822 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3823 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3827 /// A partial specialization of DominatingValue for llvm::Values that
3828 /// might be llvm::Instructions.
3829 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3831 static type restore(CodeGenFunction &CGF, saved_type value) {
3832 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3836 /// A specialization of DominatingValue for Address.
3837 template <> struct DominatingValue<Address> {
3838 typedef Address type;
3841 DominatingLLVMValue::saved_type SavedValue;
3842 CharUnits Alignment;
3845 static bool needsSaving(type value) {
3846 return DominatingLLVMValue::needsSaving(value.getPointer());
3848 static saved_type save(CodeGenFunction &CGF, type value) {
3849 return { DominatingLLVMValue::save(CGF, value.getPointer()),
3850 value.getAlignment() };
3852 static type restore(CodeGenFunction &CGF, saved_type value) {
3853 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3858 /// A specialization of DominatingValue for RValue.
3859 template <> struct DominatingValue<RValue> {
3860 typedef RValue type;
3862 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3863 AggregateAddress, ComplexAddress };
3867 unsigned Align : 29;
3868 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3869 : Value(v), K(k), Align(a) {}
3872 static bool needsSaving(RValue value);
3873 static saved_type save(CodeGenFunction &CGF, RValue value);
3874 RValue restore(CodeGenFunction &CGF);
3876 // implementations in CGCleanup.cpp
3879 static bool needsSaving(type value) {
3880 return saved_type::needsSaving(value);
3882 static saved_type save(CodeGenFunction &CGF, type value) {
3883 return saved_type::save(CGF, value);
3885 static type restore(CodeGenFunction &CGF, saved_type value) {
3886 return value.restore(CGF);
3890 } // end namespace CodeGen
3891 } // end namespace clang