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 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/TargetInfo.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "CodeGenModule.h"
27 #include "CGBuilder.h"
44 class CXXDestructorDecl;
47 class EnumConstantDecl;
49 class FunctionProtoType;
51 class ObjCContainerDecl;
52 class ObjCInterfaceDecl;
55 class ObjCImplementationDecl;
56 class ObjCPropertyImplDecl;
58 class TargetCodeGenInfo;
60 class ObjCForCollectionStmt;
62 class ObjCAtThrowStmt;
63 class ObjCAtSynchronizedStmt;
72 /// CodeGenFunction - This class organizes the per-function state that is used
73 /// while generating LLVM code.
74 class CodeGenFunction : public BlockFunction {
75 CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
76 void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT
78 CodeGenModule &CGM; // Per-module state.
79 const TargetInfo &Target;
81 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
84 /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
85 /// This excludes BlockDecls.
86 const Decl *CurFuncDecl;
87 /// CurCodeDecl - This is the inner-most code context, which includes blocks.
88 const Decl *CurCodeDecl;
89 const CGFunctionInfo *CurFnInfo;
91 llvm::Function *CurFn;
93 /// CurGD - The GlobalDecl for the current function being compiled.
96 /// ReturnBlock - Unified return block.
97 llvm::BasicBlock *ReturnBlock;
98 /// ReturnValue - The temporary alloca to hold the return value. This is null
99 /// iff the function has no return value.
100 llvm::Value *ReturnValue;
102 /// AllocaInsertPoint - This is an instruction in the entry block before which
103 /// we prefer to insert allocas.
104 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
106 const llvm::Type *LLVMIntTy;
107 uint32_t LLVMPointerWidth;
112 /// \brief A mapping from NRVO variables to the flags used to indicate
113 /// when the NRVO has been applied to this variable.
114 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
117 /// ObjCEHValueStack - Stack of Objective-C exception values, used for
119 llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
121 /// PushCleanupBlock - Push a new cleanup entry on the stack and set the
122 /// passed in block as the cleanup block.
123 void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
124 llvm::BasicBlock *CleanupExitBlock,
125 llvm::BasicBlock *PreviousInvokeDest,
126 bool EHOnly = false);
127 void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock) {
128 PushCleanupBlock(CleanupEntryBlock, 0, getInvokeDest(), false);
131 /// CleanupBlockInfo - A struct representing a popped cleanup block.
132 struct CleanupBlockInfo {
133 /// CleanupEntryBlock - the cleanup entry block
134 llvm::BasicBlock *CleanupBlock;
136 /// SwitchBlock - the block (if any) containing the switch instruction used
137 /// for jumping to the final destination.
138 llvm::BasicBlock *SwitchBlock;
140 /// EndBlock - the default destination for the switch instruction.
141 llvm::BasicBlock *EndBlock;
143 /// EHOnly - True iff this cleanup should only be performed on the
144 /// exceptional edge.
147 CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb,
148 llvm::BasicBlock *eb, bool ehonly = false)
149 : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb), EHOnly(ehonly) {}
152 /// EHCleanupBlock - RAII object that will create a cleanup block for the
153 /// exceptional edge and set the insert point to that block. When destroyed,
154 /// it creates the cleanup edge and sets the insert point to the previous
156 class EHCleanupBlock {
157 CodeGenFunction& CGF;
158 llvm::BasicBlock *PreviousInsertionBlock;
159 llvm::BasicBlock *CleanupHandler;
160 llvm::BasicBlock *PreviousInvokeDest;
162 EHCleanupBlock(CodeGenFunction &cgf)
164 PreviousInsertionBlock(CGF.Builder.GetInsertBlock()),
165 CleanupHandler(CGF.createBasicBlock("ehcleanup", CGF.CurFn)),
166 PreviousInvokeDest(CGF.getInvokeDest()) {
167 llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler();
168 CGF.Builder.SetInsertPoint(CleanupHandler);
169 CGF.setInvokeDest(TerminateHandler);
174 /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all
175 /// branch fixups and return a block info struct with the switch block and end
176 /// block. This will also reset the invoke handler to the previous value
177 /// from when the cleanup block was created.
178 CleanupBlockInfo PopCleanupBlock();
180 /// DelayedCleanupBlock - RAII object that will create a cleanup block and set
181 /// the insert point to that block. When destructed, it sets the insert point
182 /// to the previous block and pushes a new cleanup entry on the stack.
183 class DelayedCleanupBlock {
184 CodeGenFunction& CGF;
185 llvm::BasicBlock *CurBB;
186 llvm::BasicBlock *CleanupEntryBB;
187 llvm::BasicBlock *CleanupExitBB;
188 llvm::BasicBlock *CurInvokeDest;
192 DelayedCleanupBlock(CodeGenFunction &cgf, bool ehonly = false)
193 : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()),
194 CleanupEntryBB(CGF.createBasicBlock("cleanup")),
196 CurInvokeDest(CGF.getInvokeDest()),
198 CGF.Builder.SetInsertPoint(CleanupEntryBB);
201 llvm::BasicBlock *getCleanupExitBlock() {
203 CleanupExitBB = CGF.createBasicBlock("cleanup.exit");
204 return CleanupExitBB;
207 ~DelayedCleanupBlock() {
208 CGF.PushCleanupBlock(CleanupEntryBB, CleanupExitBB, CurInvokeDest,
210 // FIXME: This is silly, move this into the builder.
212 CGF.Builder.SetInsertPoint(CurBB);
214 CGF.Builder.ClearInsertionPoint();
218 /// \brief Enters a new scope for capturing cleanups, all of which will be
219 /// executed once the scope is exited.
221 CodeGenFunction& CGF;
222 size_t CleanupStackDepth;
223 bool OldDidCallStackSave;
226 CleanupScope(const CleanupScope &); // DO NOT IMPLEMENT
227 CleanupScope &operator=(const CleanupScope &); // DO NOT IMPLEMENT
230 /// \brief Enter a new cleanup scope.
231 explicit CleanupScope(CodeGenFunction &CGF)
232 : CGF(CGF), PerformCleanup(true)
234 CleanupStackDepth = CGF.CleanupEntries.size();
235 OldDidCallStackSave = CGF.DidCallStackSave;
238 /// \brief Exit this cleanup scope, emitting any accumulated
241 if (PerformCleanup) {
242 CGF.DidCallStackSave = OldDidCallStackSave;
243 CGF.EmitCleanupBlocks(CleanupStackDepth);
247 /// \brief Determine whether this scope requires any cleanups.
248 bool requiresCleanups() const {
249 return CGF.CleanupEntries.size() > CleanupStackDepth;
252 /// \brief Force the emission of cleanups now, instead of waiting
253 /// until this object is destroyed.
254 void ForceCleanup() {
255 assert(PerformCleanup && "Already forced cleanup");
256 CGF.DidCallStackSave = OldDidCallStackSave;
257 CGF.EmitCleanupBlocks(CleanupStackDepth);
258 PerformCleanup = false;
262 /// CXXTemporariesCleanupScope - Enters a new scope for catching live
263 /// temporaries, all of which will be popped once the scope is exited.
264 class CXXTemporariesCleanupScope {
265 CodeGenFunction &CGF;
266 size_t NumLiveTemporaries;
269 CXXTemporariesCleanupScope(const CXXTemporariesCleanupScope &);
270 CXXTemporariesCleanupScope &operator=(const CXXTemporariesCleanupScope &);
273 explicit CXXTemporariesCleanupScope(CodeGenFunction &CGF)
274 : CGF(CGF), NumLiveTemporaries(CGF.LiveTemporaries.size()) { }
276 ~CXXTemporariesCleanupScope() {
277 while (CGF.LiveTemporaries.size() > NumLiveTemporaries)
278 CGF.PopCXXTemporary();
283 /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup
284 /// blocks that have been added.
285 void EmitCleanupBlocks(size_t OldCleanupStackSize);
287 /// EmitBranchThroughCleanup - Emit a branch from the current insert block
288 /// through the cleanup handling code (if any) and then on to \arg Dest.
290 /// FIXME: Maybe this should really be in EmitBranch? Don't we always want
291 /// this behavior for branches?
292 void EmitBranchThroughCleanup(llvm::BasicBlock *Dest);
294 /// BeginConditionalBranch - Should be called before a conditional part of an
295 /// expression is emitted. For example, before the RHS of the expression below
300 /// This is used to make sure that any temporaries created in the conditional
301 /// branch are only destroyed if the branch is taken.
302 void BeginConditionalBranch() {
303 ++ConditionalBranchLevel;
306 /// EndConditionalBranch - Should be called after a conditional part of an
307 /// expression has been emitted.
308 void EndConditionalBranch() {
309 assert(ConditionalBranchLevel != 0 &&
310 "Conditional branch mismatch!");
312 --ConditionalBranchLevel;
316 CGDebugInfo *DebugInfo;
318 /// IndirectBranch - The first time an indirect goto is seen we create a block
319 /// with an indirect branch. Every time we see the address of a label taken,
320 /// we add the label to the indirect goto. Every subsequent indirect goto is
321 /// codegen'd as a jump to the IndirectBranch's basic block.
322 llvm::IndirectBrInst *IndirectBranch;
324 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
326 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
328 /// LabelMap - This keeps track of the LLVM basic block for each C label.
329 llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
331 // BreakContinueStack - This keeps track of where break and continue
332 // statements should jump to.
333 struct BreakContinue {
334 BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
335 : BreakBlock(bb), ContinueBlock(cb) {}
337 llvm::BasicBlock *BreakBlock;
338 llvm::BasicBlock *ContinueBlock;
340 llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
342 /// SwitchInsn - This is nearest current switch instruction. It is null if if
343 /// current context is not in a switch.
344 llvm::SwitchInst *SwitchInsn;
346 /// CaseRangeBlock - This block holds if condition check for last case
347 /// statement range in current switch instruction.
348 llvm::BasicBlock *CaseRangeBlock;
350 /// InvokeDest - This is the nearest exception target for calls
351 /// which can unwind, when exceptions are being used.
352 llvm::BasicBlock *InvokeDest;
354 // VLASizeMap - This keeps track of the associated size for each VLA type.
355 // We track this by the size expression rather than the type itself because
356 // in certain situations, like a const qualifier applied to an VLA typedef,
357 // multiple VLA types can share the same size expression.
358 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
359 // enter/leave scopes.
360 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
362 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
363 /// calling llvm.stacksave for multiple VLAs in the same scope.
364 bool DidCallStackSave;
366 struct CleanupEntry {
367 /// CleanupEntryBlock - The block of code that does the actual cleanup.
368 llvm::BasicBlock *CleanupEntryBlock;
370 /// CleanupExitBlock - The cleanup exit block.
371 llvm::BasicBlock *CleanupExitBlock;
373 /// Blocks - Basic blocks that were emitted in the current cleanup scope.
374 std::vector<llvm::BasicBlock *> Blocks;
376 /// BranchFixups - Branch instructions to basic blocks that haven't been
377 /// inserted into the current function yet.
378 std::vector<llvm::BranchInst *> BranchFixups;
380 /// PreviousInvokeDest - The invoke handler from the start of the cleanup
382 llvm::BasicBlock *PreviousInvokeDest;
384 /// EHOnly - Perform this only on the exceptional edge, not the main edge.
387 explicit CleanupEntry(llvm::BasicBlock *CleanupEntryBlock,
388 llvm::BasicBlock *CleanupExitBlock,
389 llvm::BasicBlock *PreviousInvokeDest,
391 : CleanupEntryBlock(CleanupEntryBlock),
392 CleanupExitBlock(CleanupExitBlock),
393 PreviousInvokeDest(PreviousInvokeDest),
397 /// CleanupEntries - Stack of cleanup entries.
398 llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
400 typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
402 /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
403 BlockScopeMap BlockScopes;
405 /// CXXThisDecl - When generating code for a C++ member function,
406 /// this will hold the implicit 'this' declaration.
407 ImplicitParamDecl *CXXThisDecl;
408 llvm::Value *CXXThisValue;
410 /// CXXVTTDecl - When generating code for a base object constructor or
411 /// base object destructor with virtual bases, this will hold the implicit
413 ImplicitParamDecl *CXXVTTDecl;
414 llvm::Value *CXXVTTValue;
416 /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
417 struct CXXLiveTemporaryInfo {
418 /// Temporary - The live temporary.
419 const CXXTemporary *Temporary;
421 /// ThisPtr - The pointer to the temporary.
422 llvm::Value *ThisPtr;
424 /// DtorBlock - The destructor block.
425 llvm::BasicBlock *DtorBlock;
427 /// CondPtr - If this is a conditional temporary, this is the pointer to the
428 /// condition variable that states whether the destructor should be called
430 llvm::Value *CondPtr;
432 CXXLiveTemporaryInfo(const CXXTemporary *temporary,
433 llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
434 llvm::Value *condptr)
435 : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
439 llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
441 /// ConditionalBranchLevel - Contains the nesting level of the current
442 /// conditional branch. This is used so that we know if a temporary should be
443 /// destroyed conditionally.
444 unsigned ConditionalBranchLevel;
447 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
448 /// type as well as the field number that contains the actual data.
449 llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
450 unsigned> > ByRefValueInfo;
452 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
453 /// number that holds the value.
454 unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
456 llvm::BasicBlock *TerminateHandler;
457 llvm::BasicBlock *TrapBB;
459 int UniqueAggrDestructorCount;
461 CodeGenFunction(CodeGenModule &cgm);
463 ASTContext &getContext() const;
464 CGDebugInfo *getDebugInfo() { return DebugInfo; }
466 llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
467 void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
469 llvm::LLVMContext &getLLVMContext() { return VMContext; }
471 //===--------------------------------------------------------------------===//
473 //===--------------------------------------------------------------------===//
475 void GenerateObjCMethod(const ObjCMethodDecl *OMD);
477 void StartObjCMethod(const ObjCMethodDecl *MD,
478 const ObjCContainerDecl *CD);
480 /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
481 void GenerateObjCGetter(ObjCImplementationDecl *IMP,
482 const ObjCPropertyImplDecl *PID);
483 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
484 ObjCMethodDecl *MD, bool ctor);
486 /// GenerateObjCSetter - Synthesize an Objective-C property setter function
487 /// for the given property.
488 void GenerateObjCSetter(ObjCImplementationDecl *IMP,
489 const ObjCPropertyImplDecl *PID);
490 bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
491 bool IvarTypeWithAggrGCObjects(QualType Ty);
493 //===--------------------------------------------------------------------===//
495 //===--------------------------------------------------------------------===//
497 llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
498 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
499 bool BlockHasCopyDispose,
501 const llvm::StructType *,
502 std::vector<HelperInfo> *);
504 llvm::Function *GenerateBlockFunction(const BlockExpr *BExpr,
506 const Decl *OuterFuncDecl,
507 llvm::DenseMap<const Decl*, llvm::Value*> ldm);
509 llvm::Value *LoadBlockStruct();
511 void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
512 void AllocateBlockDecl(const BlockDeclRefExpr *E);
513 llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
514 return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
516 llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
517 const llvm::Type *BuildByRefType(const ValueDecl *D);
519 void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
520 void StartFunction(GlobalDecl GD, QualType RetTy,
522 const FunctionArgList &Args,
523 SourceLocation StartLoc);
525 void EmitConstructorBody(FunctionArgList &Args);
526 void EmitDestructorBody(FunctionArgList &Args);
527 void EmitFunctionBody(FunctionArgList &Args);
529 /// EmitReturnBlock - Emit the unified return block, trying to avoid its
530 /// emission when possible.
531 void EmitReturnBlock();
533 /// FinishFunction - Complete IR generation of the current function. It is
534 /// legal to call this function even if there is no current insertion point.
535 void FinishFunction(SourceLocation EndLoc=SourceLocation());
537 /// GenerateThunk - Generate a thunk for the given method.
538 void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
540 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
541 FunctionArgList &Args);
543 /// InitializeVTablePointer - Initialize the vtable pointer of the given
546 void InitializeVTablePointer(BaseSubobject Base,
547 const CXXRecordDecl *NearestVBase,
548 uint64_t OffsetFromNearestVBase,
549 llvm::Constant *VTable,
550 const CXXRecordDecl *VTableClass);
552 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
553 void InitializeVTablePointers(BaseSubobject Base,
554 const CXXRecordDecl *NearestVBase,
555 uint64_t OffsetFromNearestVBase,
556 bool BaseIsNonVirtualPrimaryBase,
557 llvm::Constant *VTable,
558 const CXXRecordDecl *VTableClass,
559 VisitedVirtualBasesSetTy& VBases);
561 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
564 /// EmitDtorEpilogue - Emit all code that comes at the end of class's
565 /// destructor. This is to call destructors on members and base classes in
566 /// reverse order of their construction.
567 void EmitDtorEpilogue(const CXXDestructorDecl *Dtor,
570 /// EmitFunctionProlog - Emit the target specific LLVM code to load the
571 /// arguments for the given function. This is also responsible for naming the
572 /// LLVM function arguments.
573 void EmitFunctionProlog(const CGFunctionInfo &FI,
575 const FunctionArgList &Args);
577 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
579 void EmitFunctionEpilog(const CGFunctionInfo &FI, llvm::Value *ReturnValue);
581 /// EmitStartEHSpec - Emit the start of the exception spec.
582 void EmitStartEHSpec(const Decl *D);
584 /// EmitEndEHSpec - Emit the end of the exception spec.
585 void EmitEndEHSpec(const Decl *D);
587 /// getTerminateHandler - Return a handler that just calls terminate.
588 llvm::BasicBlock *getTerminateHandler();
590 const llvm::Type *ConvertTypeForMem(QualType T);
591 const llvm::Type *ConvertType(QualType T);
592 const llvm::Type *ConvertType(const TypeDecl *T) {
593 return ConvertType(getContext().getTypeDeclType(T));
596 /// LoadObjCSelf - Load the value of self. This function is only valid while
597 /// generating code for an Objective-C method.
598 llvm::Value *LoadObjCSelf();
600 /// TypeOfSelfObject - Return type of object that this self represents.
601 QualType TypeOfSelfObject();
603 /// hasAggregateLLVMType - Return true if the specified AST type will map into
604 /// an aggregate LLVM type or is void.
605 static bool hasAggregateLLVMType(QualType T);
607 /// createBasicBlock - Create an LLVM basic block.
608 llvm::BasicBlock *createBasicBlock(const char *Name="",
609 llvm::Function *Parent=0,
610 llvm::BasicBlock *InsertBefore=0) {
612 return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
614 return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
618 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
620 llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
622 /// SimplifyForwardingBlocks - If the given basic block is only a branch to
623 /// another basic block, simplify it. This assumes that no other code could
624 /// potentially reference the basic block.
625 void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
627 /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
628 /// adding a fall-through branch from the current insert block if
629 /// necessary. It is legal to call this function even if there is no current
632 /// IsFinished - If true, indicates that the caller has finished emitting
633 /// branches to the given block and does not expect to emit code into it. This
634 /// means the block can be ignored if it is unreachable.
635 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
637 /// EmitBranch - Emit a branch to the specified basic block from the current
638 /// insert block, taking care to avoid creation of branches from dummy
639 /// blocks. It is legal to call this function even if there is no current
642 /// This function clears the current insertion point. The caller should follow
643 /// calls to this function with calls to Emit*Block prior to generation new
645 void EmitBranch(llvm::BasicBlock *Block);
647 /// HaveInsertPoint - True if an insertion point is defined. If not, this
648 /// indicates that the current code being emitted is unreachable.
649 bool HaveInsertPoint() const {
650 return Builder.GetInsertBlock() != 0;
653 /// EnsureInsertPoint - Ensure that an insertion point is defined so that
654 /// emitted IR has a place to go. Note that by definition, if this function
655 /// creates a block then that block is unreachable; callers may do better to
656 /// detect when no insertion point is defined and simply skip IR generation.
657 void EnsureInsertPoint() {
658 if (!HaveInsertPoint())
659 EmitBlock(createBasicBlock());
662 /// ErrorUnsupported - Print out an error that codegen doesn't support the
663 /// specified stmt yet.
664 void ErrorUnsupported(const Stmt *S, const char *Type,
665 bool OmitOnError=false);
667 //===--------------------------------------------------------------------===//
669 //===--------------------------------------------------------------------===//
671 Qualifiers MakeQualifiers(QualType T) {
672 Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
673 Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
677 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
678 /// block. The caller is responsible for setting an appropriate alignment on
680 llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
681 const llvm::Twine &Name = "tmp");
683 /// InitTempAlloca - Provide an initial value for the given alloca.
684 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
686 /// CreateIRTemp - Create a temporary IR object of the given type, with
687 /// appropriate alignment. This routine should only be used when an temporary
688 /// value needs to be stored into an alloca (for example, to avoid explicit
689 /// PHI construction), but the type is the IR type, not the type appropriate
690 /// for storing in memory.
691 llvm::Value *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
693 /// CreateMemTemp - Create a temporary memory object of the given type, with
694 /// appropriate alignment.
695 llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
697 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
698 /// expression and compare the result against zero, returning an Int1Ty value.
699 llvm::Value *EvaluateExprAsBool(const Expr *E);
701 /// EmitAnyExpr - Emit code to compute the specified expression which can have
702 /// any type. The result is returned as an RValue struct. If this is an
703 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
704 /// the result should be returned.
706 /// \param IgnoreResult - True if the resulting value isn't used.
707 RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
708 bool IsAggLocVolatile = false, bool IgnoreResult = false,
709 bool IsInitializer = false);
711 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
712 // or the value of the expression, depending on how va_list is defined.
713 llvm::Value *EmitVAListRef(const Expr *E);
715 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
716 /// always be accessible even if no aggregate location is provided.
717 RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
718 bool IsInitializer = false);
720 /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
721 /// arbitrary expression into the given memory location.
722 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
723 bool IsLocationVolatile = false,
724 bool IsInitializer = false);
726 /// EmitAggregateCopy - Emit an aggrate copy.
728 /// \param isVolatile - True iff either the source or the destination is
730 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
731 QualType EltTy, bool isVolatile=false);
733 /// StartBlock - Start new block named N. If insert block is a dummy block
735 void StartBlock(const char *N);
737 /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
738 llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
740 /// GetAddrOfLocalVar - Return the address of a local variable.
741 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
743 /// getAccessedFieldNo - Given an encoded value and a result number, return
744 /// the input field number being accessed.
745 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
747 llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
748 llvm::BasicBlock *GetIndirectGotoBlock();
750 /// EmitNullInitialization - Generate code to set a value of the given type to
751 /// null, If the type contains data member pointers, they will be initialized
752 /// to -1 in accordance with the Itanium C++ ABI.
753 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
755 // EmitVAArg - Generate code to get an argument from the passed in pointer
756 // and update it accordingly. The return value is a pointer to the argument.
757 // FIXME: We should be able to get rid of this method and use the va_arg
758 // instruction in LLVM instead once it works well enough.
759 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
761 /// EmitVLASize - Generate code for any VLA size expressions that might occur
762 /// in a variably modified type. If Ty is a VLA, will return the value that
763 /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
765 /// This function can be called with a null (unreachable) insert point.
766 llvm::Value *EmitVLASize(QualType Ty);
768 // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
769 // of a variable length array type.
770 llvm::Value *GetVLASize(const VariableArrayType *);
772 /// LoadCXXThis - Load the value of 'this'. This function is only valid while
773 /// generating code for an C++ member function.
774 llvm::Value *LoadCXXThis() {
775 assert(CXXThisValue && "no 'this' value for this function");
779 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
781 llvm::Value *LoadCXXVTT() {
782 assert(CXXVTTValue && "no VTT value for this function");
786 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
787 /// complete class to the given direct base.
789 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
790 const CXXRecordDecl *Derived,
791 const CXXRecordDecl *Base,
794 /// GetAddressOfBaseClass - This function will add the necessary delta to the
795 /// load of 'this' and returns address of the base class.
796 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
797 const CXXRecordDecl *Derived,
798 const CXXBaseSpecifierArray &BasePath,
799 bool NullCheckValue);
801 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
802 const CXXRecordDecl *Derived,
803 const CXXBaseSpecifierArray &BasePath,
804 bool NullCheckValue);
806 llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
807 const CXXRecordDecl *ClassDecl,
808 const CXXRecordDecl *BaseClassDecl);
810 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
811 CXXCtorType CtorType,
812 const FunctionArgList &Args);
813 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
814 bool ForVirtualBase, llvm::Value *This,
815 CallExpr::const_arg_iterator ArgBeg,
816 CallExpr::const_arg_iterator ArgEnd);
818 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
819 const ConstantArrayType *ArrayTy,
820 llvm::Value *ArrayPtr,
821 CallExpr::const_arg_iterator ArgBeg,
822 CallExpr::const_arg_iterator ArgEnd);
824 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
825 llvm::Value *NumElements,
826 llvm::Value *ArrayPtr,
827 CallExpr::const_arg_iterator ArgBeg,
828 CallExpr::const_arg_iterator ArgEnd);
830 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
831 const ArrayType *Array,
834 void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
835 llvm::Value *NumElements,
838 llvm::Constant *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
839 const ArrayType *Array,
842 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
843 bool ForVirtualBase, llvm::Value *This);
845 void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
846 void PopCXXTemporary();
848 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
849 void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
851 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
854 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
855 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
857 void EmitCheck(llvm::Value *, unsigned Size);
859 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
860 bool isInc, bool isPre);
861 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
862 bool isInc, bool isPre);
863 //===--------------------------------------------------------------------===//
864 // Declaration Emission
865 //===--------------------------------------------------------------------===//
867 /// EmitDecl - Emit a declaration.
869 /// This function can be called with a null (unreachable) insert point.
870 void EmitDecl(const Decl &D);
872 /// EmitBlockVarDecl - Emit a block variable declaration.
874 /// This function can be called with a null (unreachable) insert point.
875 void EmitBlockVarDecl(const VarDecl &D);
877 /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
879 /// This function can be called with a null (unreachable) insert point.
880 void EmitLocalBlockVarDecl(const VarDecl &D);
882 void EmitStaticBlockVarDecl(const VarDecl &D,
883 llvm::GlobalValue::LinkageTypes Linkage);
885 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
886 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
888 //===--------------------------------------------------------------------===//
889 // Statement Emission
890 //===--------------------------------------------------------------------===//
892 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
893 void EmitStopPoint(const Stmt *S);
895 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
896 /// this function even if there is no current insertion point.
898 /// This function may clear the current insertion point; callers should use
899 /// EnsureInsertPoint if they wish to subsequently generate code without first
900 /// calling EmitBlock, EmitBranch, or EmitStmt.
901 void EmitStmt(const Stmt *S);
903 /// EmitSimpleStmt - Try to emit a "simple" statement which does not
904 /// necessarily require an insertion point or debug information; typically
905 /// because the statement amounts to a jump or a container of other
908 /// \return True if the statement was handled.
909 bool EmitSimpleStmt(const Stmt *S);
911 RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
912 llvm::Value *AggLoc = 0, bool isAggVol = false);
914 /// EmitLabel - Emit the block for the given label. It is legal to call this
915 /// function even if there is no current insertion point.
916 void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
918 void EmitLabelStmt(const LabelStmt &S);
919 void EmitGotoStmt(const GotoStmt &S);
920 void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
921 void EmitIfStmt(const IfStmt &S);
922 void EmitWhileStmt(const WhileStmt &S);
923 void EmitDoStmt(const DoStmt &S);
924 void EmitForStmt(const ForStmt &S);
925 void EmitReturnStmt(const ReturnStmt &S);
926 void EmitDeclStmt(const DeclStmt &S);
927 void EmitBreakStmt(const BreakStmt &S);
928 void EmitContinueStmt(const ContinueStmt &S);
929 void EmitSwitchStmt(const SwitchStmt &S);
930 void EmitDefaultStmt(const DefaultStmt &S);
931 void EmitCaseStmt(const CaseStmt &S);
932 void EmitCaseStmtRange(const CaseStmt &S);
933 void EmitAsmStmt(const AsmStmt &S);
935 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
936 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
937 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
938 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
940 llvm::Constant *getUnwindResumeOrRethrowFn();
941 struct CXXTryStmtInfo {
942 llvm::BasicBlock *SavedLandingPad;
943 llvm::BasicBlock *HandlerBlock;
944 llvm::BasicBlock *FinallyBlock;
946 CXXTryStmtInfo EnterCXXTryStmt(const CXXTryStmt &S);
947 void ExitCXXTryStmt(const CXXTryStmt &S, CXXTryStmtInfo Info);
949 void EmitCXXTryStmt(const CXXTryStmt &S);
951 //===--------------------------------------------------------------------===//
952 // LValue Expression Emission
953 //===--------------------------------------------------------------------===//
955 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
956 RValue GetUndefRValue(QualType Ty);
958 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
959 /// and issue an ErrorUnsupported style diagnostic (using the
961 RValue EmitUnsupportedRValue(const Expr *E,
964 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
965 /// an ErrorUnsupported style diagnostic (using the provided Name).
966 LValue EmitUnsupportedLValue(const Expr *E,
969 /// EmitLValue - Emit code to compute a designator that specifies the location
970 /// of the expression.
972 /// This can return one of two things: a simple address or a bitfield
973 /// reference. In either case, the LLVM Value* in the LValue structure is
974 /// guaranteed to be an LLVM pointer type.
976 /// If this returns a bitfield reference, nothing about the pointee type of
977 /// the LLVM value is known: For example, it may not be a pointer to an
980 /// If this returns a normal address, and if the lvalue's C type is fixed
981 /// size, this method guarantees that the returned pointer type will point to
982 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
983 /// variable length type, this is not possible.
985 LValue EmitLValue(const Expr *E);
987 /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
988 /// checking code to guard against undefined behavior. This is only
989 /// suitable when we know that the address will be used to access the
991 LValue EmitCheckedLValue(const Expr *E);
993 /// EmitLoadOfScalar - Load a scalar value from an address, taking
994 /// care to appropriately convert from the memory representation to
995 /// the LLVM value representation.
996 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
999 /// EmitStoreOfScalar - Store a scalar value to an address, taking
1000 /// care to appropriately convert from the memory representation to
1001 /// the LLVM value representation.
1002 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1003 bool Volatile, QualType Ty);
1005 /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1006 /// this method emits the address of the lvalue, then loads the result as an
1007 /// rvalue, returning the rvalue.
1008 RValue EmitLoadOfLValue(LValue V, QualType LVType);
1009 RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1010 RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1011 RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1012 RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1015 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1016 /// lvalue, where both are guaranteed to the have the same type, and that type
1018 void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1019 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1021 void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1022 void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1024 /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1025 /// EmitStoreThroughLValue.
1027 /// \param Result [out] - If non-null, this will be set to a Value* for the
1028 /// bit-field contents after the store, appropriate for use as the result of
1029 /// an assignment to the bit-field.
1030 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1031 llvm::Value **Result=0);
1033 // Note: only availabe for agg return types
1034 LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1035 LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1036 // Note: only available for agg return types
1037 LValue EmitCallExprLValue(const CallExpr *E);
1038 // Note: only available for agg return types
1039 LValue EmitVAArgExprLValue(const VAArgExpr *E);
1040 LValue EmitDeclRefLValue(const DeclRefExpr *E);
1041 LValue EmitStringLiteralLValue(const StringLiteral *E);
1042 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1043 LValue EmitPredefinedFunctionName(unsigned Type);
1044 LValue EmitPredefinedLValue(const PredefinedExpr *E);
1045 LValue EmitUnaryOpLValue(const UnaryOperator *E);
1046 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1047 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1048 LValue EmitMemberExpr(const MemberExpr *E);
1049 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1050 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1051 LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1052 LValue EmitCastLValue(const CastExpr *E);
1053 LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1055 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1056 const ObjCIvarDecl *Ivar);
1057 LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1058 const FieldDecl* Field,
1059 unsigned CVRQualifiers);
1060 LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1061 unsigned CVRQualifiers);
1063 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1064 /// if the Field is a reference, this will return the address of the reference
1065 /// and not the address of the value stored in the reference.
1066 LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1067 const FieldDecl* Field,
1068 unsigned CVRQualifiers);
1070 LValue EmitLValueForIvar(QualType ObjectTy,
1071 llvm::Value* Base, const ObjCIvarDecl *Ivar,
1072 unsigned CVRQualifiers);
1074 LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1075 unsigned CVRQualifiers);
1077 LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1079 LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1080 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1081 LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1082 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1084 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1085 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1086 LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1087 LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1088 LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1089 LValue EmitStmtExprLValue(const StmtExpr *E);
1090 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1092 //===--------------------------------------------------------------------===//
1093 // Scalar Expression Emission
1094 //===--------------------------------------------------------------------===//
1096 /// EmitCall - Generate a call of the given function, expecting the given
1097 /// result type, and using the given argument list which specifies both the
1098 /// LLVM arguments and the types they were derived from.
1100 /// \param TargetDecl - If given, the decl of the function in a direct call;
1101 /// used to set attributes on the call (noreturn, etc.).
1102 RValue EmitCall(const CGFunctionInfo &FnInfo,
1103 llvm::Value *Callee,
1104 ReturnValueSlot ReturnValue,
1105 const CallArgList &Args,
1106 const Decl *TargetDecl = 0,
1107 llvm::Instruction **callOrInvoke = 0);
1109 RValue EmitCall(QualType FnType, llvm::Value *Callee,
1110 ReturnValueSlot ReturnValue,
1111 CallExpr::const_arg_iterator ArgBeg,
1112 CallExpr::const_arg_iterator ArgEnd,
1113 const Decl *TargetDecl = 0);
1114 RValue EmitCallExpr(const CallExpr *E,
1115 ReturnValueSlot ReturnValue = ReturnValueSlot());
1117 llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1118 const llvm::Type *Ty);
1119 llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1120 llvm::Value *&This, const llvm::Type *Ty);
1122 RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1123 llvm::Value *Callee,
1124 ReturnValueSlot ReturnValue,
1127 CallExpr::const_arg_iterator ArgBeg,
1128 CallExpr::const_arg_iterator ArgEnd);
1129 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1130 ReturnValueSlot ReturnValue);
1131 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1132 ReturnValueSlot ReturnValue);
1134 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1135 const CXXMethodDecl *MD,
1136 ReturnValueSlot ReturnValue);
1139 RValue EmitBuiltinExpr(const FunctionDecl *FD,
1140 unsigned BuiltinID, const CallExpr *E);
1142 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1144 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1145 /// is unhandled by the current target.
1146 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1148 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1149 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1150 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1152 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1153 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1154 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1155 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1156 ReturnValueSlot Return = ReturnValueSlot());
1157 RValue EmitObjCPropertyGet(const Expr *E,
1158 ReturnValueSlot Return = ReturnValueSlot());
1159 RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S,
1160 ReturnValueSlot Return = ReturnValueSlot());
1161 void EmitObjCPropertySet(const Expr *E, RValue Src);
1162 void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1165 /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1166 /// expression. Will emit a temporary variable if E is not an LValue.
1167 RValue EmitReferenceBindingToExpr(const Expr* E, bool IsInitializer = false);
1169 //===--------------------------------------------------------------------===//
1170 // Expression Emission
1171 //===--------------------------------------------------------------------===//
1173 // Expressions are broken into three classes: scalar, complex, aggregate.
1175 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1176 /// scalar type, returning the result.
1177 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1179 /// EmitScalarConversion - Emit a conversion from the specified type to the
1180 /// specified destination type, both of which are LLVM scalar types.
1181 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1184 /// EmitComplexToScalarConversion - Emit a conversion from the specified
1185 /// complex type to the specified destination type, where the destination type
1186 /// is an LLVM scalar type.
1187 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1191 /// EmitAggExpr - Emit the computation of the specified expression of
1192 /// aggregate type. The result is computed into DestPtr. Note that if
1193 /// DestPtr is null, the value of the aggregate expression is not needed.
1194 void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1195 bool IgnoreResult = false, bool IsInitializer = false,
1196 bool RequiresGCollection = false);
1198 /// EmitAggExprToLValue - Emit the computation of the specified expression of
1199 /// aggregate type into a temporary LValue.
1200 LValue EmitAggExprToLValue(const Expr *E);
1202 /// EmitGCMemmoveCollectable - Emit special API for structs with object
1204 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1207 /// EmitComplexExpr - Emit the computation of the specified expression of
1208 /// complex type, returning the result.
1209 ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1210 bool IgnoreImag = false,
1211 bool IgnoreRealAssign = false,
1212 bool IgnoreImagAssign = false);
1214 /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1215 /// of complex type, storing into the specified Value*.
1216 void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1217 bool DestIsVolatile);
1219 /// StoreComplexToAddr - Store a complex number into the specified address.
1220 void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1221 bool DestIsVolatile);
1222 /// LoadComplexFromAddr - Load a complex number from the specified address.
1223 ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1225 /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1226 /// static block var decl.
1227 llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1228 const char *Separator,
1229 llvm::GlobalValue::LinkageTypes Linkage);
1231 /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1232 /// global variable that has already been created for it. If the initializer
1233 /// has a different type than GV does, this may free GV and return a different
1234 /// one. Otherwise it just returns GV.
1235 llvm::GlobalVariable *
1236 AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1237 llvm::GlobalVariable *GV);
1240 /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1241 /// initialized static block var decl.
1242 void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1243 llvm::GlobalVariable *GV);
1245 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1246 /// variable with global storage.
1247 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1249 /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1250 /// with the C++ runtime so that its destructor will be called at exit.
1251 void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1252 llvm::Constant *DeclPtr);
1254 /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1256 void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1257 llvm::Constant **Decls,
1260 /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1262 void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1263 const std::vector<std::pair<llvm::Constant*,
1264 llvm::Constant*> > &DtorsAndObjects);
1266 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1268 void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1270 RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1271 llvm::Value *AggLoc = 0,
1272 bool IsAggLocVolatile = false,
1273 bool IsInitializer = false);
1275 void EmitCXXThrowExpr(const CXXThrowExpr *E);
1277 //===--------------------------------------------------------------------===//
1279 //===--------------------------------------------------------------------===//
1281 /// ContainsLabel - Return true if the statement contains a label in it. If
1282 /// this statement is not executed normally, it not containing a label means
1283 /// that we can just remove the code.
1284 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1286 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1287 /// to a constant, or if it does but contains a label, return 0. If it
1288 /// constant folds to 'true' and does not contain a label, return 1, if it
1289 /// constant folds to 'false' and does not contain a label, return -1.
1290 int ConstantFoldsToSimpleInteger(const Expr *Cond);
1292 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1293 /// if statement) to the specified blocks. Based on the condition, this might
1294 /// try to simplify the codegen of the conditional based on the branch.
1295 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1296 llvm::BasicBlock *FalseBlock);
1298 /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll
1299 /// generate a branch around the created basic block as necessary.
1300 llvm::BasicBlock* getTrapBB();
1302 /// EmitCallArg - Emit a single call argument.
1303 RValue EmitCallArg(const Expr *E, QualType ArgType);
1305 /// EmitDelegateCallArg - We are performing a delegate call; that
1306 /// is, the current function is delegating to another one. Produce
1307 /// a r-value suitable for passing the given parameter.
1308 RValue EmitDelegateCallArg(const VarDecl *Param);
1312 void EmitReturnOfRValue(RValue RV, QualType Ty);
1314 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1315 /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1317 /// \param AI - The first function argument of the expansion.
1318 /// \return The argument following the last expanded function
1320 llvm::Function::arg_iterator
1321 ExpandTypeFromArgs(QualType Ty, LValue Dst,
1322 llvm::Function::arg_iterator AI);
1324 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1325 /// Ty, into individual arguments on the provided vector \arg Args. See
1326 /// ABIArgInfo::Expand.
1327 void ExpandTypeToArgs(QualType Ty, RValue Src,
1328 llvm::SmallVector<llvm::Value*, 16> &Args);
1330 llvm::Value* EmitAsmInput(const AsmStmt &S,
1331 const TargetInfo::ConstraintInfo &Info,
1332 const Expr *InputExpr, std::string &ConstraintStr);
1334 /// EmitCleanupBlock - emits a single cleanup block.
1335 void EmitCleanupBlock();
1337 /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1338 /// current cleanup scope.
1339 void AddBranchFixup(llvm::BranchInst *BI);
1341 /// EmitCallArgs - Emit call arguments for a function.
1342 /// The CallArgTypeInfo parameter is used for iterating over the known
1343 /// argument types of the function being called.
1344 template<typename T>
1345 void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1346 CallExpr::const_arg_iterator ArgBeg,
1347 CallExpr::const_arg_iterator ArgEnd) {
1348 CallExpr::const_arg_iterator Arg = ArgBeg;
1350 // First, use the argument types that the type info knows about
1351 if (CallArgTypeInfo) {
1352 for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1353 E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1354 assert(Arg != ArgEnd && "Running over edge of argument list!");
1355 QualType ArgType = *I;
1357 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1359 getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1360 "type mismatch in call argument!");
1362 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1366 // Either we've emitted all the call args, or we have a call to a
1367 // variadic function.
1368 assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1369 "Extra arguments in non-variadic function!");
1373 // If we still have any arguments, emit them using the type of the argument.
1374 for (; Arg != ArgEnd; ++Arg) {
1375 QualType ArgType = Arg->getType();
1376 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1381 const TargetCodeGenInfo &getTargetHooks() const {
1382 return CGM.getTargetCodeGenInfo();
1387 } // end namespace CodeGen
1388 } // end namespace clang