When throwing an elidable object, first try to treat the subexpression
[clang.git] / lib / CodeGen / CodeGenFunction.h
blob7686b333659c67619869ee8aa0f8fbc6fdb69d01
1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the internal per-function state used for llvm translation.
12 //===----------------------------------------------------------------------===//
14 #ifndef CLANG_CODEGEN_CODEGENFUNCTION_H
15 #define CLANG_CODEGEN_CODEGENFUNCTION_H
17 #include "clang/AST/Type.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/Basic/ABI.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/ValueHandle.h"
26 #include "CodeGenModule.h"
27 #include "CGBlocks.h"
28 #include "CGBuilder.h"
29 #include "CGCall.h"
30 #include "CGValue.h"
32 namespace llvm {
33 class BasicBlock;
34 class LLVMContext;
35 class MDNode;
36 class Module;
37 class SwitchInst;
38 class Twine;
39 class Value;
40 class CallSite;
43 namespace clang {
44 class APValue;
45 class ASTContext;
46 class CXXDestructorDecl;
47 class CXXTryStmt;
48 class Decl;
49 class EnumConstantDecl;
50 class FunctionDecl;
51 class FunctionProtoType;
52 class LabelStmt;
53 class ObjCContainerDecl;
54 class ObjCInterfaceDecl;
55 class ObjCIvarDecl;
56 class ObjCMethodDecl;
57 class ObjCImplementationDecl;
58 class ObjCPropertyImplDecl;
59 class TargetInfo;
60 class TargetCodeGenInfo;
61 class VarDecl;
62 class ObjCForCollectionStmt;
63 class ObjCAtTryStmt;
64 class ObjCAtThrowStmt;
65 class ObjCAtSynchronizedStmt;
67 namespace CodeGen {
68 class CodeGenTypes;
69 class CGDebugInfo;
70 class CGFunctionInfo;
71 class CGRecordLayout;
72 class CGBlockInfo;
73 class CGCXXABI;
75 /// A branch fixup. These are required when emitting a goto to a
76 /// label which hasn't been emitted yet. The goto is optimistically
77 /// emitted as a branch to the basic block for the label, and (if it
78 /// occurs in a scope with non-trivial cleanups) a fixup is added to
79 /// the innermost cleanup. When a (normal) cleanup is popped, any
80 /// unresolved fixups in that scope are threaded through the cleanup.
81 struct BranchFixup {
82 /// The block containing the terminator which needs to be modified
83 /// into a switch if this fixup is resolved into the current scope.
84 /// If null, LatestBranch points directly to the destination.
85 llvm::BasicBlock *OptimisticBranchBlock;
87 /// The ultimate destination of the branch.
88 ///
89 /// This can be set to null to indicate that this fixup was
90 /// successfully resolved.
91 llvm::BasicBlock *Destination;
93 /// The destination index value.
94 unsigned DestinationIndex;
96 /// The initial branch of the fixup.
97 llvm::BranchInst *InitialBranch;
100 enum CleanupKind {
101 EHCleanup = 0x1,
102 NormalCleanup = 0x2,
103 NormalAndEHCleanup = EHCleanup | NormalCleanup,
105 InactiveCleanup = 0x4,
106 InactiveEHCleanup = EHCleanup | InactiveCleanup,
107 InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
108 InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
111 /// A stack of scopes which respond to exceptions, including cleanups
112 /// and catch blocks.
113 class EHScopeStack {
114 public:
115 /// A saved depth on the scope stack. This is necessary because
116 /// pushing scopes onto the stack invalidates iterators.
117 class stable_iterator {
118 friend class EHScopeStack;
120 /// Offset from StartOfData to EndOfBuffer.
121 ptrdiff_t Size;
123 stable_iterator(ptrdiff_t Size) : Size(Size) {}
125 public:
126 static stable_iterator invalid() { return stable_iterator(-1); }
127 stable_iterator() : Size(-1) {}
129 bool isValid() const { return Size >= 0; }
131 /// Returns true if this scope encloses I.
132 /// Returns false if I is invalid.
133 /// This scope must be valid.
134 bool encloses(stable_iterator I) const { return Size <= I.Size; }
136 /// Returns true if this scope strictly encloses I: that is,
137 /// if it encloses I and is not I.
138 /// Returns false is I is invalid.
139 /// This scope must be valid.
140 bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
142 friend bool operator==(stable_iterator A, stable_iterator B) {
143 return A.Size == B.Size;
145 friend bool operator!=(stable_iterator A, stable_iterator B) {
146 return A.Size != B.Size;
150 /// Information for lazily generating a cleanup. Subclasses must be
151 /// POD-like: cleanups will not be destructed, and they will be
152 /// allocated on the cleanup stack and freely copied and moved
153 /// around.
155 /// Cleanup implementations should generally be declared in an
156 /// anonymous namespace.
157 class Cleanup {
158 public:
159 // Anchor the construction vtable. We use the destructor because
160 // gcc gives an obnoxious warning if there are virtual methods
161 // with an accessible non-virtual destructor. Unfortunately,
162 // declaring this destructor makes it non-trivial, but there
163 // doesn't seem to be any other way around this warning.
165 // This destructor will never be called.
166 virtual ~Cleanup();
168 /// Emit the cleanup. For normal cleanups, this is run in the
169 /// same EH context as when the cleanup was pushed, i.e. the
170 /// immediately-enclosing context of the cleanup scope. For
171 /// EH cleanups, this is run in a terminate context.
173 // \param IsForEHCleanup true if this is for an EH cleanup, false
174 /// if for a normal cleanup.
175 virtual void Emit(CodeGenFunction &CGF, bool IsForEHCleanup) = 0;
178 private:
179 // The implementation for this class is in CGException.h and
180 // CGException.cpp; the definition is here because it's used as a
181 // member of CodeGenFunction.
183 /// The start of the scope-stack buffer, i.e. the allocated pointer
184 /// for the buffer. All of these pointers are either simultaneously
185 /// null or simultaneously valid.
186 char *StartOfBuffer;
188 /// The end of the buffer.
189 char *EndOfBuffer;
191 /// The first valid entry in the buffer.
192 char *StartOfData;
194 /// The innermost normal cleanup on the stack.
195 stable_iterator InnermostNormalCleanup;
197 /// The innermost EH cleanup on the stack.
198 stable_iterator InnermostEHCleanup;
200 /// The number of catches on the stack.
201 unsigned CatchDepth;
203 /// The current EH destination index. Reset to FirstCatchIndex
204 /// whenever the last EH cleanup is popped.
205 unsigned NextEHDestIndex;
206 enum { FirstEHDestIndex = 1 };
208 /// The current set of branch fixups. A branch fixup is a jump to
209 /// an as-yet unemitted label, i.e. a label for which we don't yet
210 /// know the EH stack depth. Whenever we pop a cleanup, we have
211 /// to thread all the current branch fixups through it.
213 /// Fixups are recorded as the Use of the respective branch or
214 /// switch statement. The use points to the final destination.
215 /// When popping out of a cleanup, these uses are threaded through
216 /// the cleanup and adjusted to point to the new cleanup.
218 /// Note that branches are allowed to jump into protected scopes
219 /// in certain situations; e.g. the following code is legal:
220 /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
221 /// goto foo;
222 /// A a;
223 /// foo:
224 /// bar();
225 llvm::SmallVector<BranchFixup, 8> BranchFixups;
227 char *allocate(size_t Size);
229 void *pushCleanup(CleanupKind K, size_t DataSize);
231 public:
232 EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
233 InnermostNormalCleanup(stable_end()),
234 InnermostEHCleanup(stable_end()),
235 CatchDepth(0), NextEHDestIndex(FirstEHDestIndex) {}
236 ~EHScopeStack() { delete[] StartOfBuffer; }
238 // Variadic templates would make this not terrible.
240 /// Push a lazily-created cleanup on the stack.
241 template <class T>
242 void pushCleanup(CleanupKind Kind) {
243 void *Buffer = pushCleanup(Kind, sizeof(T));
244 Cleanup *Obj = new(Buffer) T();
245 (void) Obj;
248 /// Push a lazily-created cleanup on the stack.
249 template <class T, class A0>
250 void pushCleanup(CleanupKind Kind, A0 a0) {
251 void *Buffer = pushCleanup(Kind, sizeof(T));
252 Cleanup *Obj = new(Buffer) T(a0);
253 (void) Obj;
256 /// Push a lazily-created cleanup on the stack.
257 template <class T, class A0, class A1>
258 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
259 void *Buffer = pushCleanup(Kind, sizeof(T));
260 Cleanup *Obj = new(Buffer) T(a0, a1);
261 (void) Obj;
264 /// Push a lazily-created cleanup on the stack.
265 template <class T, class A0, class A1, class A2>
266 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
267 void *Buffer = pushCleanup(Kind, sizeof(T));
268 Cleanup *Obj = new(Buffer) T(a0, a1, a2);
269 (void) Obj;
272 /// Push a lazily-created cleanup on the stack.
273 template <class T, class A0, class A1, class A2, class A3>
274 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
275 void *Buffer = pushCleanup(Kind, sizeof(T));
276 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
277 (void) Obj;
280 /// Push a lazily-created cleanup on the stack.
281 template <class T, class A0, class A1, class A2, class A3, class A4>
282 void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
283 void *Buffer = pushCleanup(Kind, sizeof(T));
284 Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
285 (void) Obj;
288 // Feel free to add more variants of the following:
290 /// Push a cleanup with non-constant storage requirements on the
291 /// stack. The cleanup type must provide an additional static method:
292 /// static size_t getExtraSize(size_t);
293 /// The argument to this method will be the value N, which will also
294 /// be passed as the first argument to the constructor.
296 /// The data stored in the extra storage must obey the same
297 /// restrictions as normal cleanup member data.
299 /// The pointer returned from this method is valid until the cleanup
300 /// stack is modified.
301 template <class T, class A0, class A1, class A2>
302 T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
303 void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
304 return new (Buffer) T(N, a0, a1, a2);
307 /// Pops a cleanup scope off the stack. This should only be called
308 /// by CodeGenFunction::PopCleanupBlock.
309 void popCleanup();
311 /// Push a set of catch handlers on the stack. The catch is
312 /// uninitialized and will need to have the given number of handlers
313 /// set on it.
314 class EHCatchScope *pushCatch(unsigned NumHandlers);
316 /// Pops a catch scope off the stack.
317 void popCatch();
319 /// Push an exceptions filter on the stack.
320 class EHFilterScope *pushFilter(unsigned NumFilters);
322 /// Pops an exceptions filter off the stack.
323 void popFilter();
325 /// Push a terminate handler on the stack.
326 void pushTerminate();
328 /// Pops a terminate handler off the stack.
329 void popTerminate();
331 /// Determines whether the exception-scopes stack is empty.
332 bool empty() const { return StartOfData == EndOfBuffer; }
334 bool requiresLandingPad() const {
335 return (CatchDepth || hasEHCleanups());
338 /// Determines whether there are any normal cleanups on the stack.
339 bool hasNormalCleanups() const {
340 return InnermostNormalCleanup != stable_end();
343 /// Returns the innermost normal cleanup on the stack, or
344 /// stable_end() if there are no normal cleanups.
345 stable_iterator getInnermostNormalCleanup() const {
346 return InnermostNormalCleanup;
348 stable_iterator getInnermostActiveNormalCleanup() const; // CGException.h
350 /// Determines whether there are any EH cleanups on the stack.
351 bool hasEHCleanups() const {
352 return InnermostEHCleanup != stable_end();
355 /// Returns the innermost EH cleanup on the stack, or stable_end()
356 /// if there are no EH cleanups.
357 stable_iterator getInnermostEHCleanup() const {
358 return InnermostEHCleanup;
360 stable_iterator getInnermostActiveEHCleanup() const; // CGException.h
362 /// An unstable reference to a scope-stack depth. Invalidated by
363 /// pushes but not pops.
364 class iterator;
366 /// Returns an iterator pointing to the innermost EH scope.
367 iterator begin() const;
369 /// Returns an iterator pointing to the outermost EH scope.
370 iterator end() const;
372 /// Create a stable reference to the top of the EH stack. The
373 /// returned reference is valid until that scope is popped off the
374 /// stack.
375 stable_iterator stable_begin() const {
376 return stable_iterator(EndOfBuffer - StartOfData);
379 /// Create a stable reference to the bottom of the EH stack.
380 static stable_iterator stable_end() {
381 return stable_iterator(0);
384 /// Translates an iterator into a stable_iterator.
385 stable_iterator stabilize(iterator it) const;
387 /// Finds the nearest cleanup enclosing the given iterator.
388 /// Returns stable_iterator::invalid() if there are no such cleanups.
389 stable_iterator getEnclosingEHCleanup(iterator it) const;
391 /// Turn a stable reference to a scope depth into a unstable pointer
392 /// to the EH stack.
393 iterator find(stable_iterator save) const;
395 /// Removes the cleanup pointed to by the given stable_iterator.
396 void removeCleanup(stable_iterator save);
398 /// Add a branch fixup to the current cleanup scope.
399 BranchFixup &addBranchFixup() {
400 assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
401 BranchFixups.push_back(BranchFixup());
402 return BranchFixups.back();
405 unsigned getNumBranchFixups() const { return BranchFixups.size(); }
406 BranchFixup &getBranchFixup(unsigned I) {
407 assert(I < getNumBranchFixups());
408 return BranchFixups[I];
411 /// Pops lazily-removed fixups from the end of the list. This
412 /// should only be called by procedures which have just popped a
413 /// cleanup or resolved one or more fixups.
414 void popNullFixups();
416 /// Clears the branch-fixups list. This should only be called by
417 /// ResolveAllBranchFixups.
418 void clearFixups() { BranchFixups.clear(); }
420 /// Gets the next EH destination index.
421 unsigned getNextEHDestIndex() { return NextEHDestIndex++; }
424 /// CodeGenFunction - This class organizes the per-function state that is used
425 /// while generating LLVM code.
426 class CodeGenFunction : public BlockFunction {
427 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
428 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT
430 friend class CGCXXABI;
431 public:
432 /// A jump destination is an abstract label, branching to which may
433 /// require a jump out through normal cleanups.
434 struct JumpDest {
435 JumpDest() : Block(0), ScopeDepth(), Index(0) {}
436 JumpDest(llvm::BasicBlock *Block,
437 EHScopeStack::stable_iterator Depth,
438 unsigned Index)
439 : Block(Block), ScopeDepth(Depth), Index(Index) {}
441 bool isValid() const { return Block != 0; }
442 llvm::BasicBlock *getBlock() const { return Block; }
443 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
444 unsigned getDestIndex() const { return Index; }
446 private:
447 llvm::BasicBlock *Block;
448 EHScopeStack::stable_iterator ScopeDepth;
449 unsigned Index;
452 /// An unwind destination is an abstract label, branching to which
453 /// may require a jump out through EH cleanups.
454 struct UnwindDest {
455 UnwindDest() : Block(0), ScopeDepth(), Index(0) {}
456 UnwindDest(llvm::BasicBlock *Block,
457 EHScopeStack::stable_iterator Depth,
458 unsigned Index)
459 : Block(Block), ScopeDepth(Depth), Index(Index) {}
461 bool isValid() const { return Block != 0; }
462 llvm::BasicBlock *getBlock() const { return Block; }
463 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
464 unsigned getDestIndex() const { return Index; }
466 private:
467 llvm::BasicBlock *Block;
468 EHScopeStack::stable_iterator ScopeDepth;
469 unsigned Index;
472 CodeGenModule &CGM; // Per-module state.
473 const TargetInfo &Target;
475 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
476 CGBuilderTy Builder;
478 /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
479 /// This excludes BlockDecls.
480 const Decl *CurFuncDecl;
481 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
482 const Decl *CurCodeDecl;
483 const CGFunctionInfo *CurFnInfo;
484 QualType FnRetTy;
485 llvm::Function *CurFn;
487 /// CurGD - The GlobalDecl for the current function being compiled.
488 GlobalDecl CurGD;
490 /// ReturnBlock - Unified return block.
491 JumpDest ReturnBlock;
493 /// ReturnValue - The temporary alloca to hold the return value. This is null
494 /// iff the function has no return value.
495 llvm::Value *ReturnValue;
497 /// RethrowBlock - Unified rethrow block.
498 UnwindDest RethrowBlock;
500 /// AllocaInsertPoint - This is an instruction in the entry block before which
501 /// we prefer to insert allocas.
502 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
504 // intptr_t, i32, i64
505 const llvm::IntegerType *IntPtrTy, *Int32Ty, *Int64Ty;
506 uint32_t LLVMPointerWidth;
508 bool Exceptions;
509 bool CatchUndefined;
511 /// \brief A mapping from NRVO variables to the flags used to indicate
512 /// when the NRVO has been applied to this variable.
513 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
515 /// \brief A mapping from 'Save' expression in a conditional expression
516 /// to the IR for this expression. Used to implement IR gen. for Gnu
517 /// extension's missing LHS expression in a conditional operator expression.
518 llvm::DenseMap<const Expr *, llvm::Value *> ConditionalSaveExprs;
519 llvm::DenseMap<const Expr *, ComplexPairTy> ConditionalSaveComplexExprs;
520 llvm::DenseMap<const Expr *, LValue> ConditionalSaveLValueExprs;
522 EHScopeStack EHStack;
524 /// i32s containing the indexes of the cleanup destinations.
525 llvm::AllocaInst *NormalCleanupDest;
526 llvm::AllocaInst *EHCleanupDest;
528 unsigned NextCleanupDestIndex;
530 /// The exception slot. All landing pads write the current
531 /// exception pointer into this alloca.
532 llvm::Value *ExceptionSlot;
534 /// Emits a landing pad for the current EH stack.
535 llvm::BasicBlock *EmitLandingPad();
537 llvm::BasicBlock *getInvokeDestImpl();
539 public:
540 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
541 /// rethrows.
542 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
544 // A struct holding information about a finally block's IR
545 // generation. For now, doesn't actually hold anything.
546 struct FinallyInfo {
549 FinallyInfo EnterFinallyBlock(const Stmt *Stmt,
550 llvm::Constant *BeginCatchFn,
551 llvm::Constant *EndCatchFn,
552 llvm::Constant *RethrowFn);
553 void ExitFinallyBlock(FinallyInfo &FinallyInfo);
555 /// PushDestructorCleanup - Push a cleanup to call the
556 /// complete-object destructor of an object of the given type at the
557 /// given address. Does nothing if T is not a C++ class type with a
558 /// non-trivial destructor.
559 void PushDestructorCleanup(QualType T, llvm::Value *Addr);
561 /// PushDestructorCleanup - Push a cleanup to call the
562 /// complete-object variant of the given destructor on the object at
563 /// the given address.
564 void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
565 llvm::Value *Addr);
567 /// PopCleanupBlock - Will pop the cleanup entry on the stack and
568 /// process all branch fixups.
569 void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
571 /// DeactivateCleanupBlock - Deactivates the given cleanup block.
572 /// The block cannot be reactivated. Pops it if it's the top of the
573 /// stack.
574 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
576 /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
577 /// Cannot be used to resurrect a deactivated cleanup.
578 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup);
580 /// \brief Enters a new scope for capturing cleanups, all of which
581 /// will be executed once the scope is exited.
582 class RunCleanupsScope {
583 CodeGenFunction& CGF;
584 EHScopeStack::stable_iterator CleanupStackDepth;
585 bool OldDidCallStackSave;
586 bool PerformCleanup;
588 RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
589 RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
591 public:
592 /// \brief Enter a new cleanup scope.
593 explicit RunCleanupsScope(CodeGenFunction &CGF)
594 : CGF(CGF), PerformCleanup(true)
596 CleanupStackDepth = CGF.EHStack.stable_begin();
597 OldDidCallStackSave = CGF.DidCallStackSave;
598 CGF.DidCallStackSave = false;
601 /// \brief Exit this cleanup scope, emitting any accumulated
602 /// cleanups.
603 ~RunCleanupsScope() {
604 if (PerformCleanup) {
605 CGF.DidCallStackSave = OldDidCallStackSave;
606 CGF.PopCleanupBlocks(CleanupStackDepth);
610 /// \brief Determine whether this scope requires any cleanups.
611 bool requiresCleanups() const {
612 return CGF.EHStack.stable_begin() != CleanupStackDepth;
615 /// \brief Force the emission of cleanups now, instead of waiting
616 /// until this object is destroyed.
617 void ForceCleanup() {
618 assert(PerformCleanup && "Already forced cleanup");
619 CGF.DidCallStackSave = OldDidCallStackSave;
620 CGF.PopCleanupBlocks(CleanupStackDepth);
621 PerformCleanup = false;
626 /// PopCleanupBlocks - Takes the old cleanup stack size and emits
627 /// the cleanup blocks that have been added.
628 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
630 void ResolveBranchFixups(llvm::BasicBlock *Target);
632 /// The given basic block lies in the current EH scope, but may be a
633 /// target of a potentially scope-crossing jump; get a stable handle
634 /// to which we can perform this jump later.
635 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
636 return JumpDest(Target,
637 EHStack.getInnermostNormalCleanup(),
638 NextCleanupDestIndex++);
641 /// The given basic block lies in the current EH scope, but may be a
642 /// target of a potentially scope-crossing jump; get a stable handle
643 /// to which we can perform this jump later.
644 JumpDest getJumpDestInCurrentScope(const char *Name = 0) {
645 return getJumpDestInCurrentScope(createBasicBlock(Name));
648 /// EmitBranchThroughCleanup - Emit a branch from the current insert
649 /// block through the normal cleanup handling code (if any) and then
650 /// on to \arg Dest.
651 void EmitBranchThroughCleanup(JumpDest Dest);
653 /// EmitBranchThroughEHCleanup - Emit a branch from the current
654 /// insert block through the EH cleanup handling code (if any) and
655 /// then on to \arg Dest.
656 void EmitBranchThroughEHCleanup(UnwindDest Dest);
658 /// getRethrowDest - Returns the unified outermost-scope rethrow
659 /// destination.
660 UnwindDest getRethrowDest();
662 /// BeginConditionalBranch - Should be called before a conditional part of an
663 /// expression is emitted. For example, before the RHS of the expression below
664 /// is emitted:
666 /// b && f(T());
668 /// This is used to make sure that any temporaries created in the conditional
669 /// branch are only destroyed if the branch is taken.
670 void BeginConditionalBranch() {
671 ++ConditionalBranchLevel;
674 /// EndConditionalBranch - Should be called after a conditional part of an
675 /// expression has been emitted.
676 void EndConditionalBranch() {
677 assert(ConditionalBranchLevel != 0 &&
678 "Conditional branch mismatch!");
680 --ConditionalBranchLevel;
683 /// isInConditionalBranch - Return true if we're currently emitting
684 /// one branch or the other of a conditional expression.
685 bool isInConditionalBranch() const { return ConditionalBranchLevel != 0; }
687 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
688 /// number that holds the value.
689 unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
691 private:
692 CGDebugInfo *DebugInfo;
694 /// IndirectBranch - The first time an indirect goto is seen we create a block
695 /// with an indirect branch. Every time we see the address of a label taken,
696 /// we add the label to the indirect goto. Every subsequent indirect goto is
697 /// codegen'd as a jump to the IndirectBranch's basic block.
698 llvm::IndirectBrInst *IndirectBranch;
700 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
701 /// decls.
702 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
704 /// LabelMap - This keeps track of the LLVM basic block for each C label.
705 llvm::DenseMap<const LabelStmt*, JumpDest> LabelMap;
707 // BreakContinueStack - This keeps track of where break and continue
708 // statements should jump to.
709 struct BreakContinue {
710 BreakContinue(JumpDest Break, JumpDest Continue)
711 : BreakBlock(Break), ContinueBlock(Continue) {}
713 JumpDest BreakBlock;
714 JumpDest ContinueBlock;
716 llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
718 /// SwitchInsn - This is nearest current switch instruction. It is null if if
719 /// current context is not in a switch.
720 llvm::SwitchInst *SwitchInsn;
722 /// CaseRangeBlock - This block holds if condition check for last case
723 /// statement range in current switch instruction.
724 llvm::BasicBlock *CaseRangeBlock;
726 // VLASizeMap - This keeps track of the associated size for each VLA type.
727 // We track this by the size expression rather than the type itself because
728 // in certain situations, like a const qualifier applied to an VLA typedef,
729 // multiple VLA types can share the same size expression.
730 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
731 // enter/leave scopes.
732 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
734 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
735 /// calling llvm.stacksave for multiple VLAs in the same scope.
736 bool DidCallStackSave;
738 /// A block containing a single 'unreachable' instruction. Created
739 /// lazily by getUnreachableBlock().
740 llvm::BasicBlock *UnreachableBlock;
742 /// CXXThisDecl - When generating code for a C++ member function,
743 /// this will hold the implicit 'this' declaration.
744 ImplicitParamDecl *CXXThisDecl;
745 llvm::Value *CXXThisValue;
747 /// CXXVTTDecl - When generating code for a base object constructor or
748 /// base object destructor with virtual bases, this will hold the implicit
749 /// VTT parameter.
750 ImplicitParamDecl *CXXVTTDecl;
751 llvm::Value *CXXVTTValue;
753 /// ConditionalBranchLevel - Contains the nesting level of the current
754 /// conditional branch. This is used so that we know if a temporary should be
755 /// destroyed conditionally.
756 unsigned ConditionalBranchLevel;
759 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
760 /// type as well as the field number that contains the actual data.
761 llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
762 unsigned> > ByRefValueInfo;
764 llvm::BasicBlock *TerminateLandingPad;
765 llvm::BasicBlock *TerminateHandler;
766 llvm::BasicBlock *TrapBB;
768 public:
769 CodeGenFunction(CodeGenModule &cgm);
771 CodeGenTypes &getTypes() const { return CGM.getTypes(); }
772 ASTContext &getContext() const;
773 CGDebugInfo *getDebugInfo() { return DebugInfo; }
775 /// Returns a pointer to the function's exception object slot, which
776 /// is assigned in every landing pad.
777 llvm::Value *getExceptionSlot();
779 llvm::Value *getNormalCleanupDestSlot();
780 llvm::Value *getEHCleanupDestSlot();
782 llvm::BasicBlock *getUnreachableBlock() {
783 if (!UnreachableBlock) {
784 UnreachableBlock = createBasicBlock("unreachable");
785 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
787 return UnreachableBlock;
790 llvm::BasicBlock *getInvokeDest() {
791 if (!EHStack.requiresLandingPad()) return 0;
792 return getInvokeDestImpl();
795 llvm::LLVMContext &getLLVMContext() { return VMContext; }
797 //===--------------------------------------------------------------------===//
798 // Objective-C
799 //===--------------------------------------------------------------------===//
801 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
803 void StartObjCMethod(const ObjCMethodDecl *MD,
804 const ObjCContainerDecl *CD);
806 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
807 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
808 const ObjCPropertyImplDecl *PID);
809 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
810 ObjCMethodDecl *MD, bool ctor);
812 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
813 /// for the given property.
814 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
815 const ObjCPropertyImplDecl *PID);
816 bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
817 bool IvarTypeWithAggrGCObjects(QualType Ty);
819 //===--------------------------------------------------------------------===//
820 // Block Bits
821 //===--------------------------------------------------------------------===//
823 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
824 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
825 const CGBlockInfo &Info,
826 const llvm::StructType *,
827 llvm::Constant *BlockVarLayout,
828 std::vector<HelperInfo> *);
830 llvm::Function *GenerateBlockFunction(GlobalDecl GD,
831 const BlockExpr *BExpr,
832 CGBlockInfo &Info,
833 const Decl *OuterFuncDecl,
834 llvm::Constant *& BlockVarLayout,
835 llvm::DenseMap<const Decl*, llvm::Value*> ldm);
837 llvm::Value *LoadBlockStruct();
839 void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
840 void AllocateBlockDecl(const BlockDeclRefExpr *E);
841 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
842 return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
844 llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
845 const llvm::Type *BuildByRefType(const ValueDecl *D);
847 void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
848 void StartFunction(GlobalDecl GD, QualType RetTy,
849 llvm::Function *Fn,
850 const FunctionArgList &Args,
851 SourceLocation StartLoc);
853 void EmitConstructorBody(FunctionArgList &Args);
854 void EmitDestructorBody(FunctionArgList &Args);
855 void EmitFunctionBody(FunctionArgList &Args);
857 /// EmitReturnBlock - Emit the unified return block, trying to avoid its
858 /// emission when possible.
859 void EmitReturnBlock();
861 /// FinishFunction - Complete IR generation of the current function. It is
862 /// legal to call this function even if there is no current insertion point.
863 void FinishFunction(SourceLocation EndLoc=SourceLocation());
865 /// GenerateThunk - Generate a thunk for the given method.
866 void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
868 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
869 FunctionArgList &Args);
871 /// InitializeVTablePointer - Initialize the vtable pointer of the given
872 /// subobject.
874 void InitializeVTablePointer(BaseSubobject Base,
875 const CXXRecordDecl *NearestVBase,
876 uint64_t OffsetFromNearestVBase,
877 llvm::Constant *VTable,
878 const CXXRecordDecl *VTableClass);
880 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
881 void InitializeVTablePointers(BaseSubobject Base,
882 const CXXRecordDecl *NearestVBase,
883 uint64_t OffsetFromNearestVBase,
884 bool BaseIsNonVirtualPrimaryBase,
885 llvm::Constant *VTable,
886 const CXXRecordDecl *VTableClass,
887 VisitedVirtualBasesSetTy& VBases);
889 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
891 /// GetVTablePtr - Return the Value of the vtable pointer member pointed
892 /// to by This.
893 llvm::Value *GetVTablePtr(llvm::Value *This, const llvm::Type *Ty);
895 /// EnterDtorCleanups - Enter the cleanups necessary to complete the
896 /// given phase of destruction for a destructor. The end result
897 /// should call destructors on members and base classes in reverse
898 /// order of their construction.
899 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
901 /// ShouldInstrumentFunction - Return true if the current function should be
902 /// instrumented with __cyg_profile_func_* calls
903 bool ShouldInstrumentFunction();
905 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
906 /// instrumentation function with the current function and the call site, if
907 /// function instrumentation is enabled.
908 void EmitFunctionInstrumentation(const char *Fn);
910 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
911 /// arguments for the given function. This is also responsible for naming the
912 /// LLVM function arguments.
913 void EmitFunctionProlog(const CGFunctionInfo &FI,
914 llvm::Function *Fn,
915 const FunctionArgList &Args);
917 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
918 /// given temporary.
919 void EmitFunctionEpilog(const CGFunctionInfo &FI);
921 /// EmitStartEHSpec - Emit the start of the exception spec.
922 void EmitStartEHSpec(const Decl *D);
924 /// EmitEndEHSpec - Emit the end of the exception spec.
925 void EmitEndEHSpec(const Decl *D);
927 /// getTerminateLandingPad - Return a landing pad that just calls terminate.
928 llvm::BasicBlock *getTerminateLandingPad();
930 /// getTerminateHandler - Return a handler (not a landing pad, just
931 /// a catch handler) that just calls terminate. This is used when
932 /// a terminate scope encloses a try.
933 llvm::BasicBlock *getTerminateHandler();
935 const llvm::Type *ConvertTypeForMem(QualType T);
936 const llvm::Type *ConvertType(QualType T);
937 const llvm::Type *ConvertType(const TypeDecl *T) {
938 return ConvertType(getContext().getTypeDeclType(T));
941 /// LoadObjCSelf - Load the value of self. This function is only valid while
942 /// generating code for an Objective-C method.
943 llvm::Value *LoadObjCSelf();
945 /// TypeOfSelfObject - Return type of object that this self represents.
946 QualType TypeOfSelfObject();
948 /// hasAggregateLLVMType - Return true if the specified AST type will map into
949 /// an aggregate LLVM type or is void.
950 static bool hasAggregateLLVMType(QualType T);
952 /// createBasicBlock - Create an LLVM basic block.
953 llvm::BasicBlock *createBasicBlock(const char *Name="",
954 llvm::Function *Parent=0,
955 llvm::BasicBlock *InsertBefore=0) {
956 #ifdef NDEBUG
957 return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
958 #else
959 return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
960 #endif
963 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
964 /// label maps to.
965 JumpDest getJumpDestForLabel(const LabelStmt *S);
967 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
968 /// another basic block, simplify it. This assumes that no other code could
969 /// potentially reference the basic block.
970 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
972 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
973 /// adding a fall-through branch from the current insert block if
974 /// necessary. It is legal to call this function even if there is no current
975 /// insertion point.
977 /// IsFinished - If true, indicates that the caller has finished emitting
978 /// branches to the given block and does not expect to emit code into it. This
979 /// means the block can be ignored if it is unreachable.
980 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
982 /// EmitBranch - Emit a branch to the specified basic block from the current
983 /// insert block, taking care to avoid creation of branches from dummy
984 /// blocks. It is legal to call this function even if there is no current
985 /// insertion point.
987 /// This function clears the current insertion point. The caller should follow
988 /// calls to this function with calls to Emit*Block prior to generation new
989 /// code.
990 void EmitBranch(llvm::BasicBlock *Block);
992 /// HaveInsertPoint - True if an insertion point is defined. If not, this
993 /// indicates that the current code being emitted is unreachable.
994 bool HaveInsertPoint() const {
995 return Builder.GetInsertBlock() != 0;
998 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
999 /// emitted IR has a place to go. Note that by definition, if this function
1000 /// creates a block then that block is unreachable; callers may do better to
1001 /// detect when no insertion point is defined and simply skip IR generation.
1002 void EnsureInsertPoint() {
1003 if (!HaveInsertPoint())
1004 EmitBlock(createBasicBlock());
1007 /// ErrorUnsupported - Print out an error that codegen doesn't support the
1008 /// specified stmt yet.
1009 void ErrorUnsupported(const Stmt *S, const char *Type,
1010 bool OmitOnError=false);
1012 //===--------------------------------------------------------------------===//
1013 // Helpers
1014 //===--------------------------------------------------------------------===//
1016 LValue MakeAddrLValue(llvm::Value *V, QualType T, unsigned Alignment = 0) {
1017 return LValue::MakeAddr(V, T, Alignment, getContext(),
1018 CGM.getTBAAInfo(T));
1021 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
1022 /// block. The caller is responsible for setting an appropriate alignment on
1023 /// the alloca.
1024 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
1025 const llvm::Twine &Name = "tmp");
1027 /// InitTempAlloca - Provide an initial value for the given alloca.
1028 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
1030 /// CreateIRTemp - Create a temporary IR object of the given type, with
1031 /// appropriate alignment. This routine should only be used when an temporary
1032 /// value needs to be stored into an alloca (for example, to avoid explicit
1033 /// PHI construction), but the type is the IR type, not the type appropriate
1034 /// for storing in memory.
1035 llvm::AllocaInst *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
1037 /// CreateMemTemp - Create a temporary memory object of the given type, with
1038 /// appropriate alignment.
1039 llvm::AllocaInst *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
1041 /// CreateAggTemp - Create a temporary memory object for the given
1042 /// aggregate type.
1043 AggValueSlot CreateAggTemp(QualType T, const llvm::Twine &Name = "tmp") {
1044 return AggValueSlot::forAddr(CreateMemTemp(T, Name), false, false);
1047 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
1048 /// expression and compare the result against zero, returning an Int1Ty value.
1049 llvm::Value *EvaluateExprAsBool(const Expr *E);
1051 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
1052 void EmitIgnoredExpr(const Expr *E);
1054 /// EmitAnyExpr - Emit code to compute the specified expression which can have
1055 /// any type. The result is returned as an RValue struct. If this is an
1056 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
1057 /// the result should be returned.
1059 /// \param IgnoreResult - True if the resulting value isn't used.
1060 RValue EmitAnyExpr(const Expr *E,
1061 AggValueSlot AggSlot = AggValueSlot::ignored(),
1062 bool IgnoreResult = false);
1064 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
1065 // or the value of the expression, depending on how va_list is defined.
1066 llvm::Value *EmitVAListRef(const Expr *E);
1068 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
1069 /// always be accessible even if no aggregate location is provided.
1070 RValue EmitAnyExprToTemp(const Expr *E);
1072 /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
1073 /// arbitrary expression into the given memory location.
1074 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
1075 bool IsLocationVolatile,
1076 bool IsInitializer);
1078 /// EmitAggregateCopy - Emit an aggrate copy.
1080 /// \param isVolatile - True iff either the source or the destination is
1081 /// volatile.
1082 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1083 QualType EltTy, bool isVolatile=false);
1085 /// StartBlock - Start new block named N. If insert block is a dummy block
1086 /// then reuse it.
1087 void StartBlock(const char *N);
1089 /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
1090 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
1091 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
1094 /// GetAddrOfLocalVar - Return the address of a local variable.
1095 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
1096 llvm::Value *Res = LocalDeclMap[VD];
1097 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
1098 return Res;
1101 /// getAccessedFieldNo - Given an encoded value and a result number, return
1102 /// the input field number being accessed.
1103 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
1105 llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
1106 llvm::BasicBlock *GetIndirectGotoBlock();
1108 /// EmitNullInitialization - Generate code to set a value of the given type to
1109 /// null, If the type contains data member pointers, they will be initialized
1110 /// to -1 in accordance with the Itanium C++ ABI.
1111 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
1113 // EmitVAArg - Generate code to get an argument from the passed in pointer
1114 // and update it accordingly. The return value is a pointer to the argument.
1115 // FIXME: We should be able to get rid of this method and use the va_arg
1116 // instruction in LLVM instead once it works well enough.
1117 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
1119 /// EmitVLASize - Generate code for any VLA size expressions that might occur
1120 /// in a variably modified type. If Ty is a VLA, will return the value that
1121 /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
1123 /// This function can be called with a null (unreachable) insert point.
1124 llvm::Value *EmitVLASize(QualType Ty);
1126 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
1127 // of a variable length array type.
1128 llvm::Value *GetVLASize(const VariableArrayType *);
1130 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
1131 /// generating code for an C++ member function.
1132 llvm::Value *LoadCXXThis() {
1133 assert(CXXThisValue && "no 'this' value for this function");
1134 return CXXThisValue;
1137 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
1138 /// virtual bases.
1139 llvm::Value *LoadCXXVTT() {
1140 assert(CXXVTTValue && "no VTT value for this function");
1141 return CXXVTTValue;
1144 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
1145 /// complete class to the given direct base.
1146 llvm::Value *
1147 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
1148 const CXXRecordDecl *Derived,
1149 const CXXRecordDecl *Base,
1150 bool BaseIsVirtual);
1152 /// GetAddressOfBaseClass - This function will add the necessary delta to the
1153 /// load of 'this' and returns address of the base class.
1154 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
1155 const CXXRecordDecl *Derived,
1156 CastExpr::path_const_iterator PathBegin,
1157 CastExpr::path_const_iterator PathEnd,
1158 bool NullCheckValue);
1160 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
1161 const CXXRecordDecl *Derived,
1162 CastExpr::path_const_iterator PathBegin,
1163 CastExpr::path_const_iterator PathEnd,
1164 bool NullCheckValue);
1166 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
1167 const CXXRecordDecl *ClassDecl,
1168 const CXXRecordDecl *BaseClassDecl);
1170 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1171 CXXCtorType CtorType,
1172 const FunctionArgList &Args);
1173 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
1174 bool ForVirtualBase, llvm::Value *This,
1175 CallExpr::const_arg_iterator ArgBeg,
1176 CallExpr::const_arg_iterator ArgEnd);
1178 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1179 llvm::Value *This, llvm::Value *Src,
1180 CallExpr::const_arg_iterator ArgBeg,
1181 CallExpr::const_arg_iterator ArgEnd);
1183 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1184 const ConstantArrayType *ArrayTy,
1185 llvm::Value *ArrayPtr,
1186 CallExpr::const_arg_iterator ArgBeg,
1187 CallExpr::const_arg_iterator ArgEnd,
1188 bool ZeroInitialization = false);
1190 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
1191 llvm::Value *NumElements,
1192 llvm::Value *ArrayPtr,
1193 CallExpr::const_arg_iterator ArgBeg,
1194 CallExpr::const_arg_iterator ArgEnd,
1195 bool ZeroInitialization = false);
1197 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1198 const ArrayType *Array,
1199 llvm::Value *This);
1201 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1202 llvm::Value *NumElements,
1203 llvm::Value *This);
1205 llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
1206 const ArrayType *Array,
1207 llvm::Value *This);
1209 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
1210 bool ForVirtualBase, llvm::Value *This);
1212 void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
1213 llvm::Value *NumElements);
1215 void EmitCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
1217 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
1218 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
1220 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
1221 QualType DeleteTy);
1223 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
1224 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
1226 void EmitCheck(llvm::Value *, unsigned Size);
1228 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1229 bool isInc, bool isPre);
1230 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1231 bool isInc, bool isPre);
1232 //===--------------------------------------------------------------------===//
1233 // Declaration Emission
1234 //===--------------------------------------------------------------------===//
1236 /// EmitDecl - Emit a declaration.
1238 /// This function can be called with a null (unreachable) insert point.
1239 void EmitDecl(const Decl &D);
1241 /// EmitVarDecl - Emit a local variable declaration.
1243 /// This function can be called with a null (unreachable) insert point.
1244 void EmitVarDecl(const VarDecl &D);
1246 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
1247 llvm::Value *Address);
1249 /// EmitAutoVarDecl - Emit an auto variable declaration.
1251 /// This function can be called with a null (unreachable) insert point.
1252 void EmitAutoVarDecl(const VarDecl &D, SpecialInitFn *SpecialInit = 0);
1254 void EmitStaticVarDecl(const VarDecl &D,
1255 llvm::GlobalValue::LinkageTypes Linkage);
1257 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
1258 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
1260 //===--------------------------------------------------------------------===//
1261 // Statement Emission
1262 //===--------------------------------------------------------------------===//
1264 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
1265 void EmitStopPoint(const Stmt *S);
1267 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
1268 /// this function even if there is no current insertion point.
1270 /// This function may clear the current insertion point; callers should use
1271 /// EnsureInsertPoint if they wish to subsequently generate code without first
1272 /// calling EmitBlock, EmitBranch, or EmitStmt.
1273 void EmitStmt(const Stmt *S);
1275 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
1276 /// necessarily require an insertion point or debug information; typically
1277 /// because the statement amounts to a jump or a container of other
1278 /// statements.
1280 /// \return True if the statement was handled.
1281 bool EmitSimpleStmt(const Stmt *S);
1283 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
1284 AggValueSlot AVS = AggValueSlot::ignored());
1286 /// EmitLabel - Emit the block for the given label. It is legal to call this
1287 /// function even if there is no current insertion point.
1288 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
1290 void EmitLabelStmt(const LabelStmt &S);
1291 void EmitGotoStmt(const GotoStmt &S);
1292 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
1293 void EmitIfStmt(const IfStmt &S);
1294 void EmitWhileStmt(const WhileStmt &S);
1295 void EmitDoStmt(const DoStmt &S);
1296 void EmitForStmt(const ForStmt &S);
1297 void EmitReturnStmt(const ReturnStmt &S);
1298 void EmitDeclStmt(const DeclStmt &S);
1299 void EmitBreakStmt(const BreakStmt &S);
1300 void EmitContinueStmt(const ContinueStmt &S);
1301 void EmitSwitchStmt(const SwitchStmt &S);
1302 void EmitDefaultStmt(const DefaultStmt &S);
1303 void EmitCaseStmt(const CaseStmt &S);
1304 void EmitCaseStmtRange(const CaseStmt &S);
1305 void EmitAsmStmt(const AsmStmt &S);
1307 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
1308 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
1309 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
1310 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
1312 llvm::Constant *getUnwindResumeOrRethrowFn();
1313 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1314 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
1316 void EmitCXXTryStmt(const CXXTryStmt &S);
1318 //===--------------------------------------------------------------------===//
1319 // LValue Expression Emission
1320 //===--------------------------------------------------------------------===//
1322 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
1323 RValue GetUndefRValue(QualType Ty);
1325 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
1326 /// and issue an ErrorUnsupported style diagnostic (using the
1327 /// provided Name).
1328 RValue EmitUnsupportedRValue(const Expr *E,
1329 const char *Name);
1331 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
1332 /// an ErrorUnsupported style diagnostic (using the provided Name).
1333 LValue EmitUnsupportedLValue(const Expr *E,
1334 const char *Name);
1336 /// EmitLValue - Emit code to compute a designator that specifies the location
1337 /// of the expression.
1339 /// This can return one of two things: a simple address or a bitfield
1340 /// reference. In either case, the LLVM Value* in the LValue structure is
1341 /// guaranteed to be an LLVM pointer type.
1343 /// If this returns a bitfield reference, nothing about the pointee type of
1344 /// the LLVM value is known: For example, it may not be a pointer to an
1345 /// integer.
1347 /// If this returns a normal address, and if the lvalue's C type is fixed
1348 /// size, this method guarantees that the returned pointer type will point to
1349 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
1350 /// variable length type, this is not possible.
1352 LValue EmitLValue(const Expr *E);
1354 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1355 /// checking code to guard against undefined behavior. This is only
1356 /// suitable when we know that the address will be used to access the
1357 /// object.
1358 LValue EmitCheckedLValue(const Expr *E);
1360 /// EmitToMemory - Change a scalar value from its value
1361 /// representation to its in-memory representation.
1362 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
1364 /// EmitFromMemory - Change a scalar value from its memory
1365 /// representation to its value representation.
1366 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
1368 /// EmitLoadOfScalar - Load a scalar value from an address, taking
1369 /// care to appropriately convert from the memory representation to
1370 /// the LLVM value representation.
1371 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1372 unsigned Alignment, QualType Ty,
1373 llvm::MDNode *TBAAInfo = 0);
1375 /// EmitStoreOfScalar - Store a scalar value to an address, taking
1376 /// care to appropriately convert from the memory representation to
1377 /// the LLVM value representation.
1378 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1379 bool Volatile, unsigned Alignment, QualType Ty,
1380 llvm::MDNode *TBAAInfo = 0);
1382 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1383 /// this method emits the address of the lvalue, then loads the result as an
1384 /// rvalue, returning the rvalue.
1385 RValue EmitLoadOfLValue(LValue V, QualType LVType);
1386 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1387 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1388 RValue EmitLoadOfPropertyRefLValue(LValue LV,
1389 ReturnValueSlot Return = ReturnValueSlot());
1391 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1392 /// lvalue, where both are guaranteed to the have the same type, and that type
1393 /// is 'Ty'.
1394 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1395 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1396 QualType Ty);
1397 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst);
1399 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1400 /// EmitStoreThroughLValue.
1402 /// \param Result [out] - If non-null, this will be set to a Value* for the
1403 /// bit-field contents after the store, appropriate for use as the result of
1404 /// an assignment to the bit-field.
1405 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1406 llvm::Value **Result=0);
1408 /// Emit an l-value for an assignment (simple or compound) of complex type.
1409 LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
1410 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
1412 // Note: only availabe for agg return types
1413 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1414 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
1415 // Note: only available for agg return types
1416 LValue EmitCallExprLValue(const CallExpr *E);
1417 // Note: only available for agg return types
1418 LValue EmitVAArgExprLValue(const VAArgExpr *E);
1419 LValue EmitDeclRefLValue(const DeclRefExpr *E);
1420 LValue EmitStringLiteralLValue(const StringLiteral *E);
1421 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1422 LValue EmitPredefinedLValue(const PredefinedExpr *E);
1423 LValue EmitUnaryOpLValue(const UnaryOperator *E);
1424 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1425 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1426 LValue EmitMemberExpr(const MemberExpr *E);
1427 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1428 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1429 LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1430 LValue EmitCastLValue(const CastExpr *E);
1431 LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
1433 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1434 const ObjCIvarDecl *Ivar);
1435 LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1436 const IndirectFieldDecl* Field,
1437 unsigned CVRQualifiers);
1438 LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1439 unsigned CVRQualifiers);
1441 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1442 /// if the Field is a reference, this will return the address of the reference
1443 /// and not the address of the value stored in the reference.
1444 LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1445 const FieldDecl* Field,
1446 unsigned CVRQualifiers);
1448 LValue EmitLValueForIvar(QualType ObjectTy,
1449 llvm::Value* Base, const ObjCIvarDecl *Ivar,
1450 unsigned CVRQualifiers);
1452 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1453 unsigned CVRQualifiers);
1455 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1457 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1458 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1459 LValue EmitExprWithCleanupsLValue(const ExprWithCleanups *E);
1460 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1462 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1463 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1464 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1465 LValue EmitStmtExprLValue(const StmtExpr *E);
1466 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1467 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
1468 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
1469 //===--------------------------------------------------------------------===//
1470 // Scalar Expression Emission
1471 //===--------------------------------------------------------------------===//
1473 /// EmitCall - Generate a call of the given function, expecting the given
1474 /// result type, and using the given argument list which specifies both the
1475 /// LLVM arguments and the types they were derived from.
1477 /// \param TargetDecl - If given, the decl of the function in a direct call;
1478 /// used to set attributes on the call (noreturn, etc.).
1479 RValue EmitCall(const CGFunctionInfo &FnInfo,
1480 llvm::Value *Callee,
1481 ReturnValueSlot ReturnValue,
1482 const CallArgList &Args,
1483 const Decl *TargetDecl = 0,
1484 llvm::Instruction **callOrInvoke = 0);
1486 RValue EmitCall(QualType FnType, llvm::Value *Callee,
1487 ReturnValueSlot ReturnValue,
1488 CallExpr::const_arg_iterator ArgBeg,
1489 CallExpr::const_arg_iterator ArgEnd,
1490 const Decl *TargetDecl = 0);
1491 RValue EmitCallExpr(const CallExpr *E,
1492 ReturnValueSlot ReturnValue = ReturnValueSlot());
1494 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
1495 llvm::Value * const *ArgBegin,
1496 llvm::Value * const *ArgEnd,
1497 const llvm::Twine &Name = "");
1499 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1500 const llvm::Type *Ty);
1501 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1502 llvm::Value *This, const llvm::Type *Ty);
1503 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
1504 NestedNameSpecifier *Qual,
1505 llvm::Value *This,
1506 const llvm::Type *Ty);
1508 RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1509 llvm::Value *Callee,
1510 ReturnValueSlot ReturnValue,
1511 llvm::Value *This,
1512 llvm::Value *VTT,
1513 CallExpr::const_arg_iterator ArgBeg,
1514 CallExpr::const_arg_iterator ArgEnd);
1515 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1516 ReturnValueSlot ReturnValue);
1517 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1518 ReturnValueSlot ReturnValue);
1520 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1521 const CXXMethodDecl *MD,
1522 ReturnValueSlot ReturnValue);
1525 RValue EmitBuiltinExpr(const FunctionDecl *FD,
1526 unsigned BuiltinID, const CallExpr *E);
1528 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1530 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1531 /// is unhandled by the current target.
1532 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1534 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1535 llvm::Value *EmitNeonCall(llvm::Function *F,
1536 llvm::SmallVectorImpl<llvm::Value*> &O,
1537 const char *name,
1538 unsigned shift = 0, bool rightshift = false);
1539 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
1540 llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
1541 bool negateForRightShift);
1543 llvm::Value *BuildVector(const llvm::SmallVectorImpl<llvm::Value*> &Ops);
1544 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1545 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1547 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1548 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1549 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1550 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1551 ReturnValueSlot Return = ReturnValueSlot());
1553 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1554 /// expression. Will emit a temporary variable if E is not an LValue.
1555 RValue EmitReferenceBindingToExpr(const Expr* E,
1556 const NamedDecl *InitializedDecl);
1558 //===--------------------------------------------------------------------===//
1559 // Expression Emission
1560 //===--------------------------------------------------------------------===//
1562 // Expressions are broken into three classes: scalar, complex, aggregate.
1564 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1565 /// scalar type, returning the result.
1566 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1568 /// EmitScalarConversion - Emit a conversion from the specified type to the
1569 /// specified destination type, both of which are LLVM scalar types.
1570 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1571 QualType DstTy);
1573 /// EmitComplexToScalarConversion - Emit a conversion from the specified
1574 /// complex type to the specified destination type, where the destination type
1575 /// is an LLVM scalar type.
1576 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1577 QualType DstTy);
1580 /// EmitAggExpr - Emit the computation of the specified expression
1581 /// of aggregate type. The result is computed into the given slot,
1582 /// which may be null to indicate that the value is not needed.
1583 void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false);
1585 /// EmitAggExprToLValue - Emit the computation of the specified expression of
1586 /// aggregate type into a temporary LValue.
1587 LValue EmitAggExprToLValue(const Expr *E);
1589 /// EmitGCMemmoveCollectable - Emit special API for structs with object
1590 /// pointers.
1591 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1592 QualType Ty);
1594 /// EmitComplexExpr - Emit the computation of the specified expression of
1595 /// complex type, returning the result.
1596 ComplexPairTy EmitComplexExpr(const Expr *E,
1597 bool IgnoreReal = false,
1598 bool IgnoreImag = false);
1600 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1601 /// of complex type, storing into the specified Value*.
1602 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1603 bool DestIsVolatile);
1605 /// StoreComplexToAddr - Store a complex number into the specified address.
1606 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1607 bool DestIsVolatile);
1608 /// LoadComplexFromAddr - Load a complex number from the specified address.
1609 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1611 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
1612 /// a static local variable.
1613 llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
1614 const char *Separator,
1615 llvm::GlobalValue::LinkageTypes Linkage);
1617 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
1618 /// global variable that has already been created for it. If the initializer
1619 /// has a different type than GV does, this may free GV and return a different
1620 /// one. Otherwise it just returns GV.
1621 llvm::GlobalVariable *
1622 AddInitializerToStaticVarDecl(const VarDecl &D,
1623 llvm::GlobalVariable *GV);
1626 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1627 /// variable with global storage.
1628 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1630 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1631 /// with the C++ runtime so that its destructor will be called at exit.
1632 void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1633 llvm::Constant *DeclPtr);
1635 /// Emit code in this function to perform a guarded variable
1636 /// initialization. Guarded initializations are used when it's not
1637 /// possible to prove that an initialization will be done exactly
1638 /// once, e.g. with a static local variable or a static data member
1639 /// of a class template.
1640 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr);
1642 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1643 /// variables.
1644 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1645 llvm::Constant **Decls,
1646 unsigned NumDecls);
1648 /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1649 /// variables.
1650 void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1651 const std::vector<std::pair<llvm::WeakVH,
1652 llvm::Constant*> > &DtorsAndObjects);
1654 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D,
1655 llvm::GlobalVariable *Addr);
1657 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
1659 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
1660 const Expr *Exp);
1662 RValue EmitExprWithCleanups(const ExprWithCleanups *E,
1663 AggValueSlot Slot =AggValueSlot::ignored());
1665 void EmitCXXThrowExpr(const CXXThrowExpr *E);
1667 //===--------------------------------------------------------------------===//
1668 // Internal Helpers
1669 //===--------------------------------------------------------------------===//
1671 /// ContainsLabel - Return true if the statement contains a label in it. If
1672 /// this statement is not executed normally, it not containing a label means
1673 /// that we can just remove the code.
1674 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1676 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1677 /// to a constant, or if it does but contains a label, return 0. If it
1678 /// constant folds to 'true' and does not contain a label, return 1, if it
1679 /// constant folds to 'false' and does not contain a label, return -1.
1680 int ConstantFoldsToSimpleInteger(const Expr *Cond);
1682 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1683 /// if statement) to the specified blocks. Based on the condition, this might
1684 /// try to simplify the codegen of the conditional based on the branch.
1685 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1686 llvm::BasicBlock *FalseBlock);
1688 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll
1689 /// generate a branch around the created basic block as necessary.
1690 llvm::BasicBlock *getTrapBB();
1692 /// EmitCallArg - Emit a single call argument.
1693 RValue EmitCallArg(const Expr *E, QualType ArgType);
1695 /// EmitDelegateCallArg - We are performing a delegate call; that
1696 /// is, the current function is delegating to another one. Produce
1697 /// a r-value suitable for passing the given parameter.
1698 RValue EmitDelegateCallArg(const VarDecl *Param);
1700 private:
1701 void EmitReturnOfRValue(RValue RV, QualType Ty);
1703 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1704 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1706 /// \param AI - The first function argument of the expansion.
1707 /// \return The argument following the last expanded function
1708 /// argument.
1709 llvm::Function::arg_iterator
1710 ExpandTypeFromArgs(QualType Ty, LValue Dst,
1711 llvm::Function::arg_iterator AI);
1713 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1714 /// Ty, into individual arguments on the provided vector \arg Args. See
1715 /// ABIArgInfo::Expand.
1716 void ExpandTypeToArgs(QualType Ty, RValue Src,
1717 llvm::SmallVector<llvm::Value*, 16> &Args);
1719 llvm::Value* EmitAsmInput(const AsmStmt &S,
1720 const TargetInfo::ConstraintInfo &Info,
1721 const Expr *InputExpr, std::string &ConstraintStr);
1723 llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
1724 const TargetInfo::ConstraintInfo &Info,
1725 LValue InputValue, QualType InputType,
1726 std::string &ConstraintStr);
1728 /// EmitCallArgs - Emit call arguments for a function.
1729 /// The CallArgTypeInfo parameter is used for iterating over the known
1730 /// argument types of the function being called.
1731 template<typename T>
1732 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1733 CallExpr::const_arg_iterator ArgBeg,
1734 CallExpr::const_arg_iterator ArgEnd) {
1735 CallExpr::const_arg_iterator Arg = ArgBeg;
1737 // First, use the argument types that the type info knows about
1738 if (CallArgTypeInfo) {
1739 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1740 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1741 assert(Arg != ArgEnd && "Running over edge of argument list!");
1742 QualType ArgType = *I;
1743 #ifndef NDEBUG
1744 QualType ActualArgType = Arg->getType();
1745 if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
1746 QualType ActualBaseType =
1747 ActualArgType->getAs<PointerType>()->getPointeeType();
1748 QualType ArgBaseType =
1749 ArgType->getAs<PointerType>()->getPointeeType();
1750 if (ArgBaseType->isVariableArrayType()) {
1751 if (const VariableArrayType *VAT =
1752 getContext().getAsVariableArrayType(ActualBaseType)) {
1753 if (!VAT->getSizeExpr())
1754 ActualArgType = ArgType;
1758 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1759 getTypePtr() ==
1760 getContext().getCanonicalType(ActualArgType).getTypePtr() &&
1761 "type mismatch in call argument!");
1762 #endif
1763 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1764 ArgType));
1767 // Either we've emitted all the call args, or we have a call to a
1768 // variadic function.
1769 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1770 "Extra arguments in non-variadic function!");
1774 // If we still have any arguments, emit them using the type of the argument.
1775 for (; Arg != ArgEnd; ++Arg) {
1776 QualType ArgType = Arg->getType();
1777 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1778 ArgType));
1782 const TargetCodeGenInfo &getTargetHooks() const {
1783 return CGM.getTargetCodeGenInfo();
1786 void EmitDeclMetadata();
1789 /// CGBlockInfo - Information to generate a block literal.
1790 class CGBlockInfo {
1791 public:
1792 /// Name - The name of the block, kindof.
1793 const char *Name;
1795 /// DeclRefs - Variables from parent scopes that have been
1796 /// imported into this block.
1797 llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
1799 /// InnerBlocks - This block and the blocks it encloses.
1800 llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
1802 /// CXXThisRef - Non-null if 'this' was required somewhere, in
1803 /// which case this is that expression.
1804 const CXXThisExpr *CXXThisRef;
1806 /// NeedsObjCSelf - True if something in this block has an implicit
1807 /// reference to 'self'.
1808 bool NeedsObjCSelf : 1;
1810 /// HasCXXObject - True if block has imported c++ object requiring copy
1811 /// construction in copy helper and destruction in copy dispose helpers.
1812 bool HasCXXObject : 1;
1814 /// These are initialized by GenerateBlockFunction.
1815 bool BlockHasCopyDispose : 1;
1816 CharUnits BlockSize;
1817 CharUnits BlockAlign;
1818 llvm::SmallVector<const Expr*, 8> BlockLayout;
1820 CGBlockInfo(const char *Name);
1823 } // end namespace CodeGen
1824 } // end namespace clang
1826 #endif