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 "clang/AST/CharUnits.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Basic/ABI.h"
29 #include "clang/Basic/CapturedStmt.h"
30 #include "clang/Basic/OpenMPKinds.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Frontend/CodeGenOptions.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/Support/Debug.h"
53 class CXXDestructorDecl;
54 class CXXForRangeStmt;
58 class EnumConstantDecl;
60 class FunctionProtoType;
62 class ObjCContainerDecl;
63 class ObjCInterfaceDecl;
66 class ObjCImplementationDecl;
67 class ObjCPropertyImplDecl;
69 class TargetCodeGenInfo;
71 class ObjCForCollectionStmt;
73 class ObjCAtThrowStmt;
74 class ObjCAtSynchronizedStmt;
75 class ObjCAutoreleasePoolStmt;
84 class BlockFieldFlags;
86 /// The kind of evaluation to perform on values of a particular
87 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
90 /// TODO: should vectors maybe be split out into their own thing?
91 enum TypeEvaluationKind {
97 /// CodeGenFunction - This class organizes the per-function state that is used
98 /// while generating LLVM code.
99 class CodeGenFunction : public CodeGenTypeCache {
100 CodeGenFunction(const CodeGenFunction &) = delete;
101 void operator=(const CodeGenFunction &) = delete;
103 friend class CGCXXABI;
105 /// A jump destination is an abstract label, branching to which may
106 /// require a jump out through normal cleanups.
108 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
109 JumpDest(llvm::BasicBlock *Block,
110 EHScopeStack::stable_iterator Depth,
112 : Block(Block), ScopeDepth(Depth), Index(Index) {}
114 bool isValid() const { return Block != nullptr; }
115 llvm::BasicBlock *getBlock() const { return Block; }
116 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
117 unsigned getDestIndex() const { return Index; }
119 // This should be used cautiously.
120 void setScopeDepth(EHScopeStack::stable_iterator depth) {
125 llvm::BasicBlock *Block;
126 EHScopeStack::stable_iterator ScopeDepth;
130 CodeGenModule &CGM; // Per-module state.
131 const TargetInfo &Target;
133 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
134 LoopInfoStack LoopStack;
137 /// \brief CGBuilder insert helper. This function is called after an
138 /// instruction is created using Builder.
139 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
140 llvm::BasicBlock *BB,
141 llvm::BasicBlock::iterator InsertPt) const;
143 /// CurFuncDecl - Holds the Decl for the current outermost
144 /// non-closure context.
145 const Decl *CurFuncDecl;
146 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
147 const Decl *CurCodeDecl;
148 const CGFunctionInfo *CurFnInfo;
150 llvm::Function *CurFn;
152 /// CurGD - The GlobalDecl for the current function being compiled.
155 /// PrologueCleanupDepth - The cleanup depth enclosing all the
156 /// cleanups associated with the parameters.
157 EHScopeStack::stable_iterator PrologueCleanupDepth;
159 /// ReturnBlock - Unified return block.
160 JumpDest ReturnBlock;
162 /// ReturnValue - The temporary alloca to hold the return value. This is null
163 /// iff the function has no return value.
164 llvm::Value *ReturnValue;
166 /// AllocaInsertPoint - This is an instruction in the entry block before which
167 /// we prefer to insert allocas.
168 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
170 /// \brief API for captured statement code generation.
171 class CGCapturedStmtInfo {
173 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
174 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
175 explicit CGCapturedStmtInfo(const CapturedStmt &S,
176 CapturedRegionKind K = CR_Default)
177 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
179 RecordDecl::field_iterator Field =
180 S.getCapturedRecordDecl()->field_begin();
181 for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
183 I != E; ++I, ++Field) {
184 if (I->capturesThis())
185 CXXThisFieldDecl = *Field;
186 else if (I->capturesVariable())
187 CaptureFields[I->getCapturedVar()] = *Field;
191 virtual ~CGCapturedStmtInfo();
193 CapturedRegionKind getKind() const { return Kind; }
195 virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
196 // \brief Retrieve the value of the context parameter.
197 virtual llvm::Value *getContextValue() const { return ThisValue; }
199 /// \brief Lookup the captured field decl for a variable.
200 virtual const FieldDecl *lookup(const VarDecl *VD) const {
201 return CaptureFields.lookup(VD);
204 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
205 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
207 static bool classof(const CGCapturedStmtInfo *) {
211 /// \brief Emit the captured statement body.
212 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
213 CGF.incrementProfileCounter(S);
217 /// \brief Get the name of the capture helper.
218 virtual StringRef getHelperName() const { return "__captured_stmt"; }
221 /// \brief The kind of captured statement being generated.
222 CapturedRegionKind Kind;
224 /// \brief Keep the map between VarDecl and FieldDecl.
225 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
227 /// \brief The base address of the captured record, passed in as the first
228 /// argument of the parallel region function.
229 llvm::Value *ThisValue;
231 /// \brief Captured 'this' type.
232 FieldDecl *CXXThisFieldDecl;
234 CGCapturedStmtInfo *CapturedStmtInfo;
236 /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
237 class CGCapturedStmtRAII {
239 CodeGenFunction &CGF;
240 CGCapturedStmtInfo *PrevCapturedStmtInfo;
242 CGCapturedStmtRAII(CodeGenFunction &CGF,
243 CGCapturedStmtInfo *NewCapturedStmtInfo)
244 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
245 CGF.CapturedStmtInfo = NewCapturedStmtInfo;
247 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
250 /// BoundsChecking - Emit run-time bounds checks. Higher values mean
251 /// potentially higher performance penalties.
252 unsigned char BoundsChecking;
254 /// \brief Sanitizers enabled for this function.
255 SanitizerSet SanOpts;
257 /// \brief True if CodeGen currently emits code implementing sanitizer checks.
258 bool IsSanitizerScope;
260 /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
261 class SanitizerScope {
262 CodeGenFunction *CGF;
264 SanitizerScope(CodeGenFunction *CGF);
268 /// In C++, whether we are code generating a thunk. This controls whether we
269 /// should emit cleanups.
272 /// In ARC, whether we should autorelease the return value.
273 bool AutoreleaseResult;
275 /// Whether we processed a Microsoft-style asm block during CodeGen. These can
276 /// potentially set the return value.
279 /// True if the current function is an outlined SEH helper. This can be a
280 /// finally block or filter expression.
281 bool IsOutlinedSEHHelper;
283 const CodeGen::CGBlockInfo *BlockInfo;
284 llvm::Value *BlockPointer;
286 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
287 FieldDecl *LambdaThisCaptureField;
289 /// \brief A mapping from NRVO variables to the flags used to indicate
290 /// when the NRVO has been applied to this variable.
291 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
293 EHScopeStack EHStack;
294 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
295 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
297 /// Header for data within LifetimeExtendedCleanupStack.
298 struct LifetimeExtendedCleanupHeader {
299 /// The size of the following cleanup object.
301 /// The kind of cleanup to push: a value from the CleanupKind enumeration.
304 size_t getSize() const { return Size; }
305 CleanupKind getKind() const { return Kind; }
308 /// i32s containing the indexes of the cleanup destinations.
309 llvm::AllocaInst *NormalCleanupDest;
311 unsigned NextCleanupDestIndex;
313 /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
314 CGBlockInfo *FirstBlockInfo;
316 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
317 llvm::BasicBlock *EHResumeBlock;
319 /// The exception slot. All landing pads write the current exception pointer
320 /// into this alloca.
321 llvm::Value *ExceptionSlot;
323 /// The selector slot. Under the MandatoryCleanup model, all landing pads
324 /// write the current selector value into this alloca.
325 llvm::AllocaInst *EHSelectorSlot;
327 llvm::AllocaInst *AbnormalTerminationSlot;
329 /// The implicit parameter to SEH filter functions of type
330 /// 'EXCEPTION_POINTERS*'.
331 ImplicitParamDecl *SEHPointersDecl;
333 /// Emits a landing pad for the current EH stack.
334 llvm::BasicBlock *EmitLandingPad();
336 llvm::BasicBlock *getInvokeDestImpl();
339 typename DominatingValue<T>::saved_type saveValueInCond(T value) {
340 return DominatingValue<T>::save(*this, value);
344 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
346 SmallVector<llvm::Value*, 8> ObjCEHValueStack;
348 /// A class controlling the emission of a finally block.
350 /// Where the catchall's edge through the cleanup should go.
351 JumpDest RethrowDest;
353 /// A function to call to enter the catch.
354 llvm::Constant *BeginCatchFn;
356 /// An i1 variable indicating whether or not the @finally is
357 /// running for an exception.
358 llvm::AllocaInst *ForEHVar;
360 /// An i8* variable into which the exception pointer to rethrow
362 llvm::AllocaInst *SavedExnVar;
365 void enter(CodeGenFunction &CGF, const Stmt *Finally,
366 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
367 llvm::Constant *rethrowFn);
368 void exit(CodeGenFunction &CGF);
371 /// Returns true inside SEH __try blocks.
372 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
374 /// pushFullExprCleanup - Push a cleanup to be run at the end of the
375 /// current full-expression. Safe against the possibility that
376 /// we're currently inside a conditionally-evaluated expression.
377 template <class T, class... As>
378 void pushFullExprCleanup(CleanupKind kind, As... A) {
379 // If we're not in a conditional branch, or if none of the
380 // arguments requires saving, then use the unconditional cleanup.
381 if (!isInConditionalBranch())
382 return EHStack.pushCleanup<T>(kind, A...);
384 // Stash values in a tuple so we can guarantee the order of saves.
385 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
386 SavedTuple Saved{saveValueInCond(A)...};
388 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
389 EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
390 initFullExprCleanup();
393 /// \brief Queue a cleanup to be pushed after finishing the current
395 template <class T, class... As>
396 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
397 assert(!isInConditionalBranch() && "can't defer conditional cleanup");
399 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
401 size_t OldSize = LifetimeExtendedCleanupStack.size();
402 LifetimeExtendedCleanupStack.resize(
403 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
405 static_assert(sizeof(Header) % llvm::AlignOf<T>::Alignment == 0,
406 "Cleanup will be allocated on misaligned address");
407 char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
408 new (Buffer) LifetimeExtendedCleanupHeader(Header);
409 new (Buffer + sizeof(Header)) T(A...);
412 /// Set up the last cleaup that was pushed as a conditional
413 /// full-expression cleanup.
414 void initFullExprCleanup();
416 /// PushDestructorCleanup - Push a cleanup to call the
417 /// complete-object destructor of an object of the given type at the
418 /// given address. Does nothing if T is not a C++ class type with a
419 /// non-trivial destructor.
420 void PushDestructorCleanup(QualType T, llvm::Value *Addr);
422 /// PushDestructorCleanup - Push a cleanup to call the
423 /// complete-object variant of the given destructor on the object at
424 /// the given address.
425 void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
428 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
429 /// process all branch fixups.
430 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
432 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
433 /// The block cannot be reactivated. Pops it if it's the top of the
436 /// \param DominatingIP - An instruction which is known to
437 /// dominate the current IP (if set) and which lies along
438 /// all paths of execution between the current IP and the
439 /// the point at which the cleanup comes into scope.
440 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
441 llvm::Instruction *DominatingIP);
443 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
444 /// Cannot be used to resurrect a deactivated cleanup.
446 /// \param DominatingIP - An instruction which is known to
447 /// dominate the current IP (if set) and which lies along
448 /// all paths of execution between the current IP and the
449 /// the point at which the cleanup comes into scope.
450 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
451 llvm::Instruction *DominatingIP);
453 /// \brief Enters a new scope for capturing cleanups, all of which
454 /// will be executed once the scope is exited.
455 class RunCleanupsScope {
456 EHScopeStack::stable_iterator CleanupStackDepth;
457 size_t LifetimeExtendedCleanupStackSize;
458 bool OldDidCallStackSave;
463 RunCleanupsScope(const RunCleanupsScope &) = delete;
464 void operator=(const RunCleanupsScope &) = delete;
467 CodeGenFunction& CGF;
470 /// \brief Enter a new cleanup scope.
471 explicit RunCleanupsScope(CodeGenFunction &CGF)
472 : PerformCleanup(true), CGF(CGF)
474 CleanupStackDepth = CGF.EHStack.stable_begin();
475 LifetimeExtendedCleanupStackSize =
476 CGF.LifetimeExtendedCleanupStack.size();
477 OldDidCallStackSave = CGF.DidCallStackSave;
478 CGF.DidCallStackSave = false;
481 /// \brief Exit this cleanup scope, emitting any accumulated
483 ~RunCleanupsScope() {
484 if (PerformCleanup) {
485 CGF.DidCallStackSave = OldDidCallStackSave;
486 CGF.PopCleanupBlocks(CleanupStackDepth,
487 LifetimeExtendedCleanupStackSize);
491 /// \brief Determine whether this scope requires any cleanups.
492 bool requiresCleanups() const {
493 return CGF.EHStack.stable_begin() != CleanupStackDepth;
496 /// \brief Force the emission of cleanups now, instead of waiting
497 /// until this object is destroyed.
498 void ForceCleanup() {
499 assert(PerformCleanup && "Already forced cleanup");
500 CGF.DidCallStackSave = OldDidCallStackSave;
501 CGF.PopCleanupBlocks(CleanupStackDepth,
502 LifetimeExtendedCleanupStackSize);
503 PerformCleanup = false;
507 class LexicalScope : public RunCleanupsScope {
509 SmallVector<const LabelDecl*, 4> Labels;
510 LexicalScope *ParentScope;
512 LexicalScope(const LexicalScope &) = delete;
513 void operator=(const LexicalScope &) = delete;
516 /// \brief Enter a new cleanup scope.
517 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
518 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
519 CGF.CurLexicalScope = this;
520 if (CGDebugInfo *DI = CGF.getDebugInfo())
521 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
524 void addLabel(const LabelDecl *label) {
525 assert(PerformCleanup && "adding label to dead scope?");
526 Labels.push_back(label);
529 /// \brief Exit this cleanup scope, emitting any accumulated
532 if (CGDebugInfo *DI = CGF.getDebugInfo())
533 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
535 // If we should perform a cleanup, force them now. Note that
536 // this ends the cleanup scope before rescoping any labels.
537 if (PerformCleanup) {
538 ApplyDebugLocation DL(CGF, Range.getEnd());
543 /// \brief Force the emission of cleanups now, instead of waiting
544 /// until this object is destroyed.
545 void ForceCleanup() {
546 CGF.CurLexicalScope = ParentScope;
547 RunCleanupsScope::ForceCleanup();
553 void rescopeLabels();
556 /// \brief The scope used to remap some variables as private in the OpenMP
557 /// loop body (or other captured region emitted without outlining), and to
558 /// restore old vars back on exit.
559 class OMPPrivateScope : public RunCleanupsScope {
560 typedef llvm::DenseMap<const VarDecl *, llvm::Value *> VarDeclMapTy;
561 VarDeclMapTy SavedLocals;
562 VarDeclMapTy SavedPrivates;
565 OMPPrivateScope(const OMPPrivateScope &) = delete;
566 void operator=(const OMPPrivateScope &) = delete;
569 /// \brief Enter a new OpenMP private scope.
570 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
572 /// \brief Registers \a LocalVD variable as a private and apply \a
573 /// PrivateGen function for it to generate corresponding private variable.
574 /// \a PrivateGen returns an address of the generated private variable.
575 /// \return true if the variable is registered as private, false if it has
576 /// been privatized already.
578 addPrivate(const VarDecl *LocalVD,
579 const std::function<llvm::Value *()> &PrivateGen) {
580 assert(PerformCleanup && "adding private to dead scope");
581 if (SavedLocals.count(LocalVD) > 0) return false;
582 SavedLocals[LocalVD] = CGF.LocalDeclMap.lookup(LocalVD);
583 CGF.LocalDeclMap.erase(LocalVD);
584 SavedPrivates[LocalVD] = PrivateGen();
585 CGF.LocalDeclMap[LocalVD] = SavedLocals[LocalVD];
589 /// \brief Privatizes local variables previously registered as private.
590 /// Registration is separate from the actual privatization to allow
591 /// initializers use values of the original variables, not the private one.
592 /// This is important, for example, if the private variable is a class
593 /// variable initialized by a constructor that references other private
594 /// variables. But at initialization original variables must be used, not
596 /// \return true if at least one variable was privatized, false otherwise.
598 for (auto VDPair : SavedPrivates) {
599 CGF.LocalDeclMap[VDPair.first] = VDPair.second;
601 SavedPrivates.clear();
602 return !SavedLocals.empty();
605 void ForceCleanup() {
606 RunCleanupsScope::ForceCleanup();
607 // Remap vars back to the original values.
608 for (auto I : SavedLocals) {
609 CGF.LocalDeclMap[I.first] = I.second;
614 /// \brief Exit scope - all the mapped variables are restored.
621 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
622 /// that have been added.
623 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
625 /// \brief Takes the old cleanup stack size and emits the cleanup blocks
626 /// that have been added, then adds all lifetime-extended cleanups from
627 /// the given position to the stack.
628 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
629 size_t OldLifetimeExtendedStackSize);
631 void ResolveBranchFixups(llvm::BasicBlock *Target);
633 /// The given basic block lies in the current EH scope, but may be a
634 /// target of a potentially scope-crossing jump; get a stable handle
635 /// to which we can perform this jump later.
636 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
637 return JumpDest(Target,
638 EHStack.getInnermostNormalCleanup(),
639 NextCleanupDestIndex++);
642 /// The given basic block lies in the current EH scope, but may be a
643 /// target of a potentially scope-crossing jump; get a stable handle
644 /// to which we can perform this jump later.
645 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
646 return getJumpDestInCurrentScope(createBasicBlock(Name));
649 /// EmitBranchThroughCleanup - Emit a branch from the current insert
650 /// block through the normal cleanup handling code (if any) and then
652 void EmitBranchThroughCleanup(JumpDest Dest);
654 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
655 /// specified destination obviously has no cleanups to run. 'false' is always
656 /// a conservatively correct answer for this method.
657 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
659 /// popCatchScope - Pops the catch scope at the top of the EHScope
660 /// stack, emitting any required code (other than the catch handlers
662 void popCatchScope();
664 llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
665 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
667 /// An object to manage conditionally-evaluated expressions.
668 class ConditionalEvaluation {
669 llvm::BasicBlock *StartBB;
672 ConditionalEvaluation(CodeGenFunction &CGF)
673 : StartBB(CGF.Builder.GetInsertBlock()) {}
675 void begin(CodeGenFunction &CGF) {
676 assert(CGF.OutermostConditional != this);
677 if (!CGF.OutermostConditional)
678 CGF.OutermostConditional = this;
681 void end(CodeGenFunction &CGF) {
682 assert(CGF.OutermostConditional != nullptr);
683 if (CGF.OutermostConditional == this)
684 CGF.OutermostConditional = nullptr;
687 /// Returns a block which will be executed prior to each
688 /// evaluation of the conditional code.
689 llvm::BasicBlock *getStartingBlock() const {
694 /// isInConditionalBranch - Return true if we're currently emitting
695 /// one branch or the other of a conditional expression.
696 bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
698 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
699 assert(isInConditionalBranch());
700 llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
701 new llvm::StoreInst(value, addr, &block->back());
704 /// An RAII object to record that we're evaluating a statement
706 class StmtExprEvaluation {
707 CodeGenFunction &CGF;
709 /// We have to save the outermost conditional: cleanups in a
710 /// statement expression aren't conditional just because the
712 ConditionalEvaluation *SavedOutermostConditional;
715 StmtExprEvaluation(CodeGenFunction &CGF)
716 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
717 CGF.OutermostConditional = nullptr;
720 ~StmtExprEvaluation() {
721 CGF.OutermostConditional = SavedOutermostConditional;
722 CGF.EnsureInsertPoint();
726 /// An object which temporarily prevents a value from being
727 /// destroyed by aggressive peephole optimizations that assume that
728 /// all uses of a value have been realized in the IR.
729 class PeepholeProtection {
730 llvm::Instruction *Inst;
731 friend class CodeGenFunction;
734 PeepholeProtection() : Inst(nullptr) {}
737 /// A non-RAII class containing all the information about a bound
738 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
739 /// this which makes individual mappings very simple; using this
740 /// class directly is useful when you have a variable number of
741 /// opaque values or don't want the RAII functionality for some
743 class OpaqueValueMappingData {
744 const OpaqueValueExpr *OpaqueValue;
746 CodeGenFunction::PeepholeProtection Protection;
748 OpaqueValueMappingData(const OpaqueValueExpr *ov,
750 : OpaqueValue(ov), BoundLValue(boundLValue) {}
752 OpaqueValueMappingData() : OpaqueValue(nullptr) {}
754 static bool shouldBindAsLValue(const Expr *expr) {
755 // gl-values should be bound as l-values for obvious reasons.
756 // Records should be bound as l-values because IR generation
757 // always keeps them in memory. Expressions of function type
758 // act exactly like l-values but are formally required to be
760 return expr->isGLValue() ||
761 expr->getType()->isFunctionType() ||
762 hasAggregateEvaluationKind(expr->getType());
765 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
766 const OpaqueValueExpr *ov,
768 if (shouldBindAsLValue(ov))
769 return bind(CGF, ov, CGF.EmitLValue(e));
770 return bind(CGF, ov, CGF.EmitAnyExpr(e));
773 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
774 const OpaqueValueExpr *ov,
776 assert(shouldBindAsLValue(ov));
777 CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
778 return OpaqueValueMappingData(ov, true);
781 static OpaqueValueMappingData bind(CodeGenFunction &CGF,
782 const OpaqueValueExpr *ov,
784 assert(!shouldBindAsLValue(ov));
785 CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
787 OpaqueValueMappingData data(ov, false);
789 // Work around an extremely aggressive peephole optimization in
790 // EmitScalarConversion which assumes that all other uses of a
792 data.Protection = CGF.protectFromPeepholes(rv);
797 bool isValid() const { return OpaqueValue != nullptr; }
798 void clear() { OpaqueValue = nullptr; }
800 void unbind(CodeGenFunction &CGF) {
801 assert(OpaqueValue && "no data to unbind!");
804 CGF.OpaqueLValues.erase(OpaqueValue);
806 CGF.OpaqueRValues.erase(OpaqueValue);
807 CGF.unprotectFromPeepholes(Protection);
812 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
813 class OpaqueValueMapping {
814 CodeGenFunction &CGF;
815 OpaqueValueMappingData Data;
818 static bool shouldBindAsLValue(const Expr *expr) {
819 return OpaqueValueMappingData::shouldBindAsLValue(expr);
822 /// Build the opaque value mapping for the given conditional
823 /// operator if it's the GNU ?: extension. This is a common
824 /// enough pattern that the convenience operator is really
827 OpaqueValueMapping(CodeGenFunction &CGF,
828 const AbstractConditionalOperator *op) : CGF(CGF) {
829 if (isa<ConditionalOperator>(op))
833 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
834 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
838 OpaqueValueMapping(CodeGenFunction &CGF,
839 const OpaqueValueExpr *opaqueValue,
841 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
844 OpaqueValueMapping(CodeGenFunction &CGF,
845 const OpaqueValueExpr *opaqueValue,
847 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
855 ~OpaqueValueMapping() {
856 if (Data.isValid()) Data.unbind(CGF);
860 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
861 /// number that holds the value.
862 std::pair<llvm::Type *, unsigned>
863 getByRefValueLLVMField(const ValueDecl *VD) const;
865 /// BuildBlockByrefAddress - Computes address location of the
866 /// variable which is declared as __block.
867 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
870 CGDebugInfo *DebugInfo;
871 bool DisableDebugInfo;
873 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
874 /// calling llvm.stacksave for multiple VLAs in the same scope.
875 bool DidCallStackSave;
877 /// IndirectBranch - The first time an indirect goto is seen we create a block
878 /// with an indirect branch. Every time we see the address of a label taken,
879 /// we add the label to the indirect goto. Every subsequent indirect goto is
880 /// codegen'd as a jump to the IndirectBranch's basic block.
881 llvm::IndirectBrInst *IndirectBranch;
883 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
885 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
886 DeclMapTy LocalDeclMap;
888 /// Track escaped local variables with auto storage. Used during SEH
889 /// outlining to produce a call to llvm.frameescape.
890 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
892 /// LabelMap - This keeps track of the LLVM basic block for each C label.
893 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
895 // BreakContinueStack - This keeps track of where break and continue
896 // statements should jump to.
897 struct BreakContinue {
898 BreakContinue(JumpDest Break, JumpDest Continue)
899 : BreakBlock(Break), ContinueBlock(Continue) {}
902 JumpDest ContinueBlock;
904 SmallVector<BreakContinue, 8> BreakContinueStack;
908 /// Calculate branch weights appropriate for PGO data
909 llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
910 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
911 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
915 /// Increment the profiler's counter for the given statement.
916 void incrementProfileCounter(const Stmt *S) {
917 if (CGM.getCodeGenOpts().ProfileInstrGenerate)
918 PGO.emitCounterIncrement(Builder, S);
919 PGO.setCurrentStmt(S);
922 /// Get the profiler's count for the given statement.
923 uint64_t getProfileCount(const Stmt *S) {
924 Optional<uint64_t> Count = PGO.getStmtCount(S);
925 if (!Count.hasValue())
930 /// Set the profiler's current count.
931 void setCurrentProfileCount(uint64_t Count) {
932 PGO.setCurrentRegionCount(Count);
935 /// Get the profiler's current count. This is generally the count for the most
936 /// recently incremented counter.
937 uint64_t getCurrentProfileCount() {
938 return PGO.getCurrentRegionCount();
943 /// SwitchInsn - This is nearest current switch instruction. It is null if
944 /// current context is not in a switch.
945 llvm::SwitchInst *SwitchInsn;
946 /// The branch weights of SwitchInsn when doing instrumentation based PGO.
947 SmallVector<uint64_t, 16> *SwitchWeights;
949 /// CaseRangeBlock - This block holds if condition check for last case
950 /// statement range in current switch instruction.
951 llvm::BasicBlock *CaseRangeBlock;
953 /// OpaqueLValues - Keeps track of the current set of opaque value
955 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
956 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
958 // VLASizeMap - This keeps track of the associated size for each VLA type.
959 // We track this by the size expression rather than the type itself because
960 // in certain situations, like a const qualifier applied to an VLA typedef,
961 // multiple VLA types can share the same size expression.
962 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
963 // enter/leave scopes.
964 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
966 /// A block containing a single 'unreachable' instruction. Created
967 /// lazily by getUnreachableBlock().
968 llvm::BasicBlock *UnreachableBlock;
970 /// Counts of the number return expressions in the function.
971 unsigned NumReturnExprs;
973 /// Count the number of simple (constant) return expressions in the function.
974 unsigned NumSimpleReturnExprs;
976 /// The last regular (non-return) debug location (breakpoint) in the function.
977 SourceLocation LastStopPoint;
980 /// A scope within which we are constructing the fields of an object which
981 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
982 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
983 class FieldConstructionScope {
985 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This)
986 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
987 CGF.CXXDefaultInitExprThis = This;
989 ~FieldConstructionScope() {
990 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
994 CodeGenFunction &CGF;
995 llvm::Value *OldCXXDefaultInitExprThis;
998 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
999 /// is overridden to be the object under construction.
1000 class CXXDefaultInitExprScope {
1002 CXXDefaultInitExprScope(CodeGenFunction &CGF)
1003 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) {
1004 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis;
1006 ~CXXDefaultInitExprScope() {
1007 CGF.CXXThisValue = OldCXXThisValue;
1011 CodeGenFunction &CGF;
1012 llvm::Value *OldCXXThisValue;
1016 /// CXXThisDecl - When generating code for a C++ member function,
1017 /// this will hold the implicit 'this' declaration.
1018 ImplicitParamDecl *CXXABIThisDecl;
1019 llvm::Value *CXXABIThisValue;
1020 llvm::Value *CXXThisValue;
1022 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
1023 /// this expression.
1024 llvm::Value *CXXDefaultInitExprThis;
1026 /// CXXStructorImplicitParamDecl - When generating code for a constructor or
1027 /// destructor, this will hold the implicit argument (e.g. VTT).
1028 ImplicitParamDecl *CXXStructorImplicitParamDecl;
1029 llvm::Value *CXXStructorImplicitParamValue;
1031 /// OutermostConditional - Points to the outermost active
1032 /// conditional control. This is used so that we know if a
1033 /// temporary should be destroyed conditionally.
1034 ConditionalEvaluation *OutermostConditional;
1036 /// The current lexical scope.
1037 LexicalScope *CurLexicalScope;
1039 /// The current source location that should be used for exception
1041 SourceLocation CurEHLocation;
1043 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
1044 /// type as well as the field number that contains the actual data.
1045 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
1046 unsigned> > ByRefValueInfo;
1048 llvm::BasicBlock *TerminateLandingPad;
1049 llvm::BasicBlock *TerminateHandler;
1050 llvm::BasicBlock *TrapBB;
1052 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
1053 /// In the kernel metadata node, reference the kernel function and metadata
1054 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
1055 /// - A node for the vec_type_hint(<type>) qualifier contains string
1056 /// "vec_type_hint", an undefined value of the <type> data type,
1057 /// and a Boolean that is true if the <type> is integer and signed.
1058 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
1059 /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
1060 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
1061 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
1062 void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
1063 llvm::Function *Fn);
1066 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
1069 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
1070 ASTContext &getContext() const { return CGM.getContext(); }
1071 CGDebugInfo *getDebugInfo() {
1072 if (DisableDebugInfo)
1076 void disableDebugInfo() { DisableDebugInfo = true; }
1077 void enableDebugInfo() { DisableDebugInfo = false; }
1079 bool shouldUseFusedARCCalls() {
1080 return CGM.getCodeGenOpts().OptimizationLevel == 0;
1083 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
1085 /// Returns a pointer to the function's exception object and selector slot,
1086 /// which is assigned in every landing pad.
1087 llvm::Value *getExceptionSlot();
1088 llvm::Value *getEHSelectorSlot();
1090 /// Returns the contents of the function's exception object and selector
1092 llvm::Value *getExceptionFromSlot();
1093 llvm::Value *getSelectorFromSlot();
1095 llvm::Value *getNormalCleanupDestSlot();
1097 llvm::BasicBlock *getUnreachableBlock() {
1098 if (!UnreachableBlock) {
1099 UnreachableBlock = createBasicBlock("unreachable");
1100 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
1102 return UnreachableBlock;
1105 llvm::BasicBlock *getInvokeDest() {
1106 if (!EHStack.requiresLandingPad()) return nullptr;
1107 return getInvokeDestImpl();
1110 bool currentFunctionUsesSEHTry() const {
1111 const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
1112 return FD && FD->usesSEHTry();
1115 const TargetInfo &getTarget() const { return Target; }
1116 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
1118 //===--------------------------------------------------------------------===//
1120 //===--------------------------------------------------------------------===//
1122 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
1124 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1125 llvm::Value *arrayEndPointer,
1126 QualType elementType,
1127 Destroyer *destroyer);
1128 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1129 llvm::Value *arrayEnd,
1130 QualType elementType,
1131 Destroyer *destroyer);
1133 void pushDestroy(QualType::DestructionKind dtorKind,
1134 llvm::Value *addr, QualType type);
1135 void pushEHDestroy(QualType::DestructionKind dtorKind,
1136 llvm::Value *addr, QualType type);
1137 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
1138 Destroyer *destroyer, bool useEHCleanupForArray);
1139 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr,
1140 QualType type, Destroyer *destroyer,
1141 bool useEHCleanupForArray);
1142 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1143 llvm::Value *CompletePtr,
1144 QualType ElementType);
1145 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem);
1146 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
1147 bool useEHCleanupForArray);
1148 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type,
1149 Destroyer *destroyer,
1150 bool useEHCleanupForArray,
1152 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
1153 QualType type, Destroyer *destroyer,
1154 bool checkZeroLength, bool useEHCleanup);
1156 Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
1158 /// Determines whether an EH cleanup is required to destroy a type
1159 /// with the given destruction kind.
1160 bool needsEHCleanup(QualType::DestructionKind kind) {
1162 case QualType::DK_none:
1164 case QualType::DK_cxx_destructor:
1165 case QualType::DK_objc_weak_lifetime:
1166 return getLangOpts().Exceptions;
1167 case QualType::DK_objc_strong_lifetime:
1168 return getLangOpts().Exceptions &&
1169 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
1171 llvm_unreachable("bad destruction kind");
1174 CleanupKind getCleanupKind(QualType::DestructionKind kind) {
1175 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
1178 //===--------------------------------------------------------------------===//
1180 //===--------------------------------------------------------------------===//
1182 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
1184 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
1186 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
1187 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
1188 const ObjCPropertyImplDecl *PID);
1189 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
1190 const ObjCPropertyImplDecl *propImpl,
1191 const ObjCMethodDecl *GetterMothodDecl,
1192 llvm::Constant *AtomicHelperFn);
1194 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1195 ObjCMethodDecl *MD, bool ctor);
1197 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
1198 /// for the given property.
1199 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
1200 const ObjCPropertyImplDecl *PID);
1201 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1202 const ObjCPropertyImplDecl *propImpl,
1203 llvm::Constant *AtomicHelperFn);
1204 bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
1205 bool IvarTypeWithAggrGCObjects(QualType Ty);
1207 //===--------------------------------------------------------------------===//
1209 //===--------------------------------------------------------------------===//
1211 llvm::Value *EmitBlockLiteral(const BlockExpr *);
1212 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
1213 static void destroyBlockInfos(CGBlockInfo *info);
1214 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
1215 const CGBlockInfo &Info,
1217 llvm::Constant *BlockVarLayout);
1219 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
1220 const CGBlockInfo &Info,
1221 const DeclMapTy &ldm,
1222 bool IsLambdaConversionToBlock);
1224 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
1225 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
1226 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
1227 const ObjCPropertyImplDecl *PID);
1228 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
1229 const ObjCPropertyImplDecl *PID);
1230 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
1232 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
1234 class AutoVarEmission;
1236 void emitByrefStructureInit(const AutoVarEmission &emission);
1237 void enterByrefCleanup(const AutoVarEmission &emission);
1239 llvm::Value *LoadBlockStruct() {
1240 assert(BlockPointer && "no block pointer set!");
1241 return BlockPointer;
1244 void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
1245 void AllocateBlockDecl(const DeclRefExpr *E);
1246 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
1247 llvm::Type *BuildByRefType(const VarDecl *var);
1249 void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
1250 const CGFunctionInfo &FnInfo);
1251 /// \brief Emit code for the start of a function.
1252 /// \param Loc The location to be associated with the function.
1253 /// \param StartLoc The location of the function body.
1254 void StartFunction(GlobalDecl GD,
1257 const CGFunctionInfo &FnInfo,
1258 const FunctionArgList &Args,
1259 SourceLocation Loc = SourceLocation(),
1260 SourceLocation StartLoc = SourceLocation());
1262 void EmitConstructorBody(FunctionArgList &Args);
1263 void EmitDestructorBody(FunctionArgList &Args);
1264 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
1265 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
1266 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
1268 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
1269 CallArgList &CallArgs);
1270 void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
1271 void EmitLambdaBlockInvokeBody();
1272 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
1273 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
1274 void EmitAsanPrologueOrEpilogue(bool Prologue);
1276 /// \brief Emit the unified return block, trying to avoid its emission when
1278 /// \return The debug location of the user written return statement if the
1279 /// return block is is avoided.
1280 llvm::DebugLoc EmitReturnBlock();
1282 /// FinishFunction - Complete IR generation of the current function. It is
1283 /// legal to call this function even if there is no current insertion point.
1284 void FinishFunction(SourceLocation EndLoc=SourceLocation());
1286 void StartThunk(llvm::Function *Fn, GlobalDecl GD,
1287 const CGFunctionInfo &FnInfo);
1289 void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
1291 /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
1292 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
1293 llvm::Value *Callee);
1295 /// GenerateThunk - Generate a thunk for the given method.
1296 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
1297 GlobalDecl GD, const ThunkInfo &Thunk);
1299 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
1300 const CGFunctionInfo &FnInfo,
1301 GlobalDecl GD, const ThunkInfo &Thunk);
1303 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
1304 FunctionArgList &Args);
1306 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
1307 ArrayRef<VarDecl *> ArrayIndexes);
1309 /// InitializeVTablePointer - Initialize the vtable pointer of the given
1312 void InitializeVTablePointer(BaseSubobject Base,
1313 const CXXRecordDecl *NearestVBase,
1314 CharUnits OffsetFromNearestVBase,
1315 const CXXRecordDecl *VTableClass);
1317 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
1318 void InitializeVTablePointers(BaseSubobject Base,
1319 const CXXRecordDecl *NearestVBase,
1320 CharUnits OffsetFromNearestVBase,
1321 bool BaseIsNonVirtualPrimaryBase,
1322 const CXXRecordDecl *VTableClass,
1323 VisitedVirtualBasesSetTy& VBases);
1325 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
1327 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
1329 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
1331 enum CFITypeCheckKind {
1335 CFITCK_UnrelatedCast,
1338 /// \brief Derived is the presumed address of an object of type T after a
1339 /// cast. If T is a polymorphic class type, emit a check that the virtual
1340 /// table for Derived belongs to a class derived from T.
1341 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
1342 bool MayBeNull, CFITypeCheckKind TCK,
1343 SourceLocation Loc);
1345 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
1346 /// If vptr CFI is enabled, emit a check that VTable is valid.
1347 void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable,
1348 CFITypeCheckKind TCK, SourceLocation Loc);
1350 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
1351 /// RD using llvm.bitset.test.
1352 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
1353 CFITypeCheckKind TCK, SourceLocation Loc);
1355 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
1356 /// expr can be devirtualized.
1357 bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
1358 const CXXMethodDecl *MD);
1360 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
1361 /// given phase of destruction for a destructor. The end result
1362 /// should call destructors on members and base classes in reverse
1363 /// order of their construction.
1364 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
1366 /// ShouldInstrumentFunction - Return true if the current function should be
1367 /// instrumented with __cyg_profile_func_* calls
1368 bool ShouldInstrumentFunction();
1370 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
1371 /// instrumentation function with the current function and the call site, if
1372 /// function instrumentation is enabled.
1373 void EmitFunctionInstrumentation(const char *Fn);
1375 /// EmitMCountInstrumentation - Emit call to .mcount.
1376 void EmitMCountInstrumentation();
1378 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
1379 /// arguments for the given function. This is also responsible for naming the
1380 /// LLVM function arguments.
1381 void EmitFunctionProlog(const CGFunctionInfo &FI,
1383 const FunctionArgList &Args);
1385 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
1386 /// given temporary.
1387 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
1388 SourceLocation EndLoc);
1390 /// EmitStartEHSpec - Emit the start of the exception spec.
1391 void EmitStartEHSpec(const Decl *D);
1393 /// EmitEndEHSpec - Emit the end of the exception spec.
1394 void EmitEndEHSpec(const Decl *D);
1396 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
1397 llvm::BasicBlock *getTerminateLandingPad();
1399 /// getTerminateHandler - Return a handler (not a landing pad, just
1400 /// a catch handler) that just calls terminate. This is used when
1401 /// a terminate scope encloses a try.
1402 llvm::BasicBlock *getTerminateHandler();
1404 llvm::Type *ConvertTypeForMem(QualType T);
1405 llvm::Type *ConvertType(QualType T);
1406 llvm::Type *ConvertType(const TypeDecl *T) {
1407 return ConvertType(getContext().getTypeDeclType(T));
1410 /// LoadObjCSelf - Load the value of self. This function is only valid while
1411 /// generating code for an Objective-C method.
1412 llvm::Value *LoadObjCSelf();
1414 /// TypeOfSelfObject - Return type of object that this self represents.
1415 QualType TypeOfSelfObject();
1417 /// hasAggregateLLVMType - Return true if the specified AST type will map into
1418 /// an aggregate LLVM type or is void.
1419 static TypeEvaluationKind getEvaluationKind(QualType T);
1421 static bool hasScalarEvaluationKind(QualType T) {
1422 return getEvaluationKind(T) == TEK_Scalar;
1425 static bool hasAggregateEvaluationKind(QualType T) {
1426 return getEvaluationKind(T) == TEK_Aggregate;
1429 /// createBasicBlock - Create an LLVM basic block.
1430 llvm::BasicBlock *createBasicBlock(const Twine &name = "",
1431 llvm::Function *parent = nullptr,
1432 llvm::BasicBlock *before = nullptr) {
1434 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
1436 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
1440 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
1442 JumpDest getJumpDestForLabel(const LabelDecl *S);
1444 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
1445 /// another basic block, simplify it. This assumes that no other code could
1446 /// potentially reference the basic block.
1447 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
1449 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
1450 /// adding a fall-through branch from the current insert block if
1451 /// necessary. It is legal to call this function even if there is no current
1452 /// insertion point.
1454 /// IsFinished - If true, indicates that the caller has finished emitting
1455 /// branches to the given block and does not expect to emit code into it. This
1456 /// means the block can be ignored if it is unreachable.
1457 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
1459 /// EmitBlockAfterUses - Emit the given block somewhere hopefully
1460 /// near its uses, and leave the insertion point in it.
1461 void EmitBlockAfterUses(llvm::BasicBlock *BB);
1463 /// EmitBranch - Emit a branch to the specified basic block from the current
1464 /// insert block, taking care to avoid creation of branches from dummy
1465 /// blocks. It is legal to call this function even if there is no current
1466 /// insertion point.
1468 /// This function clears the current insertion point. The caller should follow
1469 /// calls to this function with calls to Emit*Block prior to generation new
1471 void EmitBranch(llvm::BasicBlock *Block);
1473 /// HaveInsertPoint - True if an insertion point is defined. If not, this
1474 /// indicates that the current code being emitted is unreachable.
1475 bool HaveInsertPoint() const {
1476 return Builder.GetInsertBlock() != nullptr;
1479 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
1480 /// emitted IR has a place to go. Note that by definition, if this function
1481 /// creates a block then that block is unreachable; callers may do better to
1482 /// detect when no insertion point is defined and simply skip IR generation.
1483 void EnsureInsertPoint() {
1484 if (!HaveInsertPoint())
1485 EmitBlock(createBasicBlock());
1488 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1489 /// specified stmt yet.
1490 void ErrorUnsupported(const Stmt *S, const char *Type);
1492 //===--------------------------------------------------------------------===//
1494 //===--------------------------------------------------------------------===//
1496 LValue MakeAddrLValue(llvm::Value *V, QualType T,
1497 CharUnits Alignment = CharUnits()) {
1498 return LValue::MakeAddr(V, T, Alignment, getContext(),
1499 CGM.getTBAAInfo(T));
1502 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
1504 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1505 /// block. The caller is responsible for setting an appropriate alignment on
1507 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
1508 const Twine &Name = "tmp");
1510 /// InitTempAlloca - Provide an initial value for the given alloca.
1511 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
1513 /// CreateIRTemp - Create a temporary IR object of the given type, with
1514 /// appropriate alignment. This routine should only be used when an temporary
1515 /// value needs to be stored into an alloca (for example, to avoid explicit
1516 /// PHI construction), but the type is the IR type, not the type appropriate
1517 /// for storing in memory.
1518 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
1520 /// CreateMemTemp - Create a temporary memory object of the given type, with
1521 /// appropriate alignment.
1522 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
1524 /// CreateAggTemp - Create a temporary memory object for the given
1526 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
1527 CharUnits Alignment = getContext().getTypeAlignInChars(T);
1528 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
1530 AggValueSlot::IsNotDestructed,
1531 AggValueSlot::DoesNotNeedGCBarriers,
1532 AggValueSlot::IsNotAliased);
1535 /// CreateInAllocaTmp - Create a temporary memory object for the given
1537 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca");
1539 /// Emit a cast to void* in the appropriate address space.
1540 llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
1542 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1543 /// expression and compare the result against zero, returning an Int1Ty value.
1544 llvm::Value *EvaluateExprAsBool(const Expr *E);
1546 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1547 void EmitIgnoredExpr(const Expr *E);
1549 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1550 /// any type. The result is returned as an RValue struct. If this is an
1551 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1552 /// the result should be returned.
1554 /// \param ignoreResult True if the resulting value isn't used.
1555 RValue EmitAnyExpr(const Expr *E,
1556 AggValueSlot aggSlot = AggValueSlot::ignored(),
1557 bool ignoreResult = false);
1559 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1560 // or the value of the expression, depending on how va_list is defined.
1561 llvm::Value *EmitVAListRef(const Expr *E);
1563 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1564 /// always be accessible even if no aggregate location is provided.
1565 RValue EmitAnyExprToTemp(const Expr *E);
1567 /// EmitAnyExprToMem - Emits the code necessary to evaluate an
1568 /// arbitrary expression into the given memory location.
1569 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1570 Qualifiers Quals, bool IsInitializer);
1572 void EmitAnyExprToExn(const Expr *E, llvm::Value *Addr);
1574 /// EmitExprAsInit - Emits the code necessary to initialize a
1575 /// location in memory with the given initializer.
1576 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
1577 bool capturedByInit);
1579 /// hasVolatileMember - returns true if aggregate type has a volatile
1581 bool hasVolatileMember(QualType T) {
1582 if (const RecordType *RT = T->getAs<RecordType>()) {
1583 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
1584 return RD->hasVolatileMember();
1588 /// EmitAggregateCopy - Emit an aggregate assignment.
1590 /// The difference to EmitAggregateCopy is that tail padding is not copied.
1591 /// This is required for correctness when assigning non-POD structures in C++.
1592 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1594 bool IsVolatile = hasVolatileMember(EltTy);
1595 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(),
1599 void EmitAggregateCopyCtor(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1600 QualType DestTy, QualType SrcTy) {
1601 CharUnits DestTypeAlign = getContext().getTypeAlignInChars(DestTy);
1602 CharUnits SrcTypeAlign = getContext().getTypeAlignInChars(SrcTy);
1603 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
1604 std::min(DestTypeAlign, SrcTypeAlign),
1605 /*IsAssignment=*/false);
1608 /// EmitAggregateCopy - Emit an aggregate copy.
1610 /// \param isVolatile - True iff either the source or the destination is
1612 /// \param isAssignment - If false, allow padding to be copied. This often
1613 /// yields more efficient.
1614 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1615 QualType EltTy, bool isVolatile=false,
1616 CharUnits Alignment = CharUnits::Zero(),
1617 bool isAssignment = false);
1619 /// StartBlock - Start new block named N. If insert block is a dummy block
1621 void StartBlock(const char *N);
1623 /// GetAddrOfLocalVar - Return the address of a local variable.
1624 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1625 llvm::Value *Res = LocalDeclMap[VD];
1626 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1630 /// getOpaqueLValueMapping - Given an opaque value expression (which
1631 /// must be mapped to an l-value), return its mapping.
1632 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
1633 assert(OpaqueValueMapping::shouldBindAsLValue(e));
1635 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
1636 it = OpaqueLValues.find(e);
1637 assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
1641 /// getOpaqueRValueMapping - Given an opaque value expression (which
1642 /// must be mapped to an r-value), return its mapping.
1643 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
1644 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
1646 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
1647 it = OpaqueRValues.find(e);
1648 assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
1652 /// getAccessedFieldNo - Given an encoded value and a result number, return
1653 /// the input field number being accessed.
1654 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1656 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
1657 llvm::BasicBlock *GetIndirectGotoBlock();
1659 /// EmitNullInitialization - Generate code to set a value of the given type to
1660 /// null, If the type contains data member pointers, they will be initialized
1661 /// to -1 in accordance with the Itanium C++ ABI.
1662 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1664 // EmitVAArg - Generate code to get an argument from the passed in pointer
1665 // and update it accordingly. The return value is a pointer to the argument.
1666 // FIXME: We should be able to get rid of this method and use the va_arg
1667 // instruction in LLVM instead once it works well enough.
1668 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1670 /// emitArrayLength - Compute the length of an array, even if it's a
1671 /// VLA, and drill down to the base element type.
1672 llvm::Value *emitArrayLength(const ArrayType *arrayType,
1674 llvm::Value *&addr);
1676 /// EmitVLASize - Capture all the sizes for the VLA expressions in
1677 /// the given variably-modified type and store them in the VLASizeMap.
1679 /// This function can be called with a null (unreachable) insert point.
1680 void EmitVariablyModifiedType(QualType Ty);
1682 /// getVLASize - Returns an LLVM value that corresponds to the size,
1683 /// in non-variably-sized elements, of a variable length array type,
1684 /// plus that largest non-variably-sized element type. Assumes that
1685 /// the type has already been emitted with EmitVariablyModifiedType.
1686 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
1687 std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
1689 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1690 /// generating code for an C++ member function.
1691 llvm::Value *LoadCXXThis() {
1692 assert(CXXThisValue && "no 'this' value for this function");
1693 return CXXThisValue;
1696 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1698 // FIXME: Every place that calls LoadCXXVTT is something
1699 // that needs to be abstracted properly.
1700 llvm::Value *LoadCXXVTT() {
1701 assert(CXXStructorImplicitParamValue && "no VTT value for this function");
1702 return CXXStructorImplicitParamValue;
1705 /// LoadCXXStructorImplicitParam - Load the implicit parameter
1706 /// for a constructor/destructor.
1707 llvm::Value *LoadCXXStructorImplicitParam() {
1708 assert(CXXStructorImplicitParamValue &&
1709 "no implicit argument value for this function");
1710 return CXXStructorImplicitParamValue;
1713 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1714 /// complete class to the given direct base.
1716 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1717 const CXXRecordDecl *Derived,
1718 const CXXRecordDecl *Base,
1719 bool BaseIsVirtual);
1721 /// GetAddressOfBaseClass - This function will add the necessary delta to the
1722 /// load of 'this' and returns address of the base class.
1723 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1724 const CXXRecordDecl *Derived,
1725 CastExpr::path_const_iterator PathBegin,
1726 CastExpr::path_const_iterator PathEnd,
1727 bool NullCheckValue, SourceLocation Loc);
1729 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1730 const CXXRecordDecl *Derived,
1731 CastExpr::path_const_iterator PathBegin,
1732 CastExpr::path_const_iterator PathEnd,
1733 bool NullCheckValue);
1735 /// GetVTTParameter - Return the VTT parameter that should be passed to a
1736 /// base constructor/destructor with virtual bases.
1737 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
1738 /// to ItaniumCXXABI.cpp together with all the references to VTT.
1739 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
1742 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1743 CXXCtorType CtorType,
1744 const FunctionArgList &Args,
1745 SourceLocation Loc);
1746 // It's important not to confuse this and the previous function. Delegating
1747 // constructors are the C++0x feature. The constructor delegate optimization
1748 // is used to reduce duplication in the base and complete consturctors where
1749 // they are substantially the same.
1750 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1751 const FunctionArgList &Args);
1752 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1753 bool ForVirtualBase, bool Delegating,
1754 llvm::Value *This, const CXXConstructExpr *E);
1756 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1757 llvm::Value *This, llvm::Value *Src,
1758 const CXXConstructExpr *E);
1760 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1761 const ConstantArrayType *ArrayTy,
1762 llvm::Value *ArrayPtr,
1763 const CXXConstructExpr *E,
1764 bool ZeroInitialization = false);
1766 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1767 llvm::Value *NumElements,
1768 llvm::Value *ArrayPtr,
1769 const CXXConstructExpr *E,
1770 bool ZeroInitialization = false);
1772 static Destroyer destroyCXXObject;
1774 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1775 bool ForVirtualBase, bool Delegating,
1778 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
1779 llvm::Type *ElementTy, llvm::Value *NewPtr,
1780 llvm::Value *NumElements,
1781 llvm::Value *AllocSizeWithoutCookie);
1783 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
1786 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
1787 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
1789 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1790 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1792 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1795 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1796 const Expr *Arg, bool IsDelete);
1798 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1799 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1800 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
1802 /// \brief Situations in which we might emit a check for the suitability of a
1803 /// pointer or glvalue.
1804 enum TypeCheckKind {
1805 /// Checking the operand of a load. Must be suitably sized and aligned.
1807 /// Checking the destination of a store. Must be suitably sized and aligned.
1809 /// Checking the bound value in a reference binding. Must be suitably sized
1810 /// and aligned, but is not required to refer to an object (until the
1811 /// reference is used), per core issue 453.
1812 TCK_ReferenceBinding,
1813 /// Checking the object expression in a non-static data member access. Must
1814 /// be an object within its lifetime.
1816 /// Checking the 'this' pointer for a call to a non-static member function.
1817 /// Must be an object within its lifetime.
1819 /// Checking the 'this' pointer for a constructor call.
1820 TCK_ConstructorCall,
1821 /// Checking the operand of a static_cast to a derived pointer type. Must be
1822 /// null or an object within its lifetime.
1823 TCK_DowncastPointer,
1824 /// Checking the operand of a static_cast to a derived reference type. Must
1825 /// be an object within its lifetime.
1826 TCK_DowncastReference,
1827 /// Checking the operand of a cast to a base object. Must be suitably sized
1830 /// Checking the operand of a cast to a virtual base object. Must be an
1831 /// object within its lifetime.
1832 TCK_UpcastToVirtualBase
1835 /// \brief Whether any type-checking sanitizers are enabled. If \c false,
1836 /// calls to EmitTypeCheck can be skipped.
1837 bool sanitizePerformTypeCheck() const;
1839 /// \brief Emit a check that \p V is the address of storage of the
1840 /// appropriate size and alignment for an object of type \p Type.
1841 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
1842 QualType Type, CharUnits Alignment = CharUnits::Zero(),
1843 bool SkipNullCheck = false);
1845 /// \brief Emit a check that \p Base points into an array object, which
1846 /// we can access at index \p Index. \p Accessed should be \c false if we
1847 /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
1848 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
1849 QualType IndexType, bool Accessed);
1851 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1852 bool isInc, bool isPre);
1853 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1854 bool isInc, bool isPre);
1856 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
1857 llvm::Value *OffsetValue = nullptr) {
1858 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
1862 //===--------------------------------------------------------------------===//
1863 // Declaration Emission
1864 //===--------------------------------------------------------------------===//
1866 /// EmitDecl - Emit a declaration.
1868 /// This function can be called with a null (unreachable) insert point.
1869 void EmitDecl(const Decl &D);
1871 /// EmitVarDecl - Emit a local variable declaration.
1873 /// This function can be called with a null (unreachable) insert point.
1874 void EmitVarDecl(const VarDecl &D);
1876 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
1877 bool capturedByInit);
1878 void EmitScalarInit(llvm::Value *init, LValue lvalue);
1880 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1881 llvm::Value *Address);
1883 /// \brief Determine whether the given initializer is trivial in the sense
1884 /// that it requires no code to be generated.
1885 bool isTrivialInitializer(const Expr *Init);
1887 /// EmitAutoVarDecl - Emit an auto variable declaration.
1889 /// This function can be called with a null (unreachable) insert point.
1890 void EmitAutoVarDecl(const VarDecl &D);
1892 class AutoVarEmission {
1893 friend class CodeGenFunction;
1895 const VarDecl *Variable;
1897 /// The alignment of the variable.
1898 CharUnits Alignment;
1900 /// The address of the alloca. Null if the variable was emitted
1901 /// as a global constant.
1902 llvm::Value *Address;
1904 llvm::Value *NRVOFlag;
1906 /// True if the variable is a __block variable.
1909 /// True if the variable is of aggregate type and has a constant
1911 bool IsConstantAggregate;
1913 /// Non-null if we should use lifetime annotations.
1914 llvm::Value *SizeForLifetimeMarkers;
1917 AutoVarEmission(Invalid) : Variable(nullptr) {}
1919 AutoVarEmission(const VarDecl &variable)
1920 : Variable(&variable), Address(nullptr), NRVOFlag(nullptr),
1921 IsByRef(false), IsConstantAggregate(false),
1922 SizeForLifetimeMarkers(nullptr) {}
1924 bool wasEmittedAsGlobal() const { return Address == nullptr; }
1927 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
1929 bool useLifetimeMarkers() const {
1930 return SizeForLifetimeMarkers != nullptr;
1932 llvm::Value *getSizeForLifetimeMarkers() const {
1933 assert(useLifetimeMarkers());
1934 return SizeForLifetimeMarkers;
1937 /// Returns the raw, allocated address, which is not necessarily
1938 /// the address of the object itself.
1939 llvm::Value *getAllocatedAddress() const {
1943 /// Returns the address of the object within this declaration.
1944 /// Note that this does not chase the forwarding pointer for
1946 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
1947 if (!IsByRef) return Address;
1949 auto F = CGF.getByRefValueLLVMField(Variable);
1950 return CGF.Builder.CreateStructGEP(F.first, Address, F.second,
1951 Variable->getNameAsString());
1954 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
1955 void EmitAutoVarInit(const AutoVarEmission &emission);
1956 void EmitAutoVarCleanups(const AutoVarEmission &emission);
1957 void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
1958 QualType::DestructionKind dtorKind);
1960 void EmitStaticVarDecl(const VarDecl &D,
1961 llvm::GlobalValue::LinkageTypes Linkage);
1963 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1964 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer,
1967 /// protectFromPeepholes - Protect a value that we're intending to
1968 /// store to the side, but which will probably be used later, from
1969 /// aggressive peepholing optimizations that might delete it.
1971 /// Pass the result to unprotectFromPeepholes to declare that
1972 /// protection is no longer required.
1974 /// There's no particular reason why this shouldn't apply to
1975 /// l-values, it's just that no existing peepholes work on pointers.
1976 PeepholeProtection protectFromPeepholes(RValue rvalue);
1977 void unprotectFromPeepholes(PeepholeProtection protection);
1979 //===--------------------------------------------------------------------===//
1980 // Statement Emission
1981 //===--------------------------------------------------------------------===//
1983 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1984 void EmitStopPoint(const Stmt *S);
1986 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1987 /// this function even if there is no current insertion point.
1989 /// This function may clear the current insertion point; callers should use
1990 /// EnsureInsertPoint if they wish to subsequently generate code without first
1991 /// calling EmitBlock, EmitBranch, or EmitStmt.
1992 void EmitStmt(const Stmt *S);
1994 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1995 /// necessarily require an insertion point or debug information; typically
1996 /// because the statement amounts to a jump or a container of other
1999 /// \return True if the statement was handled.
2000 bool EmitSimpleStmt(const Stmt *S);
2002 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
2003 AggValueSlot AVS = AggValueSlot::ignored());
2004 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S,
2005 bool GetLast = false,
2007 AggValueSlot::ignored());
2009 /// EmitLabel - Emit the block for the given label. It is legal to call this
2010 /// function even if there is no current insertion point.
2011 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
2013 void EmitLabelStmt(const LabelStmt &S);
2014 void EmitAttributedStmt(const AttributedStmt &S);
2015 void EmitGotoStmt(const GotoStmt &S);
2016 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
2017 void EmitIfStmt(const IfStmt &S);
2019 void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr,
2020 ArrayRef<const Attr *> Attrs);
2021 void EmitWhileStmt(const WhileStmt &S,
2022 ArrayRef<const Attr *> Attrs = None);
2023 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
2024 void EmitForStmt(const ForStmt &S,
2025 ArrayRef<const Attr *> Attrs = None);
2026 void EmitReturnStmt(const ReturnStmt &S);
2027 void EmitDeclStmt(const DeclStmt &S);
2028 void EmitBreakStmt(const BreakStmt &S);
2029 void EmitContinueStmt(const ContinueStmt &S);
2030 void EmitSwitchStmt(const SwitchStmt &S);
2031 void EmitDefaultStmt(const DefaultStmt &S);
2032 void EmitCaseStmt(const CaseStmt &S);
2033 void EmitCaseStmtRange(const CaseStmt &S);
2034 void EmitAsmStmt(const AsmStmt &S);
2036 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
2037 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
2038 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
2039 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
2040 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
2042 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2043 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
2045 void EmitCXXTryStmt(const CXXTryStmt &S);
2046 void EmitSEHTryStmt(const SEHTryStmt &S);
2047 void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
2048 void EnterSEHTryStmt(const SEHTryStmt &S);
2049 void ExitSEHTryStmt(const SEHTryStmt &S);
2051 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, StringRef Name,
2052 QualType RetTy, FunctionArgList &Args,
2053 const Stmt *OutlinedStmt);
2055 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
2056 const SEHExceptStmt &Except);
2058 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
2059 const SEHFinallyStmt &Finally);
2061 void EmitSEHExceptionCodeSave();
2062 llvm::Value *EmitSEHExceptionCode();
2063 llvm::Value *EmitSEHExceptionInfo();
2064 llvm::Value *EmitSEHAbnormalTermination();
2066 /// Scan the outlined statement for captures from the parent function. For
2067 /// each capture, mark the capture as escaped and emit a call to
2068 /// llvm.framerecover. Insert the framerecover result into the LocalDeclMap.
2069 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
2070 llvm::Value *ParentFP);
2072 void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
2073 ArrayRef<const Attr *> Attrs = None);
2075 LValue InitCapturedStruct(const CapturedStmt &S);
2076 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
2077 void GenerateCapturedStmtFunctionProlog(const CapturedStmt &S);
2078 llvm::Function *GenerateCapturedStmtFunctionEpilog(const CapturedStmt &S);
2079 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
2080 llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S);
2081 /// \brief Perform element by element copying of arrays with type \a
2082 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
2083 /// generated by \a CopyGen.
2085 /// \param DestAddr Address of the destination array.
2086 /// \param SrcAddr Address of the source array.
2087 /// \param OriginalType Type of destination and source arrays.
2088 /// \param CopyGen Copying procedure that copies value of single array element
2089 /// to another single array element.
2090 void EmitOMPAggregateAssign(
2091 llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
2092 const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen);
2093 /// \brief Emit proper copying of data from one variable to another.
2095 /// \param OriginalType Original type of the copied variables.
2096 /// \param DestAddr Destination address.
2097 /// \param SrcAddr Source address.
2098 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
2099 /// type of the base array element).
2100 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
2101 /// the base array element).
2102 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
2104 void EmitOMPCopy(CodeGenFunction &CGF, QualType OriginalType,
2105 llvm::Value *DestAddr, llvm::Value *SrcAddr,
2106 const VarDecl *DestVD, const VarDecl *SrcVD,
2108 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
2109 /// \a X = \a E \a BO \a E.
2111 /// \param X Value to be updated.
2112 /// \param E Update value.
2113 /// \param BO Binary operation for update operation.
2114 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
2115 /// expression, false otherwise.
2116 /// \param AO Atomic ordering of the generated atomic instructions.
2117 /// \param CommonGen Code generator for complex expressions that cannot be
2118 /// expressed through atomicrmw instruction.
2119 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
2120 /// generated, <false, RValue::get(nullptr)> otherwise.
2121 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
2122 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
2123 llvm::AtomicOrdering AO, SourceLocation Loc,
2124 const llvm::function_ref<RValue(RValue)> &CommonGen);
2125 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
2126 OMPPrivateScope &PrivateScope);
2127 void EmitOMPPrivateClause(const OMPExecutableDirective &D,
2128 OMPPrivateScope &PrivateScope);
2129 /// \brief Emit code for copyin clause in \a D directive. The next code is
2130 /// generated at the start of outlined functions for directives:
2132 /// threadprivate_var1 = master_threadprivate_var1;
2133 /// operator=(threadprivate_var2, master_threadprivate_var2);
2135 /// __kmpc_barrier(&loc, global_tid);
2138 /// \param D OpenMP directive possibly with 'copyin' clause(s).
2139 /// \returns true if at least one copyin variable is found, false otherwise.
2140 bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
2141 /// \brief Emit initial code for lastprivate variables. If some variable is
2142 /// not also firstprivate, then the default initialization is used. Otherwise
2143 /// initialization of this variable is performed by EmitOMPFirstprivateClause
2146 /// \param D Directive that may have 'lastprivate' directives.
2147 /// \param PrivateScope Private scope for capturing lastprivate variables for
2148 /// proper codegen in internal captured statement.
2150 /// \returns true if there is at least one lastprivate variable, false
2152 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
2153 OMPPrivateScope &PrivateScope);
2154 /// \brief Emit final copying of lastprivate values to original variables at
2155 /// the end of the worksharing or simd directive.
2157 /// \param D Directive that has at least one 'lastprivate' directives.
2158 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
2159 /// it is the last iteration of the loop code in associated directive, or to
2160 /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
2161 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
2162 llvm::Value *IsLastIterCond = nullptr);
2163 /// \brief Emit initial code for reduction variables. Creates reduction copies
2164 /// and initializes them with the values according to OpenMP standard.
2166 /// \param D Directive (possibly) with the 'reduction' clause.
2167 /// \param PrivateScope Private scope for capturing reduction variables for
2168 /// proper codegen in internal captured statement.
2170 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
2171 OMPPrivateScope &PrivateScope);
2172 /// \brief Emit final update of reduction values to original variables at
2173 /// the end of the directive.
2175 /// \param D Directive that has at least one 'reduction' directives.
2176 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
2177 /// \brief Emit initial code for linear variables. Creates private copies
2178 /// and initializes them with the values according to OpenMP standard.
2180 /// \param D Directive (possibly) with the 'linear' clause.
2181 void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
2183 void EmitOMPParallelDirective(const OMPParallelDirective &S);
2184 void EmitOMPSimdDirective(const OMPSimdDirective &S);
2185 void EmitOMPForDirective(const OMPForDirective &S);
2186 void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
2187 void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
2188 void EmitOMPSectionDirective(const OMPSectionDirective &S);
2189 void EmitOMPSingleDirective(const OMPSingleDirective &S);
2190 void EmitOMPMasterDirective(const OMPMasterDirective &S);
2191 void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
2192 void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
2193 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
2194 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
2195 void EmitOMPTaskDirective(const OMPTaskDirective &S);
2196 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
2197 void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
2198 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
2199 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
2200 void EmitOMPFlushDirective(const OMPFlushDirective &S);
2201 void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
2202 void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
2203 void EmitOMPTargetDirective(const OMPTargetDirective &S);
2204 void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
2206 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
2207 void EmitOMPCancelDirective(const OMPCancelDirective &S);
2209 /// \brief Emit inner loop of the worksharing/simd construct.
2211 /// \param S Directive, for which the inner loop must be emitted.
2212 /// \param RequiresCleanup true, if directive has some associated private
2214 /// \param LoopCond Bollean condition for loop continuation.
2215 /// \param IncExpr Increment expression for loop control variable.
2216 /// \param BodyGen Generator for the inner body of the inner loop.
2217 /// \param PostIncGen Genrator for post-increment code (required for ordered
2218 /// loop directvies).
2219 void EmitOMPInnerLoop(
2220 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
2221 const Expr *IncExpr,
2222 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
2223 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
2225 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
2229 /// Helpers for the OpenMP loop directives.
2230 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
2231 void EmitOMPSimdInit(const OMPLoopDirective &D);
2232 void EmitOMPSimdFinal(const OMPLoopDirective &D);
2233 /// \brief Emit code for the worksharing loop-based directive.
2234 /// \return true, if this construct has any lastprivate clause, false -
2236 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
2237 void EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
2238 const OMPLoopDirective &S,
2239 OMPPrivateScope &LoopScope, bool Ordered,
2240 llvm::Value *LB, llvm::Value *UB, llvm::Value *ST,
2241 llvm::Value *IL, llvm::Value *Chunk);
2242 /// \brief Emit code for sections directive.
2243 OpenMPDirectiveKind EmitSections(const OMPExecutableDirective &S);
2247 //===--------------------------------------------------------------------===//
2248 // LValue Expression Emission
2249 //===--------------------------------------------------------------------===//
2251 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
2252 RValue GetUndefRValue(QualType Ty);
2254 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
2255 /// and issue an ErrorUnsupported style diagnostic (using the
2257 RValue EmitUnsupportedRValue(const Expr *E,
2260 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
2261 /// an ErrorUnsupported style diagnostic (using the provided Name).
2262 LValue EmitUnsupportedLValue(const Expr *E,
2265 /// EmitLValue - Emit code to compute a designator that specifies the location
2266 /// of the expression.
2268 /// This can return one of two things: a simple address or a bitfield
2269 /// reference. In either case, the LLVM Value* in the LValue structure is
2270 /// guaranteed to be an LLVM pointer type.
2272 /// If this returns a bitfield reference, nothing about the pointee type of
2273 /// the LLVM value is known: For example, it may not be a pointer to an
2276 /// If this returns a normal address, and if the lvalue's C type is fixed
2277 /// size, this method guarantees that the returned pointer type will point to
2278 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
2279 /// variable length type, this is not possible.
2281 LValue EmitLValue(const Expr *E);
2283 /// \brief Same as EmitLValue but additionally we generate checking code to
2284 /// guard against undefined behavior. This is only suitable when we know
2285 /// that the address will be used to access the object.
2286 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
2288 RValue convertTempToRValue(llvm::Value *addr, QualType type,
2289 SourceLocation Loc);
2291 void EmitAtomicInit(Expr *E, LValue lvalue);
2293 bool LValueIsSuitableForInlineAtomic(LValue Src);
2294 bool typeIsSuitableForInlineAtomic(QualType Ty, bool IsVolatile) const;
2296 RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
2297 AggValueSlot Slot = AggValueSlot::ignored());
2299 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
2300 llvm::AtomicOrdering AO, bool IsVolatile = false,
2301 AggValueSlot slot = AggValueSlot::ignored());
2303 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
2305 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
2306 bool IsVolatile, bool isInit);
2308 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
2309 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2310 llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
2311 llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
2312 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
2314 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
2315 const llvm::function_ref<RValue(RValue)> &UpdateOp,
2318 /// EmitToMemory - Change a scalar value from its value
2319 /// representation to its in-memory representation.
2320 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
2322 /// EmitFromMemory - Change a scalar value from its memory
2323 /// representation to its value representation.
2324 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
2326 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2327 /// care to appropriately convert from the memory representation to
2328 /// the LLVM value representation.
2329 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
2330 unsigned Alignment, QualType Ty,
2332 llvm::MDNode *TBAAInfo = nullptr,
2333 QualType TBAABaseTy = QualType(),
2334 uint64_t TBAAOffset = 0);
2336 /// EmitLoadOfScalar - Load a scalar value from an address, taking
2337 /// care to appropriately convert from the memory representation to
2338 /// the LLVM value representation. The l-value must be a simple
2340 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
2342 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2343 /// care to appropriately convert from the memory representation to
2344 /// the LLVM value representation.
2345 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
2346 bool Volatile, unsigned Alignment, QualType Ty,
2347 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
2348 QualType TBAABaseTy = QualType(),
2349 uint64_t TBAAOffset = 0);
2351 /// EmitStoreOfScalar - Store a scalar value to an address, taking
2352 /// care to appropriately convert from the memory representation to
2353 /// the LLVM value representation. The l-value must be a simple
2354 /// l-value. The isInit flag indicates whether this is an initialization.
2355 /// If so, atomic qualifiers are ignored and the store is always non-atomic.
2356 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
2358 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
2359 /// this method emits the address of the lvalue, then loads the result as an
2360 /// rvalue, returning the rvalue.
2361 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
2362 RValue EmitLoadOfExtVectorElementLValue(LValue V);
2363 RValue EmitLoadOfBitfieldLValue(LValue LV);
2364 RValue EmitLoadOfGlobalRegLValue(LValue LV);
2366 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2367 /// lvalue, where both are guaranteed to the have the same type, and that type
2369 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
2370 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
2371 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
2373 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
2374 /// as EmitStoreThroughLValue.
2376 /// \param Result [out] - If non-null, this will be set to a Value* for the
2377 /// bit-field contents after the store, appropriate for use as the result of
2378 /// an assignment to the bit-field.
2379 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2380 llvm::Value **Result=nullptr);
2382 /// Emit an l-value for an assignment (simple or compound) of complex type.
2383 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
2384 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
2385 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
2386 llvm::Value *&Result);
2388 // Note: only available for agg return types
2389 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
2390 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
2391 // Note: only available for agg return types
2392 LValue EmitCallExprLValue(const CallExpr *E);
2393 // Note: only available for agg return types
2394 LValue EmitVAArgExprLValue(const VAArgExpr *E);
2395 LValue EmitDeclRefLValue(const DeclRefExpr *E);
2396 LValue EmitReadRegister(const VarDecl *VD);
2397 LValue EmitStringLiteralLValue(const StringLiteral *E);
2398 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
2399 LValue EmitPredefinedLValue(const PredefinedExpr *E);
2400 LValue EmitUnaryOpLValue(const UnaryOperator *E);
2401 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2402 bool Accessed = false);
2403 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
2404 LValue EmitMemberExpr(const MemberExpr *E);
2405 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
2406 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
2407 LValue EmitInitListLValue(const InitListExpr *E);
2408 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
2409 LValue EmitCastLValue(const CastExpr *E);
2410 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2411 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
2413 llvm::Value *EmitExtVectorElementLValue(LValue V);
2415 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
2417 class ConstantEmission {
2418 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
2419 ConstantEmission(llvm::Constant *C, bool isReference)
2420 : ValueAndIsReference(C, isReference) {}
2422 ConstantEmission() {}
2423 static ConstantEmission forReference(llvm::Constant *C) {
2424 return ConstantEmission(C, true);
2426 static ConstantEmission forValue(llvm::Constant *C) {
2427 return ConstantEmission(C, false);
2430 explicit operator bool() const {
2431 return ValueAndIsReference.getOpaqueValue() != nullptr;
2434 bool isReference() const { return ValueAndIsReference.getInt(); }
2435 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
2436 assert(isReference());
2437 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
2438 refExpr->getType());
2441 llvm::Constant *getValue() const {
2442 assert(!isReference());
2443 return ValueAndIsReference.getPointer();
2447 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
2449 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
2450 AggValueSlot slot = AggValueSlot::ignored());
2451 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
2453 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
2454 const ObjCIvarDecl *Ivar);
2455 LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
2456 LValue EmitLValueForLambdaField(const FieldDecl *Field);
2458 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
2459 /// if the Field is a reference, this will return the address of the reference
2460 /// and not the address of the value stored in the reference.
2461 LValue EmitLValueForFieldInitialization(LValue Base,
2462 const FieldDecl* Field);
2464 LValue EmitLValueForIvar(QualType ObjectTy,
2465 llvm::Value* Base, const ObjCIvarDecl *Ivar,
2466 unsigned CVRQualifiers);
2468 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
2469 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
2470 LValue EmitLambdaLValue(const LambdaExpr *E);
2471 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
2472 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
2474 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
2475 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
2476 LValue EmitStmtExprLValue(const StmtExpr *E);
2477 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
2478 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
2479 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
2481 //===--------------------------------------------------------------------===//
2482 // Scalar Expression Emission
2483 //===--------------------------------------------------------------------===//
2485 /// EmitCall - Generate a call of the given function, expecting the given
2486 /// result type, and using the given argument list which specifies both the
2487 /// LLVM arguments and the types they were derived from.
2489 /// \param TargetDecl - If given, the decl of the function in a direct call;
2490 /// used to set attributes on the call (noreturn, etc.).
2491 RValue EmitCall(const CGFunctionInfo &FnInfo,
2492 llvm::Value *Callee,
2493 ReturnValueSlot ReturnValue,
2494 const CallArgList &Args,
2495 const Decl *TargetDecl = nullptr,
2496 llvm::Instruction **callOrInvoke = nullptr);
2498 RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
2499 ReturnValueSlot ReturnValue,
2500 const Decl *TargetDecl = nullptr,
2501 llvm::Value *Chain = nullptr);
2502 RValue EmitCallExpr(const CallExpr *E,
2503 ReturnValueSlot ReturnValue = ReturnValueSlot());
2505 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2506 const Twine &name = "");
2507 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
2508 ArrayRef<llvm::Value*> args,
2509 const Twine &name = "");
2510 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2511 const Twine &name = "");
2512 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
2513 ArrayRef<llvm::Value*> args,
2514 const Twine &name = "");
2516 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2517 ArrayRef<llvm::Value *> Args,
2518 const Twine &Name = "");
2519 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
2520 const Twine &Name = "");
2521 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2522 ArrayRef<llvm::Value*> args,
2523 const Twine &name = "");
2524 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
2525 const Twine &name = "");
2526 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
2527 ArrayRef<llvm::Value*> args);
2529 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
2530 NestedNameSpecifier *Qual,
2533 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
2535 const CXXRecordDecl *RD);
2538 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
2539 ReturnValueSlot ReturnValue, llvm::Value *This,
2540 llvm::Value *ImplicitParam,
2541 QualType ImplicitParamTy, const CallExpr *E);
2542 RValue EmitCXXStructorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
2543 ReturnValueSlot ReturnValue, llvm::Value *This,
2544 llvm::Value *ImplicitParam,
2545 QualType ImplicitParamTy, const CallExpr *E,
2547 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
2548 ReturnValueSlot ReturnValue);
2549 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
2550 const CXXMethodDecl *MD,
2551 ReturnValueSlot ReturnValue,
2553 NestedNameSpecifier *Qualifier,
2554 bool IsArrow, const Expr *Base);
2555 // Compute the object pointer.
2556 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
2557 ReturnValueSlot ReturnValue);
2559 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
2560 const CXXMethodDecl *MD,
2561 ReturnValueSlot ReturnValue);
2563 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
2564 ReturnValueSlot ReturnValue);
2567 RValue EmitBuiltinExpr(const FunctionDecl *FD,
2568 unsigned BuiltinID, const CallExpr *E,
2569 ReturnValueSlot ReturnValue);
2571 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
2573 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
2574 /// is unhandled by the current target.
2575 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2577 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
2578 const llvm::CmpInst::Predicate Fp,
2579 const llvm::CmpInst::Predicate Ip,
2580 const llvm::Twine &Name = "");
2581 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2583 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
2584 unsigned LLVMIntrinsic,
2585 unsigned AltLLVMIntrinsic,
2586 const char *NameHint,
2589 SmallVectorImpl<llvm::Value *> &Ops,
2590 llvm::Value *Align = nullptr);
2591 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
2592 unsigned Modifier, llvm::Type *ArgTy,
2594 llvm::Value *EmitNeonCall(llvm::Function *F,
2595 SmallVectorImpl<llvm::Value*> &O,
2597 unsigned shift = 0, bool rightshift = false);
2598 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
2599 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
2600 bool negateForRightShift);
2601 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
2602 llvm::Type *Ty, bool usgn, const char *name);
2603 // Helper functions for EmitAArch64BuiltinExpr.
2604 llvm::Value *vectorWrapScalar8(llvm::Value *Op);
2605 llvm::Value *vectorWrapScalar16(llvm::Value *Op);
2606 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2608 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
2609 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2610 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2611 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2612 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2613 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
2615 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
2616 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
2617 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
2618 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
2619 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
2620 llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
2621 const ObjCMethodDecl *MethodWithObjects);
2622 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
2623 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
2624 ReturnValueSlot Return = ReturnValueSlot());
2626 /// Retrieves the default cleanup kind for an ARC cleanup.
2627 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
2628 CleanupKind getARCCleanupKind() {
2629 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
2630 ? NormalAndEHCleanup : NormalCleanup;
2634 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
2635 void EmitARCDestroyWeak(llvm::Value *addr);
2636 llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
2637 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
2638 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
2640 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
2641 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
2642 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
2643 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
2644 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
2645 bool resultIgnored);
2646 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
2647 bool resultIgnored);
2648 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
2649 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
2650 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
2651 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise);
2652 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
2653 llvm::Value *EmitARCAutorelease(llvm::Value *value);
2654 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
2655 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
2656 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
2658 std::pair<LValue,llvm::Value*>
2659 EmitARCStoreAutoreleasing(const BinaryOperator *e);
2660 std::pair<LValue,llvm::Value*>
2661 EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
2663 llvm::Value *EmitObjCThrowOperand(const Expr *expr);
2665 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
2666 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
2667 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
2669 llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
2670 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
2671 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
2673 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
2675 static Destroyer destroyARCStrongImprecise;
2676 static Destroyer destroyARCStrongPrecise;
2677 static Destroyer destroyARCWeak;
2679 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
2680 llvm::Value *EmitObjCAutoreleasePoolPush();
2681 llvm::Value *EmitObjCMRRAutoreleasePoolPush();
2682 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
2683 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
2685 /// \brief Emits a reference binding to the passed in expression.
2686 RValue EmitReferenceBindingToExpr(const Expr *E);
2688 //===--------------------------------------------------------------------===//
2689 // Expression Emission
2690 //===--------------------------------------------------------------------===//
2692 // Expressions are broken into three classes: scalar, complex, aggregate.
2694 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
2695 /// scalar type, returning the result.
2696 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
2698 /// EmitScalarConversion - Emit a conversion from the specified type to the
2699 /// specified destination type, both of which are LLVM scalar types.
2700 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
2703 /// EmitComplexToScalarConversion - Emit a conversion from the specified
2704 /// complex type to the specified destination type, where the destination type
2705 /// is an LLVM scalar type.
2706 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
2710 /// EmitAggExpr - Emit the computation of the specified expression
2711 /// of aggregate type. The result is computed into the given slot,
2712 /// which may be null to indicate that the value is not needed.
2713 void EmitAggExpr(const Expr *E, AggValueSlot AS);
2715 /// EmitAggExprToLValue - Emit the computation of the specified expression of
2716 /// aggregate type into a temporary LValue.
2717 LValue EmitAggExprToLValue(const Expr *E);
2719 /// EmitGCMemmoveCollectable - Emit special API for structs with object
2721 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
2724 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2725 /// make sure it survives garbage collection until this point.
2726 void EmitExtendGCLifetime(llvm::Value *object);
2728 /// EmitComplexExpr - Emit the computation of the specified expression of
2729 /// complex type, returning the result.
2730 ComplexPairTy EmitComplexExpr(const Expr *E,
2731 bool IgnoreReal = false,
2732 bool IgnoreImag = false);
2734 /// EmitComplexExprIntoLValue - Emit the given expression of complex
2735 /// type and place its result into the specified l-value.
2736 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
2738 /// EmitStoreOfComplex - Store a complex number into the specified l-value.
2739 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
2741 /// EmitLoadOfComplex - Load a complex number from the specified l-value.
2742 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
2744 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
2745 /// global variable that has already been created for it. If the initializer
2746 /// has a different type than GV does, this may free GV and return a different
2747 /// one. Otherwise it just returns GV.
2748 llvm::GlobalVariable *
2749 AddInitializerToStaticVarDecl(const VarDecl &D,
2750 llvm::GlobalVariable *GV);
2753 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
2754 /// variable with global storage.
2755 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
2758 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
2759 llvm::Constant *Addr);
2761 /// Call atexit() with a function that passes the given argument to
2762 /// the given function.
2763 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
2764 llvm::Constant *addr);
2766 /// Emit code in this function to perform a guarded variable
2767 /// initialization. Guarded initializations are used when it's not
2768 /// possible to prove that an initialization will be done exactly
2769 /// once, e.g. with a static local variable or a static data member
2770 /// of a class template.
2771 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
2774 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
2776 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
2777 ArrayRef<llvm::Function *> CXXThreadLocals,
2778 llvm::GlobalVariable *Guard = nullptr);
2780 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
2782 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
2783 const std::vector<std::pair<llvm::WeakVH,
2784 llvm::Constant*> > &DtorsAndObjects);
2786 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
2788 llvm::GlobalVariable *Addr,
2791 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
2793 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
2796 void enterFullExpression(const ExprWithCleanups *E) {
2797 if (E->getNumObjects() == 0) return;
2798 enterNonTrivialFullExpression(E);
2800 void enterNonTrivialFullExpression(const ExprWithCleanups *E);
2802 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
2804 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
2806 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr);
2808 //===--------------------------------------------------------------------===//
2809 // Annotations Emission
2810 //===--------------------------------------------------------------------===//
2812 /// Emit an annotation call (intrinsic or builtin).
2813 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
2814 llvm::Value *AnnotatedVal,
2815 StringRef AnnotationStr,
2816 SourceLocation Location);
2818 /// Emit local annotations for the local variable V, declared by D.
2819 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
2821 /// Emit field annotations for the given field & value. Returns the
2822 /// annotation result.
2823 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
2825 //===--------------------------------------------------------------------===//
2827 //===--------------------------------------------------------------------===//
2829 /// ContainsLabel - Return true if the statement contains a label in it. If
2830 /// this statement is not executed normally, it not containing a label means
2831 /// that we can just remove the code.
2832 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
2834 /// containsBreak - Return true if the statement contains a break out of it.
2835 /// If the statement (recursively) contains a switch or loop with a break
2836 /// inside of it, this is fine.
2837 static bool containsBreak(const Stmt *S);
2839 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2840 /// to a constant, or if it does but contains a label, return false. If it
2841 /// constant folds return true and set the boolean result in Result.
2842 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
2844 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
2845 /// to a constant, or if it does but contains a label, return false. If it
2846 /// constant folds return true and set the folded value.
2847 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
2849 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
2850 /// if statement) to the specified blocks. Based on the condition, this might
2851 /// try to simplify the codegen of the conditional based on the branch.
2852 /// TrueCount should be the number of times we expect the condition to
2853 /// evaluate to true based on PGO data.
2854 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
2855 llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
2857 /// \brief Emit a description of a type in a format suitable for passing to
2858 /// a runtime sanitizer handler.
2859 llvm::Constant *EmitCheckTypeDescriptor(QualType T);
2861 /// \brief Convert a value into a format suitable for passing to a runtime
2862 /// sanitizer handler.
2863 llvm::Value *EmitCheckValue(llvm::Value *V);
2865 /// \brief Emit a description of a source location in a format suitable for
2866 /// passing to a runtime sanitizer handler.
2867 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
2869 /// \brief Create a basic block that will call a handler function in a
2870 /// sanitizer runtime with the provided arguments, and create a conditional
2872 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2873 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2874 ArrayRef<llvm::Value *> DynamicArgs);
2876 /// \brief Create a basic block that will call the trap intrinsic, and emit a
2877 /// conditional branch to it, for the -ftrapv checks.
2878 void EmitTrapCheck(llvm::Value *Checked);
2880 /// \brief Emit a call to trap or debugtrap and attach function attribute
2881 /// "trap-func-name" if specified.
2882 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
2884 /// \brief Create a check for a function parameter that may potentially be
2885 /// declared as non-null.
2886 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
2887 const FunctionDecl *FD, unsigned ParmNum);
2889 /// EmitCallArg - Emit a single call argument.
2890 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
2892 /// EmitDelegateCallArg - We are performing a delegate call; that
2893 /// is, the current function is delegating to another one. Produce
2894 /// a r-value suitable for passing the given parameter.
2895 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
2896 SourceLocation loc);
2898 /// SetFPAccuracy - Set the minimum required accuracy of the given floating
2899 /// point operation, expressed as the maximum relative error in ulp.
2900 void SetFPAccuracy(llvm::Value *Val, float Accuracy);
2903 llvm::MDNode *getRangeForLoadFromType(QualType Ty);
2904 void EmitReturnOfRValue(RValue RV, QualType Ty);
2906 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
2908 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
2909 DeferredReplacements;
2911 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
2912 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
2914 /// \param AI - The first function argument of the expansion.
2915 void ExpandTypeFromArgs(QualType Ty, LValue Dst,
2916 SmallVectorImpl<llvm::Argument *>::iterator &AI);
2918 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
2919 /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
2920 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
2921 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
2922 SmallVectorImpl<llvm::Value *> &IRCallArgs,
2923 unsigned &IRCallArgPos);
2925 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
2926 const Expr *InputExpr, std::string &ConstraintStr);
2928 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
2929 LValue InputValue, QualType InputType,
2930 std::string &ConstraintStr,
2931 SourceLocation Loc);
2934 /// EmitCallArgs - Emit call arguments for a function.
2935 template <typename T>
2936 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
2937 CallExpr::const_arg_iterator ArgBeg,
2938 CallExpr::const_arg_iterator ArgEnd,
2939 const FunctionDecl *CalleeDecl = nullptr,
2940 unsigned ParamsToSkip = 0) {
2941 SmallVector<QualType, 16> ArgTypes;
2942 CallExpr::const_arg_iterator Arg = ArgBeg;
2944 assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
2945 "Can't skip parameters if type info is not provided");
2946 if (CallArgTypeInfo) {
2947 // First, use the argument types that the type info knows about
2948 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
2949 E = CallArgTypeInfo->param_type_end();
2950 I != E; ++I, ++Arg) {
2951 assert(Arg != ArgEnd && "Running over edge of argument list!");
2953 ((*I)->isVariablyModifiedType() ||
2955 .getCanonicalType((*I).getNonReferenceType())
2957 getContext().getCanonicalType(Arg->getType()).getTypePtr()) &&
2958 "type mismatch in call argument!");
2959 ArgTypes.push_back(*I);
2963 // Either we've emitted all the call args, or we have a call to variadic
2966 (Arg == ArgEnd || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) &&
2967 "Extra arguments in non-variadic function!");
2969 // If we still have any arguments, emit them using the type of the argument.
2970 for (; Arg != ArgEnd; ++Arg)
2971 ArgTypes.push_back(getVarArgType(*Arg));
2973 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip);
2976 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
2977 CallExpr::const_arg_iterator ArgBeg,
2978 CallExpr::const_arg_iterator ArgEnd,
2979 const FunctionDecl *CalleeDecl = nullptr,
2980 unsigned ParamsToSkip = 0);
2983 QualType getVarArgType(const Expr *Arg);
2985 const TargetCodeGenInfo &getTargetHooks() const {
2986 return CGM.getTargetCodeGenInfo();
2989 void EmitDeclMetadata();
2991 CodeGenModule::ByrefHelpers *
2992 buildByrefHelpers(llvm::StructType &byrefType,
2993 const AutoVarEmission &emission);
2995 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
2997 /// GetPointeeAlignment - Given an expression with a pointer type, emit the
2998 /// value and compute our best estimate of the alignment of the pointee.
2999 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
3001 llvm::Value *GetValueForARMHint(unsigned BuiltinID);
3004 /// Helper class with most of the code for saving a value for a
3005 /// conditional expression cleanup.
3006 struct DominatingLLVMValue {
3007 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
3009 /// Answer whether the given value needs extra work to be saved.
3010 static bool needsSaving(llvm::Value *value) {
3011 // If it's not an instruction, we don't need to save.
3012 if (!isa<llvm::Instruction>(value)) return false;
3014 // If it's an instruction in the entry block, we don't need to save.
3015 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
3016 return (block != &block->getParent()->getEntryBlock());
3019 /// Try to save the given value.
3020 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
3021 if (!needsSaving(value)) return saved_type(value, false);
3023 // Otherwise we need an alloca.
3024 llvm::Value *alloca =
3025 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
3026 CGF.Builder.CreateStore(value, alloca);
3028 return saved_type(alloca, true);
3031 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
3032 if (!value.getInt()) return value.getPointer();
3033 return CGF.Builder.CreateLoad(value.getPointer());
3037 /// A partial specialization of DominatingValue for llvm::Values that
3038 /// might be llvm::Instructions.
3039 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
3041 static type restore(CodeGenFunction &CGF, saved_type value) {
3042 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
3046 /// A specialization of DominatingValue for RValue.
3047 template <> struct DominatingValue<RValue> {
3048 typedef RValue type;
3050 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
3051 AggregateAddress, ComplexAddress };
3055 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
3058 static bool needsSaving(RValue value);
3059 static saved_type save(CodeGenFunction &CGF, RValue value);
3060 RValue restore(CodeGenFunction &CGF);
3062 // implementations in CGExprCXX.cpp
3065 static bool needsSaving(type value) {
3066 return saved_type::needsSaving(value);
3068 static saved_type save(CodeGenFunction &CGF, type value) {
3069 return saved_type::save(CGF, value);
3071 static type restore(CodeGenFunction &CGF, saved_type value) {
3072 return value.restore(CGF);
3076 } // end namespace CodeGen
3077 } // end namespace clang