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(NonnullArg, nonnull_arg, 0) \
119 SANITIZER_CHECK(NonnullReturn, nonnull_return, 0) \
120 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \
121 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \
122 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \
123 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \
124 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0)
126 enum SanitizerHandler {
127 #define SANITIZER_CHECK(Enum, Name, Version) Enum,
128 LIST_SANITIZER_CHECKS
129 #undef SANITIZER_CHECK
132 /// CodeGenFunction - This class organizes the per-function state that is used
133 /// while generating LLVM code.
134 class CodeGenFunction : public CodeGenTypeCache {
135 CodeGenFunction(const CodeGenFunction &) = delete;
136 void operator=(const CodeGenFunction &) = delete;
138 friend class CGCXXABI;
140 /// A jump destination is an abstract label, branching to which may
141 /// require a jump out through normal cleanups.
143 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
144 JumpDest(llvm::BasicBlock *Block,
145 EHScopeStack::stable_iterator Depth,
147 : Block(Block), ScopeDepth(Depth), Index(Index) {}
149 bool isValid() const { return Block != nullptr; }
150 llvm::BasicBlock *getBlock() const { return Block; }
151 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
152 unsigned getDestIndex() const { return Index; }
154 // This should be used cautiously.
155 void setScopeDepth(EHScopeStack::stable_iterator depth) {
160 llvm::BasicBlock *Block;
161 EHScopeStack::stable_iterator ScopeDepth;
165 CodeGenModule &CGM; // Per-module state.
166 const TargetInfo &Target;
168 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
169 LoopInfoStack LoopStack;
172 // Stores variables for which we can't generate correct lifetime markers
174 VarBypassDetector Bypasses;
176 /// \brief CGBuilder insert helper. This function is called after an
177 /// instruction is created using Builder.
178 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
179 llvm::BasicBlock *BB,
180 llvm::BasicBlock::iterator InsertPt) const;
182 /// CurFuncDecl - Holds the Decl for the current outermost
183 /// non-closure context.
184 const Decl *CurFuncDecl;
185 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
186 const Decl *CurCodeDecl;
187 const CGFunctionInfo *CurFnInfo;
189 llvm::Function *CurFn;
191 // Holds coroutine data if the current function is a coroutine. We use a
192 // wrapper to manage its lifetime, so that we don't have to define CGCoroData
195 std::unique_ptr<CGCoroData> Data;
201 /// CurGD - The GlobalDecl for the current function being compiled.
204 /// PrologueCleanupDepth - The cleanup depth enclosing all the
205 /// cleanups associated with the parameters.
206 EHScopeStack::stable_iterator PrologueCleanupDepth;
208 /// ReturnBlock - Unified return block.
209 JumpDest ReturnBlock;
211 /// ReturnValue - The temporary alloca to hold the return
212 /// value. This is invalid iff the function has no return value.
215 /// AllocaInsertPoint - This is an instruction in the entry block before which
216 /// we prefer to insert allocas.
217 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
219 /// \brief API for captured statement code generation.
220 class CGCapturedStmtInfo {
222 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
223 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
224 explicit CGCapturedStmtInfo(const CapturedStmt &S,
225 CapturedRegionKind K = CR_Default)
226 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
228 RecordDecl::field_iterator Field =
229 S.getCapturedRecordDecl()->field_begin();
230 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
232 I != E; ++I, ++Field) {
233 if (I->capturesThis())
234 CXXThisFieldDecl = *Field;
235 else if (I->capturesVariable())
236 CaptureFields[I->getCapturedVar()] = *Field;
237 else if (I->capturesVariableByCopy())
238 CaptureFields[I->getCapturedVar()] = *Field;
242 virtual ~CGCapturedStmtInfo();
244 CapturedRegionKind getKind() const { return Kind; }
246 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
247 // \brief Retrieve the value of the context parameter.
248 virtual llvm::Value *getContextValue() const { return ThisValue; }
250 /// \brief Lookup the captured field decl for a variable.
251 virtual const FieldDecl *lookup(const VarDecl *VD) const {
252 return CaptureFields.lookup(VD);
255 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
256 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
258 static bool classof(const CGCapturedStmtInfo *) {
262 /// \brief Emit the captured statement body.
263 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
264 CGF.incrementProfileCounter(S);
268 /// \brief Get the name of the capture helper.
269 virtual StringRef getHelperName() const { return "__captured_stmt"; }
272 /// \brief The kind of captured statement being generated.
273 CapturedRegionKind Kind;
275 /// \brief Keep the map between VarDecl and FieldDecl.
276 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
278 /// \brief The base address of the captured record, passed in as the first
279 /// argument of the parallel region function.
280 llvm::Value *ThisValue;
282 /// \brief Captured 'this' type.
283 FieldDecl *CXXThisFieldDecl;
285 CGCapturedStmtInfo *CapturedStmtInfo;
287 /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
288 class CGCapturedStmtRAII {
290 CodeGenFunction &CGF;
291 CGCapturedStmtInfo *PrevCapturedStmtInfo;
293 CGCapturedStmtRAII(CodeGenFunction &CGF,
294 CGCapturedStmtInfo *NewCapturedStmtInfo)
295 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
296 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
298 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
301 /// \brief Sanitizers enabled for this function.
302 SanitizerSet SanOpts;
304 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
305 bool IsSanitizerScope;
307 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
308 class SanitizerScope {
309 CodeGenFunction *CGF;
311 SanitizerScope(CodeGenFunction *CGF);
315 /// In C++, whether we are code generating a thunk. This controls whether we
316 /// should emit cleanups.
319 /// In ARC, whether we should autorelease the return value.
320 bool AutoreleaseResult;
322 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
323 /// potentially set the return value.
326 const FunctionDecl *CurSEHParent = nullptr;
328 /// True if the current function is an outlined SEH helper. This can be a
329 /// finally block or filter expression.
330 bool IsOutlinedSEHHelper;
332 const CodeGen::CGBlockInfo *BlockInfo;
333 llvm::Value *BlockPointer;
335 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
336 FieldDecl *LambdaThisCaptureField;
338 /// \brief A mapping from NRVO variables to the flags used to indicate
339 /// when the NRVO has been applied to this variable.
340 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
342 EHScopeStack EHStack;
343 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
344 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
346 llvm::Instruction *CurrentFuncletPad = nullptr;
348 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
353 CallLifetimeEnd(Address addr, llvm::Value *size)
354 : Addr(addr.getPointer()), Size(size) {}
356 void Emit(CodeGenFunction &CGF, Flags flags) override {
357 CGF.EmitLifetimeEnd(Size, Addr);
361 /// Header for data within LifetimeExtendedCleanupStack.
362 struct LifetimeExtendedCleanupHeader {
363 /// The size of the following cleanup object.
365 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
368 size_t getSize() const { return Size; }
369 CleanupKind getKind() const { return Kind; }
372 /// i32s containing the indexes of the cleanup destinations.
373 llvm::AllocaInst *NormalCleanupDest;
375 unsigned NextCleanupDestIndex;
377 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
378 CGBlockInfo *FirstBlockInfo;
380 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
381 llvm::BasicBlock *EHResumeBlock;
383 /// The exception slot. All landing pads write the current exception pointer
384 /// into this alloca.
385 llvm::Value *ExceptionSlot;
387 /// The selector slot. Under the MandatoryCleanup model, all landing pads
388 /// write the current selector value into this alloca.
389 llvm::AllocaInst *EHSelectorSlot;
391 /// A stack of exception code slots. Entering an __except block pushes a slot
392 /// on the stack and leaving pops one. The __exception_code() intrinsic loads
393 /// a value from the top of the stack.
394 SmallVector<Address, 1> SEHCodeSlotStack;
396 /// Value returned by __exception_info intrinsic.
397 llvm::Value *SEHInfo = nullptr;
399 /// Emits a landing pad for the current EH stack.
400 llvm::BasicBlock *EmitLandingPad();
402 llvm::BasicBlock *getInvokeDestImpl();
405 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
406 return DominatingValue<T>::save(*this, value);
410 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
412 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
414 /// A class controlling the emission of a finally block.
416 /// Where the catchall's edge through the cleanup should go.
417 JumpDest RethrowDest;
419 /// A function to call to enter the catch.
420 llvm::Constant *BeginCatchFn;
422 /// An i1 variable indicating whether or not the @finally is
423 /// running for an exception.
424 llvm::AllocaInst *ForEHVar;
426 /// An i8* variable into which the exception pointer to rethrow
428 llvm::AllocaInst *SavedExnVar;
431 void enter(CodeGenFunction &CGF, const Stmt *Finally,
432 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
433 llvm::Constant *rethrowFn);
434 void exit(CodeGenFunction &CGF);
437 /// Returns true inside SEH __try blocks.
438 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
440 /// Returns true while emitting a cleanuppad.
441 bool isCleanupPadScope() const {
442 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad);
445 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
446 /// current full-expression. Safe against the possibility that
447 /// we're currently inside a conditionally-evaluated expression.
448 template <class T, class... As>
449 void pushFullExprCleanup(CleanupKind kind, As... A) {
450 // If we're not in a conditional branch, or if none of the
451 // arguments requires saving, then use the unconditional cleanup.
452 if (!isInConditionalBranch())
453 return EHStack.pushCleanup<T>(kind, A...);
455 // Stash values in a tuple so we can guarantee the order of saves.
456 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
457 SavedTuple Saved{saveValueInCond(A)...};
459 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
460 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
461 initFullExprCleanup();
464 /// \brief Queue a cleanup to be pushed after finishing the current
466 template <class T, class... As>
467 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
468 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
470 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
472 size_t OldSize = LifetimeExtendedCleanupStack.size();
473 LifetimeExtendedCleanupStack.resize(
474 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
476 static_assert(sizeof(Header) % alignof(T) == 0,
477 "Cleanup will be allocated on misaligned address");
478 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
479 new (Buffer) LifetimeExtendedCleanupHeader(Header);
480 new (Buffer + sizeof(Header)) T(A...);
483 /// Set up the last cleaup that was pushed as a conditional
484 /// full-expression cleanup.
485 void initFullExprCleanup();
487 /// PushDestructorCleanup - Push a cleanup to call the
488 /// complete-object destructor of an object of the given type at the
489 /// given address. Does nothing if T is not a C++ class type with a
490 /// non-trivial destructor.
491 void PushDestructorCleanup(QualType T, Address Addr);
493 /// PushDestructorCleanup - Push a cleanup to call the
494 /// complete-object variant of the given destructor on the object at
495 /// the given address.
496 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, Address Addr);
498 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
499 /// process all branch fixups.
500 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
502 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
503 /// The block cannot be reactivated. Pops it if it's the top of the
506 /// \param DominatingIP - An instruction which is known to
507 /// dominate the current IP (if set) and which lies along
508 /// all paths of execution between the current IP and the
509 /// the point at which the cleanup comes into scope.
510 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
511 llvm::Instruction *DominatingIP);
513 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
514 /// Cannot be used to resurrect a deactivated cleanup.
516 /// \param DominatingIP - An instruction which is known to
517 /// dominate the current IP (if set) and which lies along
518 /// all paths of execution between the current IP and the
519 /// the point at which the cleanup comes into scope.
520 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
521 llvm::Instruction *DominatingIP);
523 /// \brief Enters a new scope for capturing cleanups, all of which
524 /// will be executed once the scope is exited.
525 class RunCleanupsScope {
526 EHScopeStack::stable_iterator CleanupStackDepth;
527 size_t LifetimeExtendedCleanupStackSize;
528 bool OldDidCallStackSave;
533 RunCleanupsScope(const RunCleanupsScope &) = delete;
534 void operator=(const RunCleanupsScope &) = delete;
537 CodeGenFunction& CGF;
540 /// \brief Enter a new cleanup scope.
541 explicit RunCleanupsScope(CodeGenFunction &CGF)
542 : PerformCleanup(true), CGF(CGF)
544 CleanupStackDepth = CGF.EHStack.stable_begin();
545 LifetimeExtendedCleanupStackSize =
546 CGF.LifetimeExtendedCleanupStack.size();
547 OldDidCallStackSave = CGF.DidCallStackSave;
548 CGF.DidCallStackSave = false;
551 /// \brief Exit this cleanup scope, emitting any accumulated
553 ~RunCleanupsScope() {
554 if (PerformCleanup) {
555 CGF.DidCallStackSave = OldDidCallStackSave;
556 CGF.PopCleanupBlocks(CleanupStackDepth,
557 LifetimeExtendedCleanupStackSize);
561 /// \brief Determine whether this scope requires any cleanups.
562 bool requiresCleanups() const {
563 return CGF.EHStack.stable_begin() != CleanupStackDepth;
566 /// \brief Force the emission of cleanups now, instead of waiting
567 /// until this object is destroyed.
568 void ForceCleanup() {
569 assert(PerformCleanup && "Already forced cleanup");
570 CGF.DidCallStackSave = OldDidCallStackSave;
571 CGF.PopCleanupBlocks(CleanupStackDepth,
572 LifetimeExtendedCleanupStackSize);
573 PerformCleanup = false;
577 class LexicalScope : public RunCleanupsScope {
579 SmallVector<const LabelDecl*, 4> Labels;
580 LexicalScope *ParentScope;
582 LexicalScope(const LexicalScope &) = delete;
583 void operator=(const LexicalScope &) = delete;
586 /// \brief Enter a new cleanup scope.
587 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
588 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
589 CGF.CurLexicalScope = this;
590 if (CGDebugInfo *DI = CGF.getDebugInfo())
591 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
594 void addLabel(const LabelDecl *label) {
595 assert(PerformCleanup && "adding label to dead scope?");
596 Labels.push_back(label);
599 /// \brief Exit this cleanup scope, emitting any accumulated
602 if (CGDebugInfo *DI = CGF.getDebugInfo())
603 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
605 // If we should perform a cleanup, force them now. Note that
606 // this ends the cleanup scope before rescoping any labels.
607 if (PerformCleanup) {
608 ApplyDebugLocation DL(CGF, Range.getEnd());
613 /// \brief Force the emission of cleanups now, instead of waiting
614 /// until this object is destroyed.
615 void ForceCleanup() {
616 CGF.CurLexicalScope = ParentScope;
617 RunCleanupsScope::ForceCleanup();
623 void rescopeLabels();
626 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy;
628 /// \brief The scope used to remap some variables as private in the OpenMP
629 /// loop body (or other captured region emitted without outlining), and to
630 /// restore old vars back on exit.
631 class OMPPrivateScope : public RunCleanupsScope {
632 DeclMapTy SavedLocals;
633 DeclMapTy SavedPrivates;
636 OMPPrivateScope(const OMPPrivateScope &) = delete;
637 void operator=(const OMPPrivateScope &) = delete;
640 /// \brief Enter a new OpenMP private scope.
641 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
643 /// \brief Registers \a LocalVD variable as a private and apply \a
644 /// PrivateGen function for it to generate corresponding private variable.
645 /// \a PrivateGen returns an address of the generated private variable.
646 /// \return true if the variable is registered as private, false if it has
647 /// been privatized already.
649 addPrivate(const VarDecl *LocalVD,
650 llvm::function_ref<Address()> PrivateGen) {
651 assert(PerformCleanup && "adding private to dead scope");
653 // Only save it once.
654 if (SavedLocals.count(LocalVD)) return false;
656 // Copy the existing local entry to SavedLocals.
657 auto it = CGF.LocalDeclMap.find(LocalVD);
658 if (it != CGF.LocalDeclMap.end()) {
659 SavedLocals.insert({LocalVD, it->second});
661 SavedLocals.insert({LocalVD, Address::invalid()});
664 // Generate the private entry.
665 Address Addr = PrivateGen();
666 QualType VarTy = LocalVD->getType();
667 if (VarTy->isReferenceType()) {
668 Address Temp = CGF.CreateMemTemp(VarTy);
669 CGF.Builder.CreateStore(Addr.getPointer(), Temp);
672 SavedPrivates.insert({LocalVD, Addr});
677 /// \brief Privatizes local variables previously registered as private.
678 /// Registration is separate from the actual privatization to allow
679 /// initializers use values of the original variables, not the private one.
680 /// This is important, for example, if the private variable is a class
681 /// variable initialized by a constructor that references other private
682 /// variables. But at initialization original variables must be used, not
684 /// \return true if at least one variable was privatized, false otherwise.
686 copyInto(SavedPrivates, CGF.LocalDeclMap);
687 SavedPrivates.clear();
688 return !SavedLocals.empty();
691 void ForceCleanup() {
692 RunCleanupsScope::ForceCleanup();
693 copyInto(SavedLocals, CGF.LocalDeclMap);
697 /// \brief Exit scope - all the mapped variables are restored.
703 /// Checks if the global variable is captured in current function.
704 bool isGlobalVarCaptured(const VarDecl *VD) const {
705 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0;
709 /// Copy all the entries in the source map over the corresponding
710 /// entries in the destination, which must exist.
711 static void copyInto(const DeclMapTy &src, DeclMapTy &dest) {
712 for (auto &pair : src) {
713 if (!pair.second.isValid()) {
714 dest.erase(pair.first);
718 auto it = dest.find(pair.first);
719 if (it != dest.end()) {
720 it->second = pair.second;
728 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
729 /// that have been added.
730 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
732 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
733 /// that have been added, then adds all lifetime-extended cleanups from
734 /// the given position to the stack.
735 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
736 size_t OldLifetimeExtendedStackSize);
738 void ResolveBranchFixups(llvm::BasicBlock *Target);
740 /// The given basic block lies in the current EH scope, but may be a
741 /// target of a potentially scope-crossing jump; get a stable handle
742 /// to which we can perform this jump later.
743 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
744 return JumpDest(Target,
745 EHStack.getInnermostNormalCleanup(),
746 NextCleanupDestIndex++);
749 /// The given basic block lies in the current EH scope, but may be a
750 /// target of a potentially scope-crossing jump; get a stable handle
751 /// to which we can perform this jump later.
752 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
753 return getJumpDestInCurrentScope(createBasicBlock(Name));
756 /// EmitBranchThroughCleanup - Emit a branch from the current insert
757 /// block through the normal cleanup handling code (if any) and then
759 void EmitBranchThroughCleanup(JumpDest Dest);
761 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
762 /// specified destination obviously has no cleanups to run. 'false' is always
763 /// a conservatively correct answer for this method.
764 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
766 /// popCatchScope - Pops the catch scope at the top of the EHScope
767 /// stack, emitting any required code (other than the catch handlers
769 void popCatchScope();
771 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
772 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
773 llvm::BasicBlock *getMSVCDispatchBlock(EHScopeStack::stable_iterator scope);
775 /// An object to manage conditionally-evaluated expressions.
776 class ConditionalEvaluation {
777 llvm::BasicBlock *StartBB;
780 ConditionalEvaluation(CodeGenFunction &CGF)
781 : StartBB(CGF.Builder.GetInsertBlock()) {}
783 void begin(CodeGenFunction &CGF) {
784 assert(CGF.OutermostConditional != this);
785 if (!CGF.OutermostConditional)
786 CGF.OutermostConditional = this;
789 void end(CodeGenFunction &CGF) {
790 assert(CGF.OutermostConditional != nullptr);
791 if (CGF.OutermostConditional == this)
792 CGF.OutermostConditional = nullptr;
795 /// Returns a block which will be executed prior to each
796 /// evaluation of the conditional code.
797 llvm::BasicBlock *getStartingBlock() const {
802 /// isInConditionalBranch - Return true if we're currently emitting
803 /// one branch or the other of a conditional expression.
804 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
806 void setBeforeOutermostConditional(llvm::Value *value, Address addr) {
807 assert(isInConditionalBranch());
808 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
809 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back());
810 store->setAlignment(addr.getAlignment().getQuantity());
813 /// An RAII object to record that we're evaluating a statement
815 class StmtExprEvaluation {
816 CodeGenFunction &CGF;
818 /// We have to save the outermost conditional: cleanups in a
819 /// statement expression aren't conditional just because the
821 ConditionalEvaluation *SavedOutermostConditional;
824 StmtExprEvaluation(CodeGenFunction &CGF)
825 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
826 CGF.OutermostConditional = nullptr;
829 ~StmtExprEvaluation() {
830 CGF.OutermostConditional = SavedOutermostConditional;
831 CGF.EnsureInsertPoint();
835 /// An object which temporarily prevents a value from being
836 /// destroyed by aggressive peephole optimizations that assume that
837 /// all uses of a value have been realized in the IR.
838 class PeepholeProtection {
839 llvm::Instruction *Inst;
840 friend class CodeGenFunction;
843 PeepholeProtection() : Inst(nullptr) {}
846 /// A non-RAII class containing all the information about a bound
847 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
848 /// this which makes individual mappings very simple; using this
849 /// class directly is useful when you have a variable number of
850 /// opaque values or don't want the RAII functionality for some
852 class OpaqueValueMappingData {
853 const OpaqueValueExpr *OpaqueValue;
855 CodeGenFunction::PeepholeProtection Protection;
857 OpaqueValueMappingData(const OpaqueValueExpr *ov,
859 : OpaqueValue(ov), BoundLValue(boundLValue) {}
861 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
863 static bool shouldBindAsLValue(const Expr *expr) {
864 // gl-values should be bound as l-values for obvious reasons.
865 // Records should be bound as l-values because IR generation
866 // always keeps them in memory. Expressions of function type
867 // act exactly like l-values but are formally required to be
869 return expr->isGLValue() ||
870 expr->getType()->isFunctionType() ||
871 hasAggregateEvaluationKind(expr->getType());
874 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
875 const OpaqueValueExpr *ov,
877 if (shouldBindAsLValue(ov))
878 return bind(CGF, ov, CGF.EmitLValue(e));
879 return bind(CGF, ov, CGF.EmitAnyExpr(e));
882 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
883 const OpaqueValueExpr *ov,
885 assert(shouldBindAsLValue(ov));
886 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
887 return OpaqueValueMappingData(ov, true);
890 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
891 const OpaqueValueExpr *ov,
893 assert(!shouldBindAsLValue(ov));
894 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
896 OpaqueValueMappingData data(ov, false);
898 // Work around an extremely aggressive peephole optimization in
899 // EmitScalarConversion which assumes that all other uses of a
901 data.Protection = CGF.protectFromPeepholes(rv);
906 bool isValid() const { return OpaqueValue != nullptr; }
907 void clear() { OpaqueValue = nullptr; }
909 void unbind(CodeGenFunction &CGF) {
910 assert(OpaqueValue && "no data to unbind!");
913 CGF.OpaqueLValues.erase(OpaqueValue);
915 CGF.OpaqueRValues.erase(OpaqueValue);
916 CGF.unprotectFromPeepholes(Protection);
921 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
922 class OpaqueValueMapping {
923 CodeGenFunction &CGF;
924 OpaqueValueMappingData Data;
927 static bool shouldBindAsLValue(const Expr *expr) {
928 return OpaqueValueMappingData::shouldBindAsLValue(expr);
931 /// Build the opaque value mapping for the given conditional
932 /// operator if it's the GNU ?: extension. This is a common
933 /// enough pattern that the convenience operator is really
936 OpaqueValueMapping(CodeGenFunction &CGF,
937 const AbstractConditionalOperator *op) : CGF(CGF) {
938 if (isa<ConditionalOperator>(op))
942 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
943 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
947 /// Build the opaque value mapping for an OpaqueValueExpr whose source
948 /// expression is set to the expression the OVE represents.
949 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV)
952 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used "
953 "for OVE with no source expression");
954 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr());
958 OpaqueValueMapping(CodeGenFunction &CGF,
959 const OpaqueValueExpr *opaqueValue,
961 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
964 OpaqueValueMapping(CodeGenFunction &CGF,
965 const OpaqueValueExpr *opaqueValue,
967 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
975 ~OpaqueValueMapping() {
976 if (Data.isValid()) Data.unbind(CGF);
981 CGDebugInfo *DebugInfo;
982 bool DisableDebugInfo;
984 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
985 /// calling llvm.stacksave for multiple VLAs in the same scope.
986 bool DidCallStackSave;
988 /// IndirectBranch - The first time an indirect goto is seen we create a block
989 /// with an indirect branch. Every time we see the address of a label taken,
990 /// we add the label to the indirect goto. Every subsequent indirect goto is
991 /// codegen'd as a jump to the IndirectBranch's basic block.
992 llvm::IndirectBrInst *IndirectBranch;
994 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
996 DeclMapTy LocalDeclMap;
998 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this
999 /// will contain a mapping from said ParmVarDecl to its implicit "object_size"
1001 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2>
1004 /// Track escaped local variables with auto storage. Used during SEH
1005 /// outlining to produce a call to llvm.localescape.
1006 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
1008 /// LabelMap - This keeps track of the LLVM basic block for each C label.
1009 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
1011 // BreakContinueStack - This keeps track of where break and continue
1012 // statements should jump to.
1013 struct BreakContinue {
1014 BreakContinue(JumpDest Break, JumpDest Continue)
1015 : BreakBlock(Break), ContinueBlock(Continue) {}
1017 JumpDest BreakBlock;
1018 JumpDest ContinueBlock;
1020 SmallVector<BreakContinue, 8> BreakContinueStack;
1022 /// Handles cancellation exit points in OpenMP-related constructs.
1023 class OpenMPCancelExitStack {
1024 /// Tracks cancellation exit point and join point for cancel-related exit
1025 /// and normal exit.
1027 CancelExit() = default;
1028 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock,
1030 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {}
1031 OpenMPDirectiveKind Kind = OMPD_unknown;
1032 /// true if the exit block has been emitted already by the special
1033 /// emitExit() call, false if the default codegen is used.
1034 bool HasBeenEmitted = false;
1039 SmallVector<CancelExit, 8> Stack;
1042 OpenMPCancelExitStack() : Stack(1) {}
1043 ~OpenMPCancelExitStack() = default;
1044 /// Fetches the exit block for the current OpenMP construct.
1045 JumpDest getExitBlock() const { return Stack.back().ExitBlock; }
1046 /// Emits exit block with special codegen procedure specific for the related
1047 /// OpenMP construct + emits code for normal construct cleanup.
1048 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1049 const llvm::function_ref<void(CodeGenFunction &)> &CodeGen) {
1050 if (Stack.back().Kind == Kind && getExitBlock().isValid()) {
1051 assert(CGF.getOMPCancelDestination(Kind).isValid());
1052 assert(CGF.HaveInsertPoint());
1053 assert(!Stack.back().HasBeenEmitted);
1054 auto IP = CGF.Builder.saveAndClearIP();
1055 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1057 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1058 CGF.Builder.restoreIP(IP);
1059 Stack.back().HasBeenEmitted = true;
1063 /// Enter the cancel supporting \a Kind construct.
1064 /// \param Kind OpenMP directive that supports cancel constructs.
1065 /// \param HasCancel true, if the construct has inner cancel directive,
1066 /// false otherwise.
1067 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) {
1068 Stack.push_back({Kind,
1069 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit")
1071 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont")
1074 /// Emits default exit point for the cancel construct (if the special one
1075 /// has not be used) + join point for cancel/normal exits.
1076 void exit(CodeGenFunction &CGF) {
1077 if (getExitBlock().isValid()) {
1078 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid());
1079 bool HaveIP = CGF.HaveInsertPoint();
1080 if (!Stack.back().HasBeenEmitted) {
1082 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1083 CGF.EmitBlock(Stack.back().ExitBlock.getBlock());
1084 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock);
1086 CGF.EmitBlock(Stack.back().ContBlock.getBlock());
1088 CGF.Builder.CreateUnreachable();
1089 CGF.Builder.ClearInsertionPoint();
1095 OpenMPCancelExitStack OMPCancelStack;
1097 /// Controls insertion of cancellation exit blocks in worksharing constructs.
1098 class OMPCancelStackRAII {
1099 CodeGenFunction &CGF;
1102 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind,
1105 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel);
1107 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); }
1112 /// Calculate branch weights appropriate for PGO data
1113 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
1114 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
1115 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
1116 uint64_t LoopCount);
1119 /// Increment the profiler's counter for the given statement.
1120 void incrementProfileCounter(const Stmt *S) {
1121 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1122 PGO.emitCounterIncrement(Builder, S);
1123 PGO.setCurrentStmt(S);
1126 /// Get the profiler's count for the given statement.
1127 uint64_t getProfileCount(const Stmt *S) {
1128 Optional<uint64_t> Count = PGO.getStmtCount(S);
1129 if (!Count.hasValue())
1134 /// Set the profiler's current count.
1135 void setCurrentProfileCount(uint64_t Count) {
1136 PGO.setCurrentRegionCount(Count);
1139 /// Get the profiler's current count. This is generally the count for the most
1140 /// recently incremented counter.
1141 uint64_t getCurrentProfileCount() {
1142 return PGO.getCurrentRegionCount();
1147 /// SwitchInsn - This is nearest current switch instruction. It is null if
1148 /// current context is not in a switch.
1149 llvm::SwitchInst *SwitchInsn;
1150 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
1151 SmallVector<uint64_t, 16> *SwitchWeights;
1153 /// CaseRangeBlock - This block holds if condition check for last case
1154 /// statement range in current switch instruction.
1155 llvm::BasicBlock *CaseRangeBlock;
1157 /// OpaqueLValues - Keeps track of the current set of opaque value
1159 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
1160 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
1162 // VLASizeMap - This keeps track of the associated size for each VLA type.
1163 // We track this by the size expression rather than the type itself because
1164 // in certain situations, like a const qualifier applied to an VLA typedef,
1165 // multiple VLA types can share the same size expression.
1166 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
1167 // enter/leave scopes.
1168 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
1170 /// A block containing a single 'unreachable' instruction. Created
1171 /// lazily by getUnreachableBlock().
1172 llvm::BasicBlock *UnreachableBlock;
1174 /// Counts of the number return expressions in the function.
1175 unsigned NumReturnExprs;
1177 /// Count the number of simple (constant) return expressions in the function.
1178 unsigned NumSimpleReturnExprs;
1180 /// The last regular (non-return) debug location (breakpoint) in the function.
1181 SourceLocation LastStopPoint;
1184 /// A scope within which we are constructing the fields of an object which
1185 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
1186 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
1187 class FieldConstructionScope {
1189 FieldConstructionScope(CodeGenFunction &CGF, Address This)
1190 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
1191 CGF.CXXDefaultInitExprThis = This;
1193 ~FieldConstructionScope() {
1194 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
1198 CodeGenFunction &CGF;
1199 Address OldCXXDefaultInitExprThis;
1202 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
1203 /// is overridden to be the object under construction.
1204 class CXXDefaultInitExprScope {
1206 CXXDefaultInitExprScope(CodeGenFunction &CGF)
1207 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue),
1208 OldCXXThisAlignment(CGF.CXXThisAlignment) {
1209 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer();
1210 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment();
1212 ~CXXDefaultInitExprScope() {
1213 CGF.CXXThisValue = OldCXXThisValue;
1214 CGF.CXXThisAlignment = OldCXXThisAlignment;
1218 CodeGenFunction &CGF;
1219 llvm::Value *OldCXXThisValue;
1220 CharUnits OldCXXThisAlignment;
1223 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the
1224 /// current loop index is overridden.
1225 class ArrayInitLoopExprScope {
1227 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index)
1228 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) {
1229 CGF.ArrayInitIndex = Index;
1231 ~ArrayInitLoopExprScope() {
1232 CGF.ArrayInitIndex = OldArrayInitIndex;
1236 CodeGenFunction &CGF;
1237 llvm::Value *OldArrayInitIndex;
1240 class InlinedInheritingConstructorScope {
1242 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD)
1243 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl),
1244 OldCurCodeDecl(CGF.CurCodeDecl),
1245 OldCXXABIThisDecl(CGF.CXXABIThisDecl),
1246 OldCXXABIThisValue(CGF.CXXABIThisValue),
1247 OldCXXThisValue(CGF.CXXThisValue),
1248 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment),
1249 OldCXXThisAlignment(CGF.CXXThisAlignment),
1250 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy),
1251 OldCXXInheritedCtorInitExprArgs(
1252 std::move(CGF.CXXInheritedCtorInitExprArgs)) {
1254 CGF.CurFuncDecl = CGF.CurCodeDecl =
1255 cast<CXXConstructorDecl>(GD.getDecl());
1256 CGF.CXXABIThisDecl = nullptr;
1257 CGF.CXXABIThisValue = nullptr;
1258 CGF.CXXThisValue = nullptr;
1259 CGF.CXXABIThisAlignment = CharUnits();
1260 CGF.CXXThisAlignment = CharUnits();
1261 CGF.ReturnValue = Address::invalid();
1262 CGF.FnRetTy = QualType();
1263 CGF.CXXInheritedCtorInitExprArgs.clear();
1265 ~InlinedInheritingConstructorScope() {
1266 CGF.CurGD = OldCurGD;
1267 CGF.CurFuncDecl = OldCurFuncDecl;
1268 CGF.CurCodeDecl = OldCurCodeDecl;
1269 CGF.CXXABIThisDecl = OldCXXABIThisDecl;
1270 CGF.CXXABIThisValue = OldCXXABIThisValue;
1271 CGF.CXXThisValue = OldCXXThisValue;
1272 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment;
1273 CGF.CXXThisAlignment = OldCXXThisAlignment;
1274 CGF.ReturnValue = OldReturnValue;
1275 CGF.FnRetTy = OldFnRetTy;
1276 CGF.CXXInheritedCtorInitExprArgs =
1277 std::move(OldCXXInheritedCtorInitExprArgs);
1281 CodeGenFunction &CGF;
1282 GlobalDecl OldCurGD;
1283 const Decl *OldCurFuncDecl;
1284 const Decl *OldCurCodeDecl;
1285 ImplicitParamDecl *OldCXXABIThisDecl;
1286 llvm::Value *OldCXXABIThisValue;
1287 llvm::Value *OldCXXThisValue;
1288 CharUnits OldCXXABIThisAlignment;
1289 CharUnits OldCXXThisAlignment;
1290 Address OldReturnValue;
1291 QualType OldFnRetTy;
1292 CallArgList OldCXXInheritedCtorInitExprArgs;
1296 /// CXXThisDecl - When generating code for a C++ member function,
1297 /// this will hold the implicit 'this' declaration.
1298 ImplicitParamDecl *CXXABIThisDecl;
1299 llvm::Value *CXXABIThisValue;
1300 llvm::Value *CXXThisValue;
1301 CharUnits CXXABIThisAlignment;
1302 CharUnits CXXThisAlignment;
1304 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1305 /// this expression.
1306 Address CXXDefaultInitExprThis = Address::invalid();
1308 /// The current array initialization index when evaluating an
1309 /// ArrayInitIndexExpr within an ArrayInitLoopExpr.
1310 llvm::Value *ArrayInitIndex = nullptr;
1312 /// The values of function arguments to use when evaluating
1313 /// CXXInheritedCtorInitExprs within this context.
1314 CallArgList CXXInheritedCtorInitExprArgs;
1316 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1317 /// destructor, this will hold the implicit argument (e.g. VTT).
1318 ImplicitParamDecl *CXXStructorImplicitParamDecl;
1319 llvm::Value *CXXStructorImplicitParamValue;
1321 /// OutermostConditional - Points to the outermost active
1322 /// conditional control. This is used so that we know if a
1323 /// temporary should be destroyed conditionally.
1324 ConditionalEvaluation *OutermostConditional;
1326 /// The current lexical scope.
1327 LexicalScope *CurLexicalScope;
1329 /// The current source location that should be used for exception
1331 SourceLocation CurEHLocation;
1333 /// BlockByrefInfos - For each __block variable, contains
1334 /// information about the layout of the variable.
1335 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos;
1337 llvm::BasicBlock *TerminateLandingPad;
1338 llvm::BasicBlock *TerminateHandler;
1339 llvm::BasicBlock *TrapBB;
1341 /// True if we need emit the life-time markers.
1342 const bool ShouldEmitLifetimeMarkers;
1344 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
1345 /// In the kernel metadata node, reference the kernel function and metadata
1346 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
1347 /// - A node for the vec_type_hint(<type>) qualifier contains string
1348 /// "vec_type_hint", an undefined value of the <type> data type,
1349 /// and a Boolean that is true if the <type> is integer and signed.
1350 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
1351 /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
1352 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
1353 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
1354 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1355 llvm::Function *Fn);
1358 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1361 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1362 ASTContext &getContext() const { return CGM.getContext(); }
1363 CGDebugInfo *getDebugInfo() {
1364 if (DisableDebugInfo)
1368 void disableDebugInfo() { DisableDebugInfo = true; }
1369 void enableDebugInfo() { DisableDebugInfo = false; }
1371 bool shouldUseFusedARCCalls() {
1372 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1375 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1377 /// Returns a pointer to the function's exception object and selector slot,
1378 /// which is assigned in every landing pad.
1379 Address getExceptionSlot();
1380 Address getEHSelectorSlot();
1382 /// Returns the contents of the function's exception object and selector
1384 llvm::Value *getExceptionFromSlot();
1385 llvm::Value *getSelectorFromSlot();
1387 Address getNormalCleanupDestSlot();
1389 llvm::BasicBlock *getUnreachableBlock() {
1390 if (!UnreachableBlock) {
1391 UnreachableBlock = createBasicBlock("unreachable");
1392 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1394 return UnreachableBlock;
1397 llvm::BasicBlock *getInvokeDest() {
1398 if (!EHStack.requiresLandingPad()) return nullptr;
1399 return getInvokeDestImpl();
1402 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; }
1404 const TargetInfo &getTarget() const { return Target; }
1405 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1407 //===--------------------------------------------------------------------===//
1409 //===--------------------------------------------------------------------===//
1411 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty);
1413 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1414 Address arrayEndPointer,
1415 QualType elementType,
1416 CharUnits elementAlignment,
1417 Destroyer *destroyer);
1418 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1419 llvm::Value *arrayEnd,
1420 QualType elementType,
1421 CharUnits elementAlignment,
1422 Destroyer *destroyer);
1424 void pushDestroy(QualType::DestructionKind dtorKind,
1425 Address addr, QualType type);
1426 void pushEHDestroy(QualType::DestructionKind dtorKind,
1427 Address addr, QualType type);
1428 void pushDestroy(CleanupKind kind, Address addr, QualType type,
1429 Destroyer *destroyer, bool useEHCleanupForArray);
1430 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr,
1431 QualType type, Destroyer *destroyer,
1432 bool useEHCleanupForArray);
1433 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1434 llvm::Value *CompletePtr,
1435 QualType ElementType);
1436 void pushStackRestore(CleanupKind kind, Address SPMem);
1437 void emitDestroy(Address addr, QualType type, Destroyer *destroyer,
1438 bool useEHCleanupForArray);
1439 llvm::Function *generateDestroyHelper(Address addr, QualType type,
1440 Destroyer *destroyer,
1441 bool useEHCleanupForArray,
1443 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1444 QualType elementType, CharUnits elementAlign,
1445 Destroyer *destroyer,
1446 bool checkZeroLength, bool useEHCleanup);
1448 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1450 /// Determines whether an EH cleanup is required to destroy a type
1451 /// with the given destruction kind.
1452 bool needsEHCleanup(QualType::DestructionKind kind) {
1454 case QualType::DK_none:
1456 case QualType::DK_cxx_destructor:
1457 case QualType::DK_objc_weak_lifetime:
1458 return getLangOpts().Exceptions;
1459 case QualType::DK_objc_strong_lifetime:
1460 return getLangOpts().Exceptions &&
1461 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1463 llvm_unreachable("bad destruction kind");
1466 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1467 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1470 //===--------------------------------------------------------------------===//
1472 //===--------------------------------------------------------------------===//
1474 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1476 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1478 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1479 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1480 const ObjCPropertyImplDecl *PID);
1481 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1482 const ObjCPropertyImplDecl *propImpl,
1483 const ObjCMethodDecl *GetterMothodDecl,
1484 llvm::Constant *AtomicHelperFn);
1486 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1487 ObjCMethodDecl *MD, bool ctor);
1489 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1490 /// for the given property.
1491 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1492 const ObjCPropertyImplDecl *PID);
1493 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1494 const ObjCPropertyImplDecl *propImpl,
1495 llvm::Constant *AtomicHelperFn);
1497 //===--------------------------------------------------------------------===//
1499 //===--------------------------------------------------------------------===//
1501 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1502 static void destroyBlockInfos(CGBlockInfo *info);
1504 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1505 const CGBlockInfo &Info,
1506 const DeclMapTy &ldm,
1507 bool IsLambdaConversionToBlock);
1509 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1510 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1511 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1512 const ObjCPropertyImplDecl *PID);
1513 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1514 const ObjCPropertyImplDecl *PID);
1515 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1517 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1519 class AutoVarEmission;
1521 void emitByrefStructureInit(const AutoVarEmission &emission);
1522 void enterByrefCleanup(const AutoVarEmission &emission);
1524 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum,
1527 Address LoadBlockStruct();
1528 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1530 /// BuildBlockByrefAddress - Computes the location of the
1531 /// data in a variable which is declared as __block.
1532 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V,
1533 bool followForward = true);
1534 Address emitBlockByrefAddress(Address baseAddr,
1535 const BlockByrefInfo &info,
1537 const llvm::Twine &name);
1539 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var);
1541 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args);
1543 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1544 const CGFunctionInfo &FnInfo);
1545 /// \brief Emit code for the start of a function.
1546 /// \param Loc The location to be associated with the function.
1547 /// \param StartLoc The location of the function body.
1548 void StartFunction(GlobalDecl GD,
1551 const CGFunctionInfo &FnInfo,
1552 const FunctionArgList &Args,
1553 SourceLocation Loc = SourceLocation(),
1554 SourceLocation StartLoc = SourceLocation());
1556 void EmitConstructorBody(FunctionArgList &Args);
1557 void EmitDestructorBody(FunctionArgList &Args);
1558 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1559 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1560 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1562 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1563 CallArgList &CallArgs);
1564 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1565 void EmitLambdaBlockInvokeBody();
1566 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1567 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1568 void EmitAsanPrologueOrEpilogue(bool Prologue);
1570 /// \brief Emit the unified return block, trying to avoid its emission when
1572 /// \return The debug location of the user written return statement if the
1573 /// return block is is avoided.
1574 llvm::DebugLoc EmitReturnBlock();
1576 /// FinishFunction - Complete IR generation of the current function. It is
1577 /// legal to call this function even if there is no current insertion point.
1578 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1580 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1581 const CGFunctionInfo &FnInfo);
1583 void EmitCallAndReturnForThunk(llvm::Constant *Callee,
1584 const ThunkInfo *Thunk);
1588 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1589 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1590 llvm::Value *Callee);
1592 /// Generate a thunk for the given method.
1593 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1594 GlobalDecl GD, const ThunkInfo &Thunk);
1596 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1597 const CGFunctionInfo &FnInfo,
1598 GlobalDecl GD, const ThunkInfo &Thunk);
1600 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1601 FunctionArgList &Args);
1603 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init);
1605 /// Struct with all informations about dynamic [sub]class needed to set vptr.
1608 const CXXRecordDecl *NearestVBase;
1609 CharUnits OffsetFromNearestVBase;
1610 const CXXRecordDecl *VTableClass;
1613 /// Initialize the vtable pointer of the given subobject.
1614 void InitializeVTablePointer(const VPtr &vptr);
1616 typedef llvm::SmallVector<VPtr, 4> VPtrsVector;
1618 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1619 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass);
1621 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase,
1622 CharUnits OffsetFromNearestVBase,
1623 bool BaseIsNonVirtualPrimaryBase,
1624 const CXXRecordDecl *VTableClass,
1625 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs);
1627 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1629 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1631 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy,
1632 const CXXRecordDecl *VTableClass);
1634 enum CFITypeCheckKind {
1638 CFITCK_UnrelatedCast,
1642 /// \brief Derived is the presumed address of an object of type T after a
1643 /// cast. If T is a polymorphic class type, emit a check that the virtual
1644 /// table for Derived belongs to a class derived from T.
1645 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1646 bool MayBeNull, CFITypeCheckKind TCK,
1647 SourceLocation Loc);
1649 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1650 /// If vptr CFI is enabled, emit a check that VTable is valid.
1651 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable,
1652 CFITypeCheckKind TCK, SourceLocation Loc);
1654 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1655 /// RD using llvm.type.test.
1656 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1657 CFITypeCheckKind TCK, SourceLocation Loc);
1659 /// If whole-program virtual table optimization is enabled, emit an assumption
1660 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is
1661 /// enabled, emit a check that VTable is a member of RD's type identifier.
1662 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
1663 llvm::Value *VTable, SourceLocation Loc);
1665 /// Returns whether we should perform a type checked load when loading a
1666 /// virtual function for virtual calls to members of RD. This is generally
1667 /// true when both vcall CFI and whole-program-vtables are enabled.
1668 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD);
1670 /// Emit a type checked load from the given vtable.
1671 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable,
1672 uint64_t VTableByteOffset);
1674 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1675 /// expr can be devirtualized.
1676 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1677 const CXXMethodDecl *MD);
1679 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1680 /// given phase of destruction for a destructor. The end result
1681 /// should call destructors on members and base classes in reverse
1682 /// order of their construction.
1683 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1685 /// ShouldInstrumentFunction - Return true if the current function should be
1686 /// instrumented with __cyg_profile_func_* calls
1687 bool ShouldInstrumentFunction();
1689 /// ShouldXRayInstrument - Return true if the current function should be
1690 /// instrumented with XRay nop sleds.
1691 bool ShouldXRayInstrumentFunction() const;
1693 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1694 /// instrumentation function with the current function and the call site, if
1695 /// function instrumentation is enabled.
1696 void EmitFunctionInstrumentation(const char *Fn);
1698 /// EmitMCountInstrumentation - Emit call to .mcount.
1699 void EmitMCountInstrumentation();
1701 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1702 /// arguments for the given function. This is also responsible for naming the
1703 /// LLVM function arguments.
1704 void EmitFunctionProlog(const CGFunctionInfo &FI,
1706 const FunctionArgList &Args);
1708 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1709 /// given temporary.
1710 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1711 SourceLocation EndLoc);
1713 /// EmitStartEHSpec - Emit the start of the exception spec.
1714 void EmitStartEHSpec(const Decl *D);
1716 /// EmitEndEHSpec - Emit the end of the exception spec.
1717 void EmitEndEHSpec(const Decl *D);
1719 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1720 llvm::BasicBlock *getTerminateLandingPad();
1722 /// getTerminateHandler - Return a handler (not a landing pad, just
1723 /// a catch handler) that just calls terminate. This is used when
1724 /// a terminate scope encloses a try.
1725 llvm::BasicBlock *getTerminateHandler();
1727 llvm::Type *ConvertTypeForMem(QualType T);
1728 llvm::Type *ConvertType(QualType T);
1729 llvm::Type *ConvertType(const TypeDecl *T) {
1730 return ConvertType(getContext().getTypeDeclType(T));
1733 /// LoadObjCSelf - Load the value of self. This function is only valid while
1734 /// generating code for an Objective-C method.
1735 llvm::Value *LoadObjCSelf();
1737 /// TypeOfSelfObject - Return type of object that this self represents.
1738 QualType TypeOfSelfObject();
1740 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1741 /// an aggregate LLVM type or is void.
1742 static TypeEvaluationKind getEvaluationKind(QualType T);
1744 static bool hasScalarEvaluationKind(QualType T) {
1745 return getEvaluationKind(T) == TEK_Scalar;
1748 static bool hasAggregateEvaluationKind(QualType T) {
1749 return getEvaluationKind(T) == TEK_Aggregate;
1752 /// createBasicBlock - Create an LLVM basic block.
1753 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1754 llvm::Function *parent = nullptr,
1755 llvm::BasicBlock *before = nullptr) {
1757 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1759 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1763 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1765 JumpDest getJumpDestForLabel(const LabelDecl *S);
1767 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1768 /// another basic block, simplify it. This assumes that no other code could
1769 /// potentially reference the basic block.
1770 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1772 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1773 /// adding a fall-through branch from the current insert block if
1774 /// necessary. It is legal to call this function even if there is no current
1775 /// insertion point.
1777 /// IsFinished - If true, indicates that the caller has finished emitting
1778 /// branches to the given block and does not expect to emit code into it. This
1779 /// means the block can be ignored if it is unreachable.
1780 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1782 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1783 /// near its uses, and leave the insertion point in it.
1784 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1786 /// EmitBranch - Emit a branch to the specified basic block from the current
1787 /// insert block, taking care to avoid creation of branches from dummy
1788 /// blocks. It is legal to call this function even if there is no current
1789 /// insertion point.
1791 /// This function clears the current insertion point. The caller should follow
1792 /// calls to this function with calls to Emit*Block prior to generation new
1794 void EmitBranch(llvm::BasicBlock *Block);
1796 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1797 /// indicates that the current code being emitted is unreachable.
1798 bool HaveInsertPoint() const {
1799 return Builder.GetInsertBlock() != nullptr;
1802 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1803 /// emitted IR has a place to go. Note that by definition, if this function
1804 /// creates a block then that block is unreachable; callers may do better to
1805 /// detect when no insertion point is defined and simply skip IR generation.
1806 void EnsureInsertPoint() {
1807 if (!HaveInsertPoint())
1808 EmitBlock(createBasicBlock());
1811 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1812 /// specified stmt yet.
1813 void ErrorUnsupported(const Stmt *S, const char *Type);
1815 //===--------------------------------------------------------------------===//
1817 //===--------------------------------------------------------------------===//
1819 LValue MakeAddrLValue(Address Addr, QualType T,
1820 AlignmentSource AlignSource = AlignmentSource::Type) {
1821 return LValue::MakeAddr(Addr, T, getContext(), AlignSource,
1822 CGM.getTBAAInfo(T));
1825 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment,
1826 AlignmentSource AlignSource = AlignmentSource::Type) {
1827 return LValue::MakeAddr(Address(V, Alignment), T, getContext(),
1828 AlignSource, CGM.getTBAAInfo(T));
1831 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T);
1832 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1833 CharUnits getNaturalTypeAlignment(QualType T,
1834 AlignmentSource *Source = nullptr,
1835 bool forPointeeType = false);
1836 CharUnits getNaturalPointeeTypeAlignment(QualType T,
1837 AlignmentSource *Source = nullptr);
1839 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy,
1840 AlignmentSource *Source = nullptr);
1841 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy);
1843 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy,
1844 AlignmentSource *Source = nullptr);
1845 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy);
1847 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1848 /// block. The caller is responsible for setting an appropriate alignment on
1850 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1851 const Twine &Name = "tmp");
1852 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align,
1853 const Twine &Name = "tmp");
1855 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the
1856 /// default ABI alignment of the given LLVM type.
1858 /// IMPORTANT NOTE: This is *not* generally the right alignment for
1859 /// any given AST type that happens to have been lowered to the
1860 /// given IR type. This should only ever be used for function-local,
1861 /// IR-driven manipulations like saving and restoring a value. Do
1862 /// not hand this address off to arbitrary IRGen routines, and especially
1863 /// do not pass it as an argument to a function that might expect a
1864 /// properly ABI-aligned value.
1865 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty,
1866 const Twine &Name = "tmp");
1868 /// InitTempAlloca - Provide an initial value for the given alloca which
1869 /// will be observable at all locations in the function.
1871 /// The address should be something that was returned from one of
1872 /// the CreateTempAlloca or CreateMemTemp routines, and the
1873 /// initializer must be valid in the entry block (i.e. it must
1874 /// either be a constant or an argument value).
1875 void InitTempAlloca(Address Alloca, llvm::Value *Value);
1877 /// CreateIRTemp - Create a temporary IR object of the given type, with
1878 /// appropriate alignment. This routine should only be used when an temporary
1879 /// value needs to be stored into an alloca (for example, to avoid explicit
1880 /// PHI construction), but the type is the IR type, not the type appropriate
1881 /// for storing in memory.
1883 /// That is, this is exactly equivalent to CreateMemTemp, but calling
1884 /// ConvertType instead of ConvertTypeForMem.
1885 Address CreateIRTemp(QualType T, const Twine &Name = "tmp");
1887 /// CreateMemTemp - Create a temporary memory object of the given type, with
1888 /// appropriate alignment.
1889 Address CreateMemTemp(QualType T, const Twine &Name = "tmp");
1890 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp");
1892 /// CreateAggTemp - Create a temporary memory object for the given
1894 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1895 return AggValueSlot::forAddr(CreateMemTemp(T, Name),
1897 AggValueSlot::IsNotDestructed,
1898 AggValueSlot::DoesNotNeedGCBarriers,
1899 AggValueSlot::IsNotAliased);
1902 /// Emit a cast to void* in the appropriate address space.
1903 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1905 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1906 /// expression and compare the result against zero, returning an Int1Ty value.
1907 llvm::Value *EvaluateExprAsBool(const Expr *E);
1909 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1910 void EmitIgnoredExpr(const Expr *E);
1912 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1913 /// any type. The result is returned as an RValue struct. If this is an
1914 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1915 /// the result should be returned.
1917 /// \param ignoreResult True if the resulting value isn't used.
1918 RValue EmitAnyExpr(const Expr *E,
1919 AggValueSlot aggSlot = AggValueSlot::ignored(),
1920 bool ignoreResult = false);
1922 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1923 // or the value of the expression, depending on how va_list is defined.
1924 Address EmitVAListRef(const Expr *E);
1926 /// Emit a "reference" to a __builtin_ms_va_list; this is
1927 /// always the value of the expression, because a __builtin_ms_va_list is a
1928 /// pointer to a char.
1929 Address EmitMSVAListRef(const Expr *E);
1931 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1932 /// always be accessible even if no aggregate location is provided.
1933 RValue EmitAnyExprToTemp(const Expr *E);
1935 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1936 /// arbitrary expression into the given memory location.
1937 void EmitAnyExprToMem(const Expr *E, Address Location,
1938 Qualifiers Quals, bool IsInitializer);
1940 void EmitAnyExprToExn(const Expr *E, Address Addr);
1942 /// EmitExprAsInit - Emits the code necessary to initialize a
1943 /// location in memory with the given initializer.
1944 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
1945 bool capturedByInit);
1947 /// hasVolatileMember - returns true if aggregate type has a volatile
1949 bool hasVolatileMember(QualType T) {
1950 if (const RecordType *RT = T->getAs<RecordType>()) {
1951 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1952 return RD->hasVolatileMember();
1956 /// EmitAggregateCopy - Emit an aggregate assignment.
1958 /// The difference to EmitAggregateCopy is that tail padding is not copied.
1959 /// This is required for correctness when assigning non-POD structures in C++.
1960 void EmitAggregateAssign(Address DestPtr, Address SrcPtr,
1962 bool IsVolatile = hasVolatileMember(EltTy);
1963 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true);
1966 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr,
1967 QualType DestTy, QualType SrcTy) {
1968 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
1969 /*IsAssignment=*/false);
1972 /// EmitAggregateCopy - Emit an aggregate copy.
1974 /// \param isVolatile - True iff either the source or the destination is
1976 /// \param isAssignment - If false, allow padding to be copied. This often
1977 /// yields more efficient.
1978 void EmitAggregateCopy(Address DestPtr, Address SrcPtr,
1979 QualType EltTy, bool isVolatile=false,
1980 bool isAssignment = false);
1982 /// GetAddrOfLocalVar - Return the address of a local variable.
1983 Address GetAddrOfLocalVar(const VarDecl *VD) {
1984 auto it = LocalDeclMap.find(VD);
1985 assert(it != LocalDeclMap.end() &&
1986 "Invalid argument to GetAddrOfLocalVar(), no decl!");
1990 /// getOpaqueLValueMapping - Given an opaque value expression (which
1991 /// must be mapped to an l-value), return its mapping.
1992 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1993 assert(OpaqueValueMapping::shouldBindAsLValue(e));
1995 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1996 it = OpaqueLValues.find(e);
1997 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
2001 /// getOpaqueRValueMapping - Given an opaque value expression (which
2002 /// must be mapped to an r-value), return its mapping.
2003 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
2004 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
2006 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
2007 it = OpaqueRValues.find(e);
2008 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
2012 /// Get the index of the current ArrayInitLoopExpr, if any.
2013 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; }
2015 /// getAccessedFieldNo - Given an encoded value and a result number, return
2016 /// the input field number being accessed.
2017 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
2019 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
2020 llvm::BasicBlock *GetIndirectGotoBlock();
2022 /// EmitNullInitialization - Generate code to set a value of the given type to
2023 /// null, If the type contains data member pointers, they will be initialized
2024 /// to -1 in accordance with the Itanium C++ ABI.
2025 void EmitNullInitialization(Address DestPtr, QualType Ty);
2027 /// Emits a call to an LLVM variable-argument intrinsic, either
2028 /// \c llvm.va_start or \c llvm.va_end.
2029 /// \param ArgValue A reference to the \c va_list as emitted by either
2030 /// \c EmitVAListRef or \c EmitMSVAListRef.
2031 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise,
2032 /// calls \c llvm.va_end.
2033 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart);
2035 /// Generate code to get an argument from the passed in pointer
2036 /// and update it accordingly.
2037 /// \param VE The \c VAArgExpr for which to generate code.
2038 /// \param VAListAddr Receives a reference to the \c va_list as emitted by
2039 /// either \c EmitVAListRef or \c EmitMSVAListRef.
2040 /// \returns A pointer to the argument.
2041 // FIXME: We should be able to get rid of this method and use the va_arg
2042 // instruction in LLVM instead once it works well enough.
2043 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr);
2045 /// emitArrayLength - Compute the length of an array, even if it's a
2046 /// VLA, and drill down to the base element type.
2047 llvm::Value *emitArrayLength(const ArrayType *arrayType,
2051 /// EmitVLASize - Capture all the sizes for the VLA expressions in
2052 /// the given variably-modified type and store them in the VLASizeMap.
2054 /// This function can be called with a null (unreachable) insert point.
2055 void EmitVariablyModifiedType(QualType Ty);
2057 /// getVLASize - Returns an LLVM value that corresponds to the size,
2058 /// in non-variably-sized elements, of a variable length array type,
2059 /// plus that largest non-variably-sized element type. Assumes that
2060 /// the type has already been emitted with EmitVariablyModifiedType.
2061 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
2062 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
2064 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
2065 /// generating code for an C++ member function.
2066 llvm::Value *LoadCXXThis() {
2067 assert(CXXThisValue && "no 'this' value for this function");
2068 return CXXThisValue;
2070 Address LoadCXXThisAddress();
2072 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
2074 // FIXME: Every place that calls LoadCXXVTT is something
2075 // that needs to be abstracted properly.
2076 llvm::Value *LoadCXXVTT() {
2077 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
2078 return CXXStructorImplicitParamValue;
2081 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
2082 /// complete class to the given direct base.
2084 GetAddressOfDirectBaseInCompleteClass(Address Value,
2085 const CXXRecordDecl *Derived,
2086 const CXXRecordDecl *Base,
2087 bool BaseIsVirtual);
2089 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast);
2091 /// GetAddressOfBaseClass - This function will add the necessary delta to the
2092 /// load of 'this' and returns address of the base class.
2093 Address GetAddressOfBaseClass(Address Value,
2094 const CXXRecordDecl *Derived,
2095 CastExpr::path_const_iterator PathBegin,
2096 CastExpr::path_const_iterator PathEnd,
2097 bool NullCheckValue, SourceLocation Loc);
2099 Address GetAddressOfDerivedClass(Address Value,
2100 const CXXRecordDecl *Derived,
2101 CastExpr::path_const_iterator PathBegin,
2102 CastExpr::path_const_iterator PathEnd,
2103 bool NullCheckValue);
2105 /// GetVTTParameter - Return the VTT parameter that should be passed to a
2106 /// base constructor/destructor with virtual bases.
2107 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
2108 /// to ItaniumCXXABI.cpp together with all the references to VTT.
2109 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
2112 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
2113 CXXCtorType CtorType,
2114 const FunctionArgList &Args,
2115 SourceLocation Loc);
2116 // It's important not to confuse this and the previous function. Delegating
2117 // constructors are the C++0x feature. The constructor delegate optimization
2118 // is used to reduce duplication in the base and complete consturctors where
2119 // they are substantially the same.
2120 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2121 const FunctionArgList &Args);
2123 /// Emit a call to an inheriting constructor (that is, one that invokes a
2124 /// constructor inherited from a base class) by inlining its definition. This
2125 /// is necessary if the ABI does not support forwarding the arguments to the
2126 /// base class constructor (because they're variadic or similar).
2127 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2128 CXXCtorType CtorType,
2129 bool ForVirtualBase,
2133 /// Emit a call to a constructor inherited from a base class, passing the
2134 /// current constructor's arguments along unmodified (without even making
2136 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D,
2137 bool ForVirtualBase, Address This,
2138 bool InheritedFromVBase,
2139 const CXXInheritedCtorInitExpr *E);
2141 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2142 bool ForVirtualBase, bool Delegating,
2143 Address This, const CXXConstructExpr *E);
2145 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
2146 bool ForVirtualBase, bool Delegating,
2147 Address This, CallArgList &Args);
2149 /// Emit assumption load for all bases. Requires to be be called only on
2150 /// most-derived class and not under construction of the object.
2151 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This);
2153 /// Emit assumption that vptr load == global vtable.
2154 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This);
2156 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
2157 Address This, Address Src,
2158 const CXXConstructExpr *E);
2160 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2161 const ArrayType *ArrayTy,
2163 const CXXConstructExpr *E,
2164 bool ZeroInitialization = false);
2166 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
2167 llvm::Value *NumElements,
2169 const CXXConstructExpr *E,
2170 bool ZeroInitialization = false);
2172 static Destroyer destroyCXXObject;
2174 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
2175 bool ForVirtualBase, bool Delegating,
2178 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
2179 llvm::Type *ElementTy, Address NewPtr,
2180 llvm::Value *NumElements,
2181 llvm::Value *AllocSizeWithoutCookie);
2183 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
2186 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
2187 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
2189 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
2190 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
2192 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
2193 QualType DeleteTy, llvm::Value *NumElements = nullptr,
2194 CharUnits CookieSize = CharUnits());
2196 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
2197 const Expr *Arg, bool IsDelete);
2199 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E);
2200 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE);
2201 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E);
2203 /// \brief Situations in which we might emit a check for the suitability of a
2204 /// pointer or glvalue.
2205 enum TypeCheckKind {
2206 /// Checking the operand of a load. Must be suitably sized and aligned.
2208 /// Checking the destination of a store. Must be suitably sized and aligned.
2210 /// Checking the bound value in a reference binding. Must be suitably sized
2211 /// and aligned, but is not required to refer to an object (until the
2212 /// reference is used), per core issue 453.
2213 TCK_ReferenceBinding,
2214 /// Checking the object expression in a non-static data member access. Must
2215 /// be an object within its lifetime.
2217 /// Checking the 'this' pointer for a call to a non-static member function.
2218 /// Must be an object within its lifetime.
2220 /// Checking the 'this' pointer for a constructor call.
2221 TCK_ConstructorCall,
2222 /// Checking the operand of a static_cast to a derived pointer type. Must be
2223 /// null or an object within its lifetime.
2224 TCK_DowncastPointer,
2225 /// Checking the operand of a static_cast to a derived reference type. Must
2226 /// be an object within its lifetime.
2227 TCK_DowncastReference,
2228 /// Checking the operand of a cast to a base object. Must be suitably sized
2231 /// Checking the operand of a cast to a virtual base object. Must be an
2232 /// object within its lifetime.
2233 TCK_UpcastToVirtualBase
2236 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
2237 /// calls to EmitTypeCheck can be skipped.
2238 bool sanitizePerformTypeCheck() const;
2240 /// \brief Emit a check that \p V is the address of storage of the
2241 /// appropriate size and alignment for an object of type \p Type.
2242 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
2243 QualType Type, CharUnits Alignment = CharUnits::Zero(),
2244 bool SkipNullCheck = false);
2246 /// \brief Emit a check that \p Base points into an array object, which
2247 /// we can access at index \p Index. \p Accessed should be \c false if we
2248 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
2249 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
2250 QualType IndexType, bool Accessed);
2252 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2253 bool isInc, bool isPre);
2254 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
2255 bool isInc, bool isPre);
2257 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
2258 llvm::Value *OffsetValue = nullptr) {
2259 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
2263 /// Converts Location to a DebugLoc, if debug information is enabled.
2264 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location);
2267 //===--------------------------------------------------------------------===//
2268 // Declaration Emission
2269 //===--------------------------------------------------------------------===//
2271 /// EmitDecl - Emit a declaration.
2273 /// This function can be called with a null (unreachable) insert point.
2274 void EmitDecl(const Decl &D);
2276 /// EmitVarDecl - Emit a local variable declaration.
2278 /// This function can be called with a null (unreachable) insert point.
2279 void EmitVarDecl(const VarDecl &D);
2281 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
2282 bool capturedByInit);
2284 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
2285 llvm::Value *Address);
2287 /// \brief Determine whether the given initializer is trivial in the sense
2288 /// that it requires no code to be generated.
2289 bool isTrivialInitializer(const Expr *Init);
2291 /// EmitAutoVarDecl - Emit an auto variable declaration.
2293 /// This function can be called with a null (unreachable) insert point.
2294 void EmitAutoVarDecl(const VarDecl &D);
2296 class AutoVarEmission {
2297 friend class CodeGenFunction;
2299 const VarDecl *Variable;
2301 /// The address of the alloca. Invalid if the variable was emitted
2302 /// as a global constant.
2305 llvm::Value *NRVOFlag;
2307 /// True if the variable is a __block variable.
2310 /// True if the variable is of aggregate type and has a constant
2312 bool IsConstantAggregate;
2314 /// Non-null if we should use lifetime annotations.
2315 llvm::Value *SizeForLifetimeMarkers;
2318 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {}
2320 AutoVarEmission(const VarDecl &variable)
2321 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr),
2322 IsByRef(false), IsConstantAggregate(false),
2323 SizeForLifetimeMarkers(nullptr) {}
2325 bool wasEmittedAsGlobal() const { return !Addr.isValid(); }
2328 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
2330 bool useLifetimeMarkers() const {
2331 return SizeForLifetimeMarkers != nullptr;
2333 llvm::Value *getSizeForLifetimeMarkers() const {
2334 assert(useLifetimeMarkers());
2335 return SizeForLifetimeMarkers;
2338 /// Returns the raw, allocated address, which is not necessarily
2339 /// the address of the object itself.
2340 Address getAllocatedAddress() const {
2344 /// Returns the address of the object within this declaration.
2345 /// Note that this does not chase the forwarding pointer for
2347 Address getObjectAddress(CodeGenFunction &CGF) const {
2348 if (!IsByRef) return Addr;
2350 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false);
2353 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
2354 void EmitAutoVarInit(const AutoVarEmission &emission);
2355 void EmitAutoVarCleanups(const AutoVarEmission &emission);
2356 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
2357 QualType::DestructionKind dtorKind);
2359 void EmitStaticVarDecl(const VarDecl &D,
2360 llvm::GlobalValue::LinkageTypes Linkage);
2365 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {}
2367 static ParamValue forDirect(llvm::Value *value) {
2368 return ParamValue(value, 0);
2370 static ParamValue forIndirect(Address addr) {
2371 assert(!addr.getAlignment().isZero());
2372 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity());
2375 bool isIndirect() const { return Alignment != 0; }
2376 llvm::Value *getAnyValue() const { return Value; }
2378 llvm::Value *getDirectValue() const {
2379 assert(!isIndirect());
2383 Address getIndirectAddress() const {
2384 assert(isIndirect());
2385 return Address(Value, CharUnits::fromQuantity(Alignment));
2389 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
2390 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo);
2392 /// protectFromPeepholes - Protect a value that we're intending to
2393 /// store to the side, but which will probably be used later, from
2394 /// aggressive peepholing optimizations that might delete it.
2396 /// Pass the result to unprotectFromPeepholes to declare that
2397 /// protection is no longer required.
2399 /// There's no particular reason why this shouldn't apply to
2400 /// l-values, it's just that no existing peepholes work on pointers.
2401 PeepholeProtection protectFromPeepholes(RValue rvalue);
2402 void unprotectFromPeepholes(PeepholeProtection protection);
2404 //===--------------------------------------------------------------------===//
2405 // Statement Emission
2406 //===--------------------------------------------------------------------===//
2408 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
2409 void EmitStopPoint(const Stmt *S);
2411 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
2412 /// this function even if there is no current insertion point.
2414 /// This function may clear the current insertion point; callers should use
2415 /// EnsureInsertPoint if they wish to subsequently generate code without first
2416 /// calling EmitBlock, EmitBranch, or EmitStmt.
2417 void EmitStmt(const Stmt *S);
2419 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
2420 /// necessarily require an insertion point or debug information; typically
2421 /// because the statement amounts to a jump or a container of other
2424 /// \return True if the statement was handled.
2425 bool EmitSimpleStmt(const Stmt *S);
2427 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2428 AggValueSlot AVS = AggValueSlot::ignored());
2429 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2430 bool GetLast = false,
2432 AggValueSlot::ignored());
2434 /// EmitLabel - Emit the block for the given label. It is legal to call this
2435 /// function even if there is no current insertion point.
2436 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2438 void EmitLabelStmt(const LabelStmt &S);
2439 void EmitAttributedStmt(const AttributedStmt &S);
2440 void EmitGotoStmt(const GotoStmt &S);
2441 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2442 void EmitIfStmt(const IfStmt &S);
2444 void EmitWhileStmt(const WhileStmt &S,
2445 ArrayRef<const Attr *> Attrs = None);
2446 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2447 void EmitForStmt(const ForStmt &S,
2448 ArrayRef<const Attr *> Attrs = None);
2449 void EmitReturnStmt(const ReturnStmt &S);
2450 void EmitDeclStmt(const DeclStmt &S);
2451 void EmitBreakStmt(const BreakStmt &S);
2452 void EmitContinueStmt(const ContinueStmt &S);
2453 void EmitSwitchStmt(const SwitchStmt &S);
2454 void EmitDefaultStmt(const DefaultStmt &S);
2455 void EmitCaseStmt(const CaseStmt &S);
2456 void EmitCaseStmtRange(const CaseStmt &S);
2457 void EmitAsmStmt(const AsmStmt &S);
2459 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2460 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2461 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2462 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2463 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2465 void EmitCoroutineBody(const CoroutineBodyStmt &S);
2466 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID);
2468 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2469 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2471 void EmitCXXTryStmt(const CXXTryStmt &S);
2472 void EmitSEHTryStmt(const SEHTryStmt &S);
2473 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2474 void EnterSEHTryStmt(const SEHTryStmt &S);
2475 void ExitSEHTryStmt(const SEHTryStmt &S);
2477 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
2478 const Stmt *OutlinedStmt);
2480 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2481 const SEHExceptStmt &Except);
2483 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2484 const SEHFinallyStmt &Finally);
2486 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
2487 llvm::Value *ParentFP,
2488 llvm::Value *EntryEBP);
2489 llvm::Value *EmitSEHExceptionCode();
2490 llvm::Value *EmitSEHExceptionInfo();
2491 llvm::Value *EmitSEHAbnormalTermination();
2493 /// Scan the outlined statement for captures from the parent function. For
2494 /// each capture, mark the capture as escaped and emit a call to
2495 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
2496 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2499 /// Recovers the address of a local in a parent function. ParentVar is the
2500 /// address of the variable used in the immediate parent function. It can
2501 /// either be an alloca or a call to llvm.localrecover if there are nested
2502 /// outlined functions. ParentFP is the frame pointer of the outermost parent
2504 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
2506 llvm::Value *ParentFP);
2508 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2509 ArrayRef<const Attr *> Attrs = None);
2511 /// Returns calculated size of the specified type.
2512 llvm::Value *getTypeSize(QualType Ty);
2513 LValue InitCapturedStruct(const CapturedStmt &S);
2514 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2515 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2516 Address GenerateCapturedStmtArgument(const CapturedStmt &S);
2517 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S);
2518 void GenerateOpenMPCapturedVars(const CapturedStmt &S,
2519 SmallVectorImpl<llvm::Value *> &CapturedVars);
2520 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy,
2521 SourceLocation Loc);
2522 /// \brief Perform element by element copying of arrays with type \a
2523 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2524 /// generated by \a CopyGen.
2526 /// \param DestAddr Address of the destination array.
2527 /// \param SrcAddr Address of the source array.
2528 /// \param OriginalType Type of destination and source arrays.
2529 /// \param CopyGen Copying procedure that copies value of single array element
2530 /// to another single array element.
2531 void EmitOMPAggregateAssign(
2532 Address DestAddr, Address SrcAddr, QualType OriginalType,
2533 const llvm::function_ref<void(Address, Address)> &CopyGen);
2534 /// \brief Emit proper copying of data from one variable to another.
2536 /// \param OriginalType Original type of the copied variables.
2537 /// \param DestAddr Destination address.
2538 /// \param SrcAddr Source address.
2539 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2540 /// type of the base array element).
2541 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2542 /// the base array element).
2543 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2545 void EmitOMPCopy(QualType OriginalType,
2546 Address DestAddr, Address SrcAddr,
2547 const VarDecl *DestVD, const VarDecl *SrcVD,
2549 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2550 /// \a X = \a E \a BO \a E.
2552 /// \param X Value to be updated.
2553 /// \param E Update value.
2554 /// \param BO Binary operation for update operation.
2555 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2556 /// expression, false otherwise.
2557 /// \param AO Atomic ordering of the generated atomic instructions.
2558 /// \param CommonGen Code generator for complex expressions that cannot be
2559 /// expressed through atomicrmw instruction.
2560 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2561 /// generated, <false, RValue::get(nullptr)> otherwise.
2562 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2563 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2564 llvm::AtomicOrdering AO, SourceLocation Loc,
2565 const llvm::function_ref<RValue(RValue)> &CommonGen);
2566 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2567 OMPPrivateScope &PrivateScope);
2568 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2569 OMPPrivateScope &PrivateScope);
2570 void EmitOMPUseDevicePtrClause(
2571 const OMPClause &C, OMPPrivateScope &PrivateScope,
2572 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap);
2573 /// \brief Emit code for copyin clause in \a D directive. The next code is
2574 /// generated at the start of outlined functions for directives:
2576 /// threadprivate_var1 = master_threadprivate_var1;
2577 /// operator=(threadprivate_var2, master_threadprivate_var2);
2579 /// __kmpc_barrier(&loc, global_tid);
2582 /// \param D OpenMP directive possibly with 'copyin' clause(s).
2583 /// \returns true if at least one copyin variable is found, false otherwise.
2584 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2585 /// \brief Emit initial code for lastprivate variables. If some variable is
2586 /// not also firstprivate, then the default initialization is used. Otherwise
2587 /// initialization of this variable is performed by EmitOMPFirstprivateClause
2590 /// \param D Directive that may have 'lastprivate' directives.
2591 /// \param PrivateScope Private scope for capturing lastprivate variables for
2592 /// proper codegen in internal captured statement.
2594 /// \returns true if there is at least one lastprivate variable, false
2596 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2597 OMPPrivateScope &PrivateScope);
2598 /// \brief Emit final copying of lastprivate values to original variables at
2599 /// the end of the worksharing or simd directive.
2601 /// \param D Directive that has at least one 'lastprivate' directives.
2602 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2603 /// it is the last iteration of the loop code in associated directive, or to
2604 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2605 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2607 llvm::Value *IsLastIterCond = nullptr);
2608 /// Emit initial code for linear clauses.
2609 void EmitOMPLinearClause(const OMPLoopDirective &D,
2610 CodeGenFunction::OMPPrivateScope &PrivateScope);
2611 /// Emit final code for linear clauses.
2612 /// \param CondGen Optional conditional code for final part of codegen for
2614 void EmitOMPLinearClauseFinal(
2615 const OMPLoopDirective &D,
2616 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2617 /// \brief Emit initial code for reduction variables. Creates reduction copies
2618 /// and initializes them with the values according to OpenMP standard.
2620 /// \param D Directive (possibly) with the 'reduction' clause.
2621 /// \param PrivateScope Private scope for capturing reduction variables for
2622 /// proper codegen in internal captured statement.
2624 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2625 OMPPrivateScope &PrivateScope);
2626 /// \brief Emit final update of reduction values to original variables at
2627 /// the end of the directive.
2629 /// \param D Directive that has at least one 'reduction' directives.
2630 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
2631 /// \brief Emit initial code for linear variables. Creates private copies
2632 /// and initializes them with the values according to OpenMP standard.
2634 /// \param D Directive (possibly) with the 'linear' clause.
2635 void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2637 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/,
2638 llvm::Value * /*OutlinedFn*/,
2639 const OMPTaskDataTy & /*Data*/)>
2641 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S,
2642 const RegionCodeGenTy &BodyGen,
2643 const TaskGenTy &TaskGen, OMPTaskDataTy &Data);
2645 void EmitOMPParallelDirective(const OMPParallelDirective &S);
2646 void EmitOMPSimdDirective(const OMPSimdDirective &S);
2647 void EmitOMPForDirective(const OMPForDirective &S);
2648 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2649 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2650 void EmitOMPSectionDirective(const OMPSectionDirective &S);
2651 void EmitOMPSingleDirective(const OMPSingleDirective &S);
2652 void EmitOMPMasterDirective(const OMPMasterDirective &S);
2653 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2654 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2655 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2656 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2657 void EmitOMPTaskDirective(const OMPTaskDirective &S);
2658 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2659 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2660 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2661 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2662 void EmitOMPFlushDirective(const OMPFlushDirective &S);
2663 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2664 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2665 void EmitOMPTargetDirective(const OMPTargetDirective &S);
2666 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S);
2667 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S);
2668 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S);
2669 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S);
2670 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S);
2672 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S);
2673 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2675 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2676 void EmitOMPCancelDirective(const OMPCancelDirective &S);
2677 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S);
2678 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S);
2679 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S);
2680 void EmitOMPDistributeDirective(const OMPDistributeDirective &S);
2681 void EmitOMPDistributeLoop(const OMPDistributeDirective &S);
2682 void EmitOMPDistributeParallelForDirective(
2683 const OMPDistributeParallelForDirective &S);
2684 void EmitOMPDistributeParallelForSimdDirective(
2685 const OMPDistributeParallelForSimdDirective &S);
2686 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
2687 void EmitOMPTargetParallelForSimdDirective(
2688 const OMPTargetParallelForSimdDirective &S);
2689 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
2690 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
2692 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
2693 void EmitOMPTeamsDistributeParallelForSimdDirective(
2694 const OMPTeamsDistributeParallelForSimdDirective &S);
2695 void EmitOMPTeamsDistributeParallelForDirective(
2696 const OMPTeamsDistributeParallelForDirective &S);
2697 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S);
2698 void EmitOMPTargetTeamsDistributeDirective(
2699 const OMPTargetTeamsDistributeDirective &S);
2700 void EmitOMPTargetTeamsDistributeParallelForDirective(
2701 const OMPTargetTeamsDistributeParallelForDirective &S);
2702 void EmitOMPTargetTeamsDistributeParallelForSimdDirective(
2703 const OMPTargetTeamsDistributeParallelForSimdDirective &S);
2704 void EmitOMPTargetTeamsDistributeSimdDirective(
2705 const OMPTargetTeamsDistributeSimdDirective &S);
2707 /// Emit outlined function for the target directive.
2708 static std::pair<llvm::Function * /*OutlinedFn*/,
2709 llvm::Constant * /*OutlinedFnID*/>
2710 EmitOMPTargetDirectiveOutlinedFunction(CodeGenModule &CGM,
2711 const OMPTargetDirective &S,
2712 StringRef ParentName,
2713 bool IsOffloadEntry);
2714 /// \brief Emit inner loop of the worksharing/simd construct.
2716 /// \param S Directive, for which the inner loop must be emitted.
2717 /// \param RequiresCleanup true, if directive has some associated private
2719 /// \param LoopCond Bollean condition for loop continuation.
2720 /// \param IncExpr Increment expression for loop control variable.
2721 /// \param BodyGen Generator for the inner body of the inner loop.
2722 /// \param PostIncGen Genrator for post-increment code (required for ordered
2723 /// loop directvies).
2724 void EmitOMPInnerLoop(
2725 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2726 const Expr *IncExpr,
2727 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2728 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2730 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2731 /// Emit initial code for loop counters of loop-based directives.
2732 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S,
2733 OMPPrivateScope &LoopScope);
2736 /// Helpers for blocks
2737 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
2739 /// Helpers for the OpenMP loop directives.
2740 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2741 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false);
2742 void EmitOMPSimdFinal(
2743 const OMPLoopDirective &D,
2744 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen);
2745 /// \brief Emit code for the worksharing loop-based directive.
2746 /// \return true, if this construct has any lastprivate clause, false -
2748 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
2749 void EmitOMPOuterLoop(bool IsMonotonic, bool DynamicOrOrdered,
2750 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered,
2751 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2752 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind,
2753 bool IsMonotonic, const OMPLoopDirective &S,
2754 OMPPrivateScope &LoopScope, bool Ordered, Address LB,
2755 Address UB, Address ST, Address IL,
2756 llvm::Value *Chunk);
2757 void EmitOMPDistributeOuterLoop(
2758 OpenMPDistScheduleClauseKind ScheduleKind,
2759 const OMPDistributeDirective &S, OMPPrivateScope &LoopScope,
2760 Address LB, Address UB, Address ST, Address IL, llvm::Value *Chunk);
2761 /// \brief Emit code for sections directive.
2762 void EmitSections(const OMPExecutableDirective &S);
2766 //===--------------------------------------------------------------------===//
2767 // LValue Expression Emission
2768 //===--------------------------------------------------------------------===//
2770 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2771 RValue GetUndefRValue(QualType Ty);
2773 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2774 /// and issue an ErrorUnsupported style diagnostic (using the
2776 RValue EmitUnsupportedRValue(const Expr *E,
2779 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2780 /// an ErrorUnsupported style diagnostic (using the provided Name).
2781 LValue EmitUnsupportedLValue(const Expr *E,
2784 /// EmitLValue - Emit code to compute a designator that specifies the location
2785 /// of the expression.
2787 /// This can return one of two things: a simple address or a bitfield
2788 /// reference. In either case, the LLVM Value* in the LValue structure is
2789 /// guaranteed to be an LLVM pointer type.
2791 /// If this returns a bitfield reference, nothing about the pointee type of
2792 /// the LLVM value is known: For example, it may not be a pointer to an
2795 /// If this returns a normal address, and if the lvalue's C type is fixed
2796 /// size, this method guarantees that the returned pointer type will point to
2797 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
2798 /// variable length type, this is not possible.
2800 LValue EmitLValue(const Expr *E);
2802 /// \brief Same as EmitLValue but additionally we generate checking code to
2803 /// guard against undefined behavior. This is only suitable when we know
2804 /// that the address will be used to access the object.
2805 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2807 RValue convertTempToRValue(Address addr, QualType type,
2808 SourceLocation Loc);
2810 void EmitAtomicInit(Expr *E, LValue lvalue);
2812 bool LValueIsSuitableForInlineAtomic(LValue Src);
2814 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2815 AggValueSlot Slot = AggValueSlot::ignored());
2817 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2818 llvm::AtomicOrdering AO, bool IsVolatile = false,
2819 AggValueSlot slot = AggValueSlot::ignored());
2821 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2823 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2824 bool IsVolatile, bool isInit);
2826 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2827 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2828 llvm::AtomicOrdering Success =
2829 llvm::AtomicOrdering::SequentiallyConsistent,
2830 llvm::AtomicOrdering Failure =
2831 llvm::AtomicOrdering::SequentiallyConsistent,
2832 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2834 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2835 const llvm::function_ref<RValue(RValue)> &UpdateOp,
2838 /// EmitToMemory - Change a scalar value from its value
2839 /// representation to its in-memory representation.
2840 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2842 /// EmitFromMemory - Change a scalar value from its memory
2843 /// representation to its value representation.
2844 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2846 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2847 /// care to appropriately convert from the memory representation to
2848 /// the LLVM value representation.
2849 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty,
2851 AlignmentSource AlignSource =
2852 AlignmentSource::Type,
2853 llvm::MDNode *TBAAInfo = nullptr,
2854 QualType TBAABaseTy = QualType(),
2855 uint64_t TBAAOffset = 0,
2856 bool isNontemporal = false);
2858 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2859 /// care to appropriately convert from the memory representation to
2860 /// the LLVM value representation. The l-value must be a simple
2862 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
2864 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2865 /// care to appropriately convert from the memory representation to
2866 /// the LLVM value representation.
2867 void EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2868 bool Volatile, QualType Ty,
2869 AlignmentSource AlignSource = AlignmentSource::Type,
2870 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
2871 QualType TBAABaseTy = QualType(),
2872 uint64_t TBAAOffset = 0, bool isNontemporal = false);
2874 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2875 /// care to appropriately convert from the memory representation to
2876 /// the LLVM value representation. The l-value must be a simple
2877 /// l-value. The isInit flag indicates whether this is an initialization.
2878 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2879 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
2881 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2882 /// this method emits the address of the lvalue, then loads the result as an
2883 /// rvalue, returning the rvalue.
2884 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
2885 RValue EmitLoadOfExtVectorElementLValue(LValue V);
2886 RValue EmitLoadOfBitfieldLValue(LValue LV);
2887 RValue EmitLoadOfGlobalRegLValue(LValue LV);
2889 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2890 /// lvalue, where both are guaranteed to the have the same type, and that type
2892 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
2893 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
2894 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
2896 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2897 /// as EmitStoreThroughLValue.
2899 /// \param Result [out] - If non-null, this will be set to a Value* for the
2900 /// bit-field contents after the store, appropriate for use as the result of
2901 /// an assignment to the bit-field.
2902 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2903 llvm::Value **Result=nullptr);
2905 /// Emit an l-value for an assignment (simple or compound) of complex type.
2906 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
2907 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
2908 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
2909 llvm::Value *&Result);
2911 // Note: only available for agg return types
2912 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
2913 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
2914 // Note: only available for agg return types
2915 LValue EmitCallExprLValue(const CallExpr *E);
2916 // Note: only available for agg return types
2917 LValue EmitVAArgExprLValue(const VAArgExpr *E);
2918 LValue EmitDeclRefLValue(const DeclRefExpr *E);
2919 LValue EmitStringLiteralLValue(const StringLiteral *E);
2920 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
2921 LValue EmitPredefinedLValue(const PredefinedExpr *E);
2922 LValue EmitUnaryOpLValue(const UnaryOperator *E);
2923 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2924 bool Accessed = false);
2925 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2926 bool IsLowerBound = true);
2927 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
2928 LValue EmitMemberExpr(const MemberExpr *E);
2929 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
2930 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
2931 LValue EmitInitListLValue(const InitListExpr *E);
2932 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
2933 LValue EmitCastLValue(const CastExpr *E);
2934 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2935 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
2937 Address EmitExtVectorElementLValue(LValue V);
2939 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
2941 Address EmitArrayToPointerDecay(const Expr *Array,
2942 AlignmentSource *AlignSource = nullptr);
2944 class ConstantEmission {
2945 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
2946 ConstantEmission(llvm::Constant *C, bool isReference)
2947 : ValueAndIsReference(C, isReference) {}
2949 ConstantEmission() {}
2950 static ConstantEmission forReference(llvm::Constant *C) {
2951 return ConstantEmission(C, true);
2953 static ConstantEmission forValue(llvm::Constant *C) {
2954 return ConstantEmission(C, false);
2957 explicit operator bool() const {
2958 return ValueAndIsReference.getOpaqueValue() != nullptr;
2961 bool isReference() const { return ValueAndIsReference.getInt(); }
2962 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
2963 assert(isReference());
2964 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
2965 refExpr->getType());
2968 llvm::Constant *getValue() const {
2969 assert(!isReference());
2970 return ValueAndIsReference.getPointer();
2974 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
2976 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
2977 AggValueSlot slot = AggValueSlot::ignored());
2978 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
2980 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2981 const ObjCIvarDecl *Ivar);
2982 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
2983 LValue EmitLValueForLambdaField(const FieldDecl *Field);
2985 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2986 /// if the Field is a reference, this will return the address of the reference
2987 /// and not the address of the value stored in the reference.
2988 LValue EmitLValueForFieldInitialization(LValue Base,
2989 const FieldDecl* Field);
2991 LValue EmitLValueForIvar(QualType ObjectTy,
2992 llvm::Value* Base, const ObjCIvarDecl *Ivar,
2993 unsigned CVRQualifiers);
2995 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2996 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2997 LValue EmitLambdaLValue(const LambdaExpr *E);
2998 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2999 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
3001 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
3002 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
3003 LValue EmitStmtExprLValue(const StmtExpr *E);
3004 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
3005 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
3006 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init);
3008 //===--------------------------------------------------------------------===//
3009 // Scalar Expression Emission
3010 //===--------------------------------------------------------------------===//
3012 /// EmitCall - Generate a call of the given function, expecting the given
3013 /// result type, and using the given argument list which specifies both the
3014 /// LLVM arguments and the types they were derived from.
3015 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee,
3016 ReturnValueSlot ReturnValue, const CallArgList &Args,
3017 llvm::Instruction **callOrInvoke = nullptr);
3019 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E,
3020 ReturnValueSlot ReturnValue,
3021 llvm::Value *Chain = nullptr);
3022 RValue EmitCallExpr(const CallExpr *E,
3023 ReturnValueSlot ReturnValue = ReturnValueSlot());
3024 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3025 CGCallee EmitCallee(const Expr *E);
3027 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl);
3029 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3030 const Twine &name = "");
3031 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
3032 ArrayRef<llvm::Value*> args,
3033 const Twine &name = "");
3034 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3035 const Twine &name = "");
3036 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
3037 ArrayRef<llvm::Value*> args,
3038 const Twine &name = "");
3040 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
3041 ArrayRef<llvm::Value *> Args,
3042 const Twine &Name = "");
3043 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3044 ArrayRef<llvm::Value*> args,
3045 const Twine &name = "");
3046 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
3047 const Twine &name = "");
3048 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
3049 ArrayRef<llvm::Value*> args);
3051 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
3052 NestedNameSpecifier *Qual,
3055 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
3057 const CXXRecordDecl *RD);
3060 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method,
3061 const CGCallee &Callee,
3062 ReturnValueSlot ReturnValue, llvm::Value *This,
3063 llvm::Value *ImplicitParam,
3064 QualType ImplicitParamTy, const CallExpr *E,
3065 CallArgList *RtlArgs);
3066 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD,
3067 const CGCallee &Callee,
3068 llvm::Value *This, llvm::Value *ImplicitParam,
3069 QualType ImplicitParamTy, const CallExpr *E,
3071 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
3072 ReturnValueSlot ReturnValue);
3073 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
3074 const CXXMethodDecl *MD,
3075 ReturnValueSlot ReturnValue,
3077 NestedNameSpecifier *Qualifier,
3078 bool IsArrow, const Expr *Base);
3079 // Compute the object pointer.
3080 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
3081 llvm::Value *memberPtr,
3082 const MemberPointerType *memberPtrType,
3083 AlignmentSource *AlignSource = nullptr);
3084 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
3085 ReturnValueSlot ReturnValue);
3087 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
3088 const CXXMethodDecl *MD,
3089 ReturnValueSlot ReturnValue);
3090 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
3092 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
3093 ReturnValueSlot ReturnValue);
3095 RValue EmitCUDADevicePrintfCallExpr(const CallExpr *E,
3096 ReturnValueSlot ReturnValue);
3098 RValue EmitBuiltinExpr(const FunctionDecl *FD,
3099 unsigned BuiltinID, const CallExpr *E,
3100 ReturnValueSlot ReturnValue);
3102 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
3104 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
3105 /// is unhandled by the current target.
3106 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3108 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
3109 const llvm::CmpInst::Predicate Fp,
3110 const llvm::CmpInst::Predicate Ip,
3111 const llvm::Twine &Name = "");
3112 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3114 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
3115 unsigned LLVMIntrinsic,
3116 unsigned AltLLVMIntrinsic,
3117 const char *NameHint,
3120 SmallVectorImpl<llvm::Value *> &Ops,
3121 Address PtrOp0, Address PtrOp1);
3122 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
3123 unsigned Modifier, llvm::Type *ArgTy,
3125 llvm::Value *EmitNeonCall(llvm::Function *F,
3126 SmallVectorImpl<llvm::Value*> &O,
3128 unsigned shift = 0, bool rightshift = false);
3129 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
3130 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
3131 bool negateForRightShift);
3132 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
3133 llvm::Type *Ty, bool usgn, const char *name);
3134 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
3135 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3137 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
3138 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3139 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3140 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3141 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3142 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
3143 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
3147 enum class MSVCIntrin;
3150 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E);
3152 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
3153 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
3154 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
3155 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
3156 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
3157 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
3158 const ObjCMethodDecl *MethodWithObjects);
3159 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
3160 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
3161 ReturnValueSlot Return = ReturnValueSlot());
3163 /// Retrieves the default cleanup kind for an ARC cleanup.
3164 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
3165 CleanupKind getARCCleanupKind() {
3166 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
3167 ? NormalAndEHCleanup : NormalCleanup;
3171 void EmitARCInitWeak(Address addr, llvm::Value *value);
3172 void EmitARCDestroyWeak(Address addr);
3173 llvm::Value *EmitARCLoadWeak(Address addr);
3174 llvm::Value *EmitARCLoadWeakRetained(Address addr);
3175 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored);
3176 void EmitARCCopyWeak(Address dst, Address src);
3177 void EmitARCMoveWeak(Address dst, Address src);
3178 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
3179 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
3180 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
3181 bool resultIgnored);
3182 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value,
3183 bool resultIgnored);
3184 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
3185 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
3186 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
3187 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise);
3188 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
3189 llvm::Value *EmitARCAutorelease(llvm::Value *value);
3190 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
3191 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
3192 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
3193 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value);
3195 std::pair<LValue,llvm::Value*>
3196 EmitARCStoreAutoreleasing(const BinaryOperator *e);
3197 std::pair<LValue,llvm::Value*>
3198 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
3199 std::pair<LValue,llvm::Value*>
3200 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored);
3202 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
3203 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
3204 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
3206 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
3207 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e,
3208 bool allowUnsafeClaim);
3209 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
3210 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
3211 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr);
3213 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
3215 static Destroyer destroyARCStrongImprecise;
3216 static Destroyer destroyARCStrongPrecise;
3217 static Destroyer destroyARCWeak;
3219 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
3220 llvm::Value *EmitObjCAutoreleasePoolPush();
3221 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
3222 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
3223 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
3225 /// \brief Emits a reference binding to the passed in expression.
3226 RValue EmitReferenceBindingToExpr(const Expr *E);
3228 //===--------------------------------------------------------------------===//
3229 // Expression Emission
3230 //===--------------------------------------------------------------------===//
3232 // Expressions are broken into three classes: scalar, complex, aggregate.
3234 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
3235 /// scalar type, returning the result.
3236 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
3238 /// Emit a conversion from the specified type to the specified destination
3239 /// type, both of which are LLVM scalar types.
3240 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
3241 QualType DstTy, SourceLocation Loc);
3243 /// Emit a conversion from the specified complex type to the specified
3244 /// destination type, where the destination type is an LLVM scalar type.
3245 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
3247 SourceLocation Loc);
3249 /// EmitAggExpr - Emit the computation of the specified expression
3250 /// of aggregate type. The result is computed into the given slot,
3251 /// which may be null to indicate that the value is not needed.
3252 void EmitAggExpr(const Expr *E, AggValueSlot AS);
3254 /// EmitAggExprToLValue - Emit the computation of the specified expression of
3255 /// aggregate type into a temporary LValue.
3256 LValue EmitAggExprToLValue(const Expr *E);
3258 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3259 /// make sure it survives garbage collection until this point.
3260 void EmitExtendGCLifetime(llvm::Value *object);
3262 /// EmitComplexExpr - Emit the computation of the specified expression of
3263 /// complex type, returning the result.
3264 ComplexPairTy EmitComplexExpr(const Expr *E,
3265 bool IgnoreReal = false,
3266 bool IgnoreImag = false);
3268 /// EmitComplexExprIntoLValue - Emit the given expression of complex
3269 /// type and place its result into the specified l-value.
3270 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
3272 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
3273 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
3275 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
3276 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
3278 Address emitAddrOfRealComponent(Address complex, QualType complexType);
3279 Address emitAddrOfImagComponent(Address complex, QualType complexType);
3281 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3282 /// global variable that has already been created for it. If the initializer
3283 /// has a different type than GV does, this may free GV and return a different
3284 /// one. Otherwise it just returns GV.
3285 llvm::GlobalVariable *
3286 AddInitializerToStaticVarDecl(const VarDecl &D,
3287 llvm::GlobalVariable *GV);
3290 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
3291 /// variable with global storage.
3292 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
3295 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
3296 llvm::Constant *Addr);
3298 /// Call atexit() with a function that passes the given argument to
3299 /// the given function.
3300 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
3301 llvm::Constant *addr);
3303 /// Emit code in this function to perform a guarded variable
3304 /// initialization. Guarded initializations are used when it's not
3305 /// possible to prove that an initialization will be done exactly
3306 /// once, e.g. with a static local variable or a static data member
3307 /// of a class template.
3308 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
3311 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
3313 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
3314 ArrayRef<llvm::Function *> CXXThreadLocals,
3315 Address Guard = Address::invalid());
3317 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
3319 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
3320 const std::vector<std::pair<llvm::WeakVH,
3321 llvm::Constant*> > &DtorsAndObjects);
3323 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
3325 llvm::GlobalVariable *Addr,
3328 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
3330 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp);
3332 void enterFullExpression(const ExprWithCleanups *E) {
3333 if (E->getNumObjects() == 0) return;
3334 enterNonTrivialFullExpression(E);
3336 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
3338 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
3340 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
3342 RValue EmitAtomicExpr(AtomicExpr *E);
3344 //===--------------------------------------------------------------------===//
3345 // Annotations Emission
3346 //===--------------------------------------------------------------------===//
3348 /// Emit an annotation call (intrinsic or builtin).
3349 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
3350 llvm::Value *AnnotatedVal,
3351 StringRef AnnotationStr,
3352 SourceLocation Location);
3354 /// Emit local annotations for the local variable V, declared by D.
3355 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
3357 /// Emit field annotations for the given field & value. Returns the
3358 /// annotation result.
3359 Address EmitFieldAnnotations(const FieldDecl *D, Address V);
3361 //===--------------------------------------------------------------------===//
3363 //===--------------------------------------------------------------------===//
3365 /// ContainsLabel - Return true if the statement contains a label in it. If
3366 /// this statement is not executed normally, it not containing a label means
3367 /// that we can just remove the code.
3368 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
3370 /// containsBreak - Return true if the statement contains a break out of it.
3371 /// If the statement (recursively) contains a switch or loop with a break
3372 /// inside of it, this is fine.
3373 static bool containsBreak(const Stmt *S);
3375 /// Determine if the given statement might introduce a declaration into the
3376 /// current scope, by being a (possibly-labelled) DeclStmt.
3377 static bool mightAddDeclToScope(const Stmt *S);
3379 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3380 /// to a constant, or if it does but contains a label, return false. If it
3381 /// constant folds return true and set the boolean result in Result.
3382 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result,
3383 bool AllowLabels = false);
3385 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
3386 /// to a constant, or if it does but contains a label, return false. If it
3387 /// constant folds return true and set the folded value.
3388 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result,
3389 bool AllowLabels = false);
3391 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
3392 /// if statement) to the specified blocks. Based on the condition, this might
3393 /// try to simplify the codegen of the conditional based on the branch.
3394 /// TrueCount should be the number of times we expect the condition to
3395 /// evaluate to true based on PGO data.
3396 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
3397 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
3399 /// \brief Emit a description of a type in a format suitable for passing to
3400 /// a runtime sanitizer handler.
3401 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
3403 /// \brief Convert a value into a format suitable for passing to a runtime
3404 /// sanitizer handler.
3405 llvm::Value *EmitCheckValue(llvm::Value *V);
3407 /// \brief Emit a description of a source location in a format suitable for
3408 /// passing to a runtime sanitizer handler.
3409 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
3411 /// \brief Create a basic block that will call a handler function in a
3412 /// sanitizer runtime with the provided arguments, and create a conditional
3414 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3415 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs,
3416 ArrayRef<llvm::Value *> DynamicArgs);
3418 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath
3419 /// if Cond if false.
3420 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond,
3421 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
3422 ArrayRef<llvm::Constant *> StaticArgs);
3424 /// \brief Create a basic block that will call the trap intrinsic, and emit a
3425 /// conditional branch to it, for the -ftrapv checks.
3426 void EmitTrapCheck(llvm::Value *Checked);
3428 /// \brief Emit a call to trap or debugtrap and attach function attribute
3429 /// "trap-func-name" if specified.
3430 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
3432 /// \brief Emit a cross-DSO CFI failure handling function.
3433 void EmitCfiCheckFail();
3435 /// \brief Create a check for a function parameter that may potentially be
3436 /// declared as non-null.
3437 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
3438 const FunctionDecl *FD, unsigned ParmNum);
3440 /// EmitCallArg - Emit a single call argument.
3441 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
3443 /// EmitDelegateCallArg - We are performing a delegate call; that
3444 /// is, the current function is delegating to another one. Produce
3445 /// a r-value suitable for passing the given parameter.
3446 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
3447 SourceLocation loc);
3449 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
3450 /// point operation, expressed as the maximum relative error in ulp.
3451 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
3454 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
3455 void EmitReturnOfRValue(RValue RV, QualType Ty);
3457 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
3459 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
3460 DeferredReplacements;
3462 /// Set the address of a local variable.
3463 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) {
3464 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!");
3465 LocalDeclMap.insert({VD, Addr});
3468 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
3469 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
3471 /// \param AI - The first function argument of the expansion.
3472 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
3473 SmallVectorImpl<llvm::Value *>::iterator &AI);
3475 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
3476 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
3477 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
3478 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
3479 SmallVectorImpl<llvm::Value *> &IRCallArgs,
3480 unsigned &IRCallArgPos);
3482 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
3483 const Expr *InputExpr, std::string &ConstraintStr);
3485 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
3486 LValue InputValue, QualType InputType,
3487 std::string &ConstraintStr,
3488 SourceLocation Loc);
3490 /// \brief Attempts to statically evaluate the object size of E. If that
3491 /// fails, emits code to figure the size of E out for us. This is
3492 /// pass_object_size aware.
3493 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
3494 llvm::IntegerType *ResType);
3496 /// \brief Emits the size of E, as required by __builtin_object_size. This
3497 /// function is aware of pass_object_size parameters, and will act accordingly
3498 /// if E is a parameter with the pass_object_size attribute.
3499 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type,
3500 llvm::IntegerType *ResType);
3504 // Determine whether the given argument is an Objective-C method
3505 // that may have type parameters in its signature.
3506 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
3507 const DeclContext *dc = method->getDeclContext();
3508 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
3509 return classDecl->getTypeParamListAsWritten();
3512 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
3513 return catDecl->getTypeParamList();
3519 template<typename T>
3520 static bool isObjCMethodWithTypeParams(const T *) { return false; }
3523 enum class EvaluationOrder {
3524 ///! No language constraints on evaluation order.
3526 ///! Language semantics require left-to-right evaluation.
3528 ///! Language semantics require right-to-left evaluation.
3532 /// EmitCallArgs - Emit call arguments for a function.
3533 template <typename T>
3534 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
3535 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3536 const FunctionDecl *CalleeDecl = nullptr,
3537 unsigned ParamsToSkip = 0,
3538 EvaluationOrder Order = EvaluationOrder::Default) {
3539 SmallVector<QualType, 16> ArgTypes;
3540 CallExpr::const_arg_iterator Arg = ArgRange.begin();
3542 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
3543 "Can't skip parameters if type info is not provided");
3544 if (CallArgTypeInfo) {
3546 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
3549 // First, use the argument types that the type info knows about
3550 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
3551 E = CallArgTypeInfo->param_type_end();
3552 I != E; ++I, ++Arg) {
3553 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
3554 assert((isGenericMethod ||
3555 ((*I)->isVariablyModifiedType() ||
3556 (*I).getNonReferenceType()->isObjCRetainableType() ||
3558 .getCanonicalType((*I).getNonReferenceType())
3561 .getCanonicalType((*Arg)->getType())
3563 "type mismatch in call argument!");
3564 ArgTypes.push_back(*I);
3568 // Either we've emitted all the call args, or we have a call to variadic
3570 assert((Arg == ArgRange.end() || !CallArgTypeInfo ||
3571 CallArgTypeInfo->isVariadic()) &&
3572 "Extra arguments in non-variadic function!");
3574 // If we still have any arguments, emit them using the type of the argument.
3575 for (auto *A : llvm::make_range(Arg, ArgRange.end()))
3576 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType());
3578 EmitCallArgs(Args, ArgTypes, ArgRange, CalleeDecl, ParamsToSkip, Order);
3581 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
3582 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
3583 const FunctionDecl *CalleeDecl = nullptr,
3584 unsigned ParamsToSkip = 0,
3585 EvaluationOrder Order = EvaluationOrder::Default);
3587 /// EmitPointerWithAlignment - Given an expression with a pointer
3588 /// type, emit the value and compute our best estimate of the
3589 /// alignment of the pointee.
3591 /// Note that this function will conservatively fall back on the type
3594 /// \param Source - If non-null, this will be initialized with
3595 /// information about the source of the alignment. Note that this
3596 /// function will conservatively fall back on the type when it
3597 /// doesn't recognize the expression, which means that sometimes
3599 /// a worst-case One
3600 /// reasonable way to use this information is when there's a
3601 /// language guarantee that the pointer must be aligned to some
3602 /// stricter value, and we're simply trying to ensure that
3603 /// sufficiently obvious uses of under-aligned objects don't get
3604 /// miscompiled; for example, a placement new into the address of
3605 /// a local variable. In such a case, it's quite reasonable to
3606 /// just ignore the returned alignment when it isn't from an
3607 /// explicit source.
3608 Address EmitPointerWithAlignment(const Expr *Addr,
3609 AlignmentSource *Source = nullptr);
3611 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK);
3614 QualType getVarArgType(const Expr *Arg);
3616 const TargetCodeGenInfo &getTargetHooks() const {
3617 return CGM.getTargetCodeGenInfo();
3620 void EmitDeclMetadata();
3622 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType,
3623 const AutoVarEmission &emission);
3625 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
3627 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3630 /// Helper class with most of the code for saving a value for a
3631 /// conditional expression cleanup.
3632 struct DominatingLLVMValue {
3633 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3635 /// Answer whether the given value needs extra work to be saved.
3636 static bool needsSaving(llvm::Value *value) {
3637 // If it's not an instruction, we don't need to save.
3638 if (!isa<llvm::Instruction>(value)) return false;
3640 // If it's an instruction in the entry block, we don't need to save.
3641 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3642 return (block != &block->getParent()->getEntryBlock());
3645 /// Try to save the given value.
3646 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3647 if (!needsSaving(value)) return saved_type(value, false);
3649 // Otherwise, we need an alloca.
3650 auto align = CharUnits::fromQuantity(
3651 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType()));
3653 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save");
3654 CGF.Builder.CreateStore(value, alloca);
3656 return saved_type(alloca.getPointer(), true);
3659 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3660 // If the value says it wasn't saved, trust that it's still dominating.
3661 if (!value.getInt()) return value.getPointer();
3663 // Otherwise, it should be an alloca instruction, as set up in save().
3664 auto alloca = cast<llvm::AllocaInst>(value.getPointer());
3665 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment());
3669 /// A partial specialization of DominatingValue for llvm::Values that
3670 /// might be llvm::Instructions.
3671 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3673 static type restore(CodeGenFunction &CGF, saved_type value) {
3674 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3678 /// A specialization of DominatingValue for Address.
3679 template <> struct DominatingValue<Address> {
3680 typedef Address type;
3683 DominatingLLVMValue::saved_type SavedValue;
3684 CharUnits Alignment;
3687 static bool needsSaving(type value) {
3688 return DominatingLLVMValue::needsSaving(value.getPointer());
3690 static saved_type save(CodeGenFunction &CGF, type value) {
3691 return { DominatingLLVMValue::save(CGF, value.getPointer()),
3692 value.getAlignment() };
3694 static type restore(CodeGenFunction &CGF, saved_type value) {
3695 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue),
3700 /// A specialization of DominatingValue for RValue.
3701 template <> struct DominatingValue<RValue> {
3702 typedef RValue type;
3704 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3705 AggregateAddress, ComplexAddress };
3709 unsigned Align : 29;
3710 saved_type(llvm::Value *v, Kind k, unsigned a = 0)
3711 : Value(v), K(k), Align(a) {}
3714 static bool needsSaving(RValue value);
3715 static saved_type save(CodeGenFunction &CGF, RValue value);
3716 RValue restore(CodeGenFunction &CGF);
3718 // implementations in CGCleanup.cpp
3721 static bool needsSaving(type value) {
3722 return saved_type::needsSaving(value);
3724 static saved_type save(CodeGenFunction &CGF, type value) {
3725 return saved_type::save(CGF, value);
3727 static type restore(CodeGenFunction &CGF, saved_type value) {
3728 return value.restore(CGF);
3732 } // end namespace CodeGen
3733 } // end namespace clang