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.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef CLANG_CODEGEN_CODEGENFUNCTION_H
15 #define CLANG_CODEGEN_CODEGENFUNCTION_H
16 
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"
26 #include "CGBlocks.h"
27 #include "CGBuilder.h"
28 #include "CGCall.h"
29 #include "CGCXX.h"
30 #include "CGValue.h"
31 
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 }
41 
42 namespace clang {
43   class ASTContext;
44   class CXXDestructorDecl;
45   class CXXTryStmt;
46   class Decl;
47   class EnumConstantDecl;
48   class FunctionDecl;
49   class FunctionProtoType;
50   class LabelStmt;
51   class ObjCContainerDecl;
52   class ObjCInterfaceDecl;
53   class ObjCIvarDecl;
54   class ObjCMethodDecl;
55   class ObjCImplementationDecl;
56   class ObjCPropertyImplDecl;
57   class TargetInfo;
58   class TargetCodeGenInfo;
59   class VarDecl;
60   class ObjCForCollectionStmt;
61   class ObjCAtTryStmt;
62   class ObjCAtThrowStmt;
63   class ObjCAtSynchronizedStmt;
64 
65 namespace CodeGen {
66   class CodeGenTypes;
67   class CGDebugInfo;
68   class CGFunctionInfo;
69   class CGRecordLayout;
70   class CGBlockInfo;
71 
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
77 public:
78   CodeGenModule &CGM;  // Per-module state.
79   const TargetInfo &Target;
80 
81   typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
82   CGBuilderTy Builder;
83 
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;
90   QualType FnRetTy;
91   llvm::Function *CurFn;
92 
93   /// CurGD - The GlobalDecl for the current function being compiled.
94   GlobalDecl CurGD;
95 
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;
101 
102   /// AllocaInsertPoint - This is an instruction in the entry block before which
103   /// we prefer to insert allocas.
104   llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
105 
106   // intptr_t, i32, i64
107   const llvm::IntegerType *IntPtrTy, *Int32Ty, *Int64Ty;
108   uint32_t LLVMPointerWidth;
109 
110   bool Exceptions;
111   bool CatchUndefined;
112 
113   /// \brief A mapping from NRVO variables to the flags used to indicate
114   /// when the NRVO has been applied to this variable.
115   llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
116 
117 public:
118   /// ObjCEHValueStack - Stack of Objective-C exception values, used for
119   /// rethrows.
120   llvm::SmallVector<llvm::Value*, 8> ObjCEHValueStack;
121 
122   /// PushCleanupBlock - Push a new cleanup entry on the stack and set the
123   /// passed in block as the cleanup block.
124   void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock,
125                         llvm::BasicBlock *CleanupExitBlock,
126                         llvm::BasicBlock *PreviousInvokeDest,
127                         bool EHOnly = false);
128   void PushCleanupBlock(llvm::BasicBlock *CleanupEntryBlock) {
129     PushCleanupBlock(CleanupEntryBlock, 0, getInvokeDest(), false);
130   }
131 
132   /// CleanupBlockInfo - A struct representing a popped cleanup block.
133   struct CleanupBlockInfo {
134     /// CleanupEntryBlock - the cleanup entry block
135     llvm::BasicBlock *CleanupBlock;
136 
137     /// SwitchBlock - the block (if any) containing the switch instruction used
138     /// for jumping to the final destination.
139     llvm::BasicBlock *SwitchBlock;
140 
141     /// EndBlock - the default destination for the switch instruction.
142     llvm::BasicBlock *EndBlock;
143 
144     /// EHOnly - True iff this cleanup should only be performed on the
145     /// exceptional edge.
146     bool EHOnly;
147 
148     CleanupBlockInfo(llvm::BasicBlock *cb, llvm::BasicBlock *sb,
149                      llvm::BasicBlock *eb, bool ehonly = false)
150       : CleanupBlock(cb), SwitchBlock(sb), EndBlock(eb), EHOnly(ehonly) {}
151   };
152 
153   /// EHCleanupBlock - RAII object that will create a cleanup block for the
154   /// exceptional edge and set the insert point to that block.  When destroyed,
155   /// it creates the cleanup edge and sets the insert point to the previous
156   /// block.
157   class EHCleanupBlock {
158     CodeGenFunction& CGF;
159     llvm::BasicBlock *PreviousInsertionBlock;
160     llvm::BasicBlock *CleanupHandler;
161     llvm::BasicBlock *PreviousInvokeDest;
162   public:
163     EHCleanupBlock(CodeGenFunction &cgf)
164       : CGF(cgf),
165         PreviousInsertionBlock(CGF.Builder.GetInsertBlock()),
166         CleanupHandler(CGF.createBasicBlock("ehcleanup", CGF.CurFn)),
167         PreviousInvokeDest(CGF.getInvokeDest()) {
168       llvm::BasicBlock *TerminateHandler = CGF.getTerminateHandler();
169       CGF.Builder.SetInsertPoint(CleanupHandler);
170       CGF.setInvokeDest(TerminateHandler);
171     }
172     ~EHCleanupBlock();
173   };
174 
175   /// PopCleanupBlock - Will pop the cleanup entry on the stack, process all
176   /// branch fixups and return a block info struct with the switch block and end
177   /// block.  This will also reset the invoke handler to the previous value
178   /// from when the cleanup block was created.
179   CleanupBlockInfo PopCleanupBlock();
180 
181   /// DelayedCleanupBlock - RAII object that will create a cleanup block and set
182   /// the insert point to that block. When destructed, it sets the insert point
183   /// to the previous block and pushes a new cleanup entry on the stack.
184   class DelayedCleanupBlock {
185     CodeGenFunction& CGF;
186     llvm::BasicBlock *CurBB;
187     llvm::BasicBlock *CleanupEntryBB;
188     llvm::BasicBlock *CleanupExitBB;
189     llvm::BasicBlock *CurInvokeDest;
190     bool EHOnly;
191 
192   public:
193     DelayedCleanupBlock(CodeGenFunction &cgf, bool ehonly = false)
194       : CGF(cgf), CurBB(CGF.Builder.GetInsertBlock()),
195         CleanupEntryBB(CGF.createBasicBlock("cleanup")),
196         CleanupExitBB(0),
197         CurInvokeDest(CGF.getInvokeDest()),
198         EHOnly(ehonly) {
199       CGF.Builder.SetInsertPoint(CleanupEntryBB);
200     }
201 
202     llvm::BasicBlock *getCleanupExitBlock() {
203       if (!CleanupExitBB)
204         CleanupExitBB = CGF.createBasicBlock("cleanup.exit");
205       return CleanupExitBB;
206     }
207 
208     ~DelayedCleanupBlock() {
209       CGF.PushCleanupBlock(CleanupEntryBB, CleanupExitBB, CurInvokeDest,
210                            EHOnly);
211       // FIXME: This is silly, move this into the builder.
212       if (CurBB)
213         CGF.Builder.SetInsertPoint(CurBB);
214       else
215         CGF.Builder.ClearInsertionPoint();
216     }
217   };
218 
219   /// \brief Enters a new scope for capturing cleanups, all of which will be
220   /// executed once the scope is exited.
221   class CleanupScope {
222     CodeGenFunction& CGF;
223     size_t CleanupStackDepth;
224     bool OldDidCallStackSave;
225     bool PerformCleanup;
226 
227     CleanupScope(const CleanupScope &); // DO NOT IMPLEMENT
228     CleanupScope &operator=(const CleanupScope &); // DO NOT IMPLEMENT
229 
230   public:
231     /// \brief Enter a new cleanup scope.
232     explicit CleanupScope(CodeGenFunction &CGF)
233       : CGF(CGF), PerformCleanup(true)
234     {
235       CleanupStackDepth = CGF.CleanupEntries.size();
236       OldDidCallStackSave = CGF.DidCallStackSave;
237     }
238 
239     /// \brief Exit this cleanup scope, emitting any accumulated
240     /// cleanups.
241     ~CleanupScope() {
242       if (PerformCleanup) {
243         CGF.DidCallStackSave = OldDidCallStackSave;
244         CGF.EmitCleanupBlocks(CleanupStackDepth);
245       }
246     }
247 
248     /// \brief Determine whether this scope requires any cleanups.
249     bool requiresCleanups() const {
250       return CGF.CleanupEntries.size() > CleanupStackDepth;
251     }
252 
253     /// \brief Force the emission of cleanups now, instead of waiting
254     /// until this object is destroyed.
255     void ForceCleanup() {
256       assert(PerformCleanup && "Already forced cleanup");
257       CGF.DidCallStackSave = OldDidCallStackSave;
258       CGF.EmitCleanupBlocks(CleanupStackDepth);
259       PerformCleanup = false;
260     }
261   };
262 
263   /// CXXTemporariesCleanupScope - Enters a new scope for catching live
264   /// temporaries, all of which will be popped once the scope is exited.
265   class CXXTemporariesCleanupScope {
266     CodeGenFunction &CGF;
267     size_t NumLiveTemporaries;
268 
269     // DO NOT IMPLEMENT
270     CXXTemporariesCleanupScope(const CXXTemporariesCleanupScope &);
271     CXXTemporariesCleanupScope &operator=(const CXXTemporariesCleanupScope &);
272 
273   public:
274     explicit CXXTemporariesCleanupScope(CodeGenFunction &CGF)
275       : CGF(CGF), NumLiveTemporaries(CGF.LiveTemporaries.size()) { }
276 
277     ~CXXTemporariesCleanupScope() {
278       while (CGF.LiveTemporaries.size() > NumLiveTemporaries)
279         CGF.PopCXXTemporary();
280     }
281   };
282 
283 
284   /// EmitCleanupBlocks - Takes the old cleanup stack size and emits the cleanup
285   /// blocks that have been added.
286   void EmitCleanupBlocks(size_t OldCleanupStackSize);
287 
288   /// EmitBranchThroughCleanup - Emit a branch from the current insert block
289   /// through the cleanup handling code (if any) and then on to \arg Dest.
290   ///
291   /// FIXME: Maybe this should really be in EmitBranch? Don't we always want
292   /// this behavior for branches?
293   void EmitBranchThroughCleanup(llvm::BasicBlock *Dest);
294 
295   /// BeginConditionalBranch - Should be called before a conditional part of an
296   /// expression is emitted. For example, before the RHS of the expression below
297   /// is emitted:
298   ///
299   /// b && f(T());
300   ///
301   /// This is used to make sure that any temporaries created in the conditional
302   /// branch are only destroyed if the branch is taken.
303   void BeginConditionalBranch() {
304     ++ConditionalBranchLevel;
305   }
306 
307   /// EndConditionalBranch - Should be called after a conditional part of an
308   /// expression has been emitted.
309   void EndConditionalBranch() {
310     assert(ConditionalBranchLevel != 0 &&
311            "Conditional branch mismatch!");
312 
313     --ConditionalBranchLevel;
314   }
315 
316 private:
317   CGDebugInfo *DebugInfo;
318 
319   /// IndirectBranch - The first time an indirect goto is seen we create a block
320   /// with an indirect branch.  Every time we see the address of a label taken,
321   /// we add the label to the indirect goto.  Every subsequent indirect goto is
322   /// codegen'd as a jump to the IndirectBranch's basic block.
323   llvm::IndirectBrInst *IndirectBranch;
324 
325   /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
326   /// decls.
327   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
328 
329   /// LabelMap - This keeps track of the LLVM basic block for each C label.
330   llvm::DenseMap<const LabelStmt*, llvm::BasicBlock*> LabelMap;
331 
332   // BreakContinueStack - This keeps track of where break and continue
333   // statements should jump to.
334   struct BreakContinue {
335     BreakContinue(llvm::BasicBlock *bb, llvm::BasicBlock *cb)
336       : BreakBlock(bb), ContinueBlock(cb) {}
337 
338     llvm::BasicBlock *BreakBlock;
339     llvm::BasicBlock *ContinueBlock;
340   };
341   llvm::SmallVector<BreakContinue, 8> BreakContinueStack;
342 
343   /// SwitchInsn - This is nearest current switch instruction. It is null if if
344   /// current context is not in a switch.
345   llvm::SwitchInst *SwitchInsn;
346 
347   /// CaseRangeBlock - This block holds if condition check for last case
348   /// statement range in current switch instruction.
349   llvm::BasicBlock *CaseRangeBlock;
350 
351   /// InvokeDest - This is the nearest exception target for calls
352   /// which can unwind, when exceptions are being used.
353   llvm::BasicBlock *InvokeDest;
354 
355   // VLASizeMap - This keeps track of the associated size for each VLA type.
356   // We track this by the size expression rather than the type itself because
357   // in certain situations, like a const qualifier applied to an VLA typedef,
358   // multiple VLA types can share the same size expression.
359   // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
360   // enter/leave scopes.
361   llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
362 
363   /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
364   /// calling llvm.stacksave for multiple VLAs in the same scope.
365   bool DidCallStackSave;
366 
367   struct CleanupEntry {
368     /// CleanupEntryBlock - The block of code that does the actual cleanup.
369     llvm::BasicBlock *CleanupEntryBlock;
370 
371     /// CleanupExitBlock - The cleanup exit block.
372     llvm::BasicBlock *CleanupExitBlock;
373 
374     /// Blocks - Basic blocks that were emitted in the current cleanup scope.
375     std::vector<llvm::BasicBlock *> Blocks;
376 
377     /// BranchFixups - Branch instructions to basic blocks that haven't been
378     /// inserted into the current function yet.
379     std::vector<llvm::BranchInst *> BranchFixups;
380 
381     /// PreviousInvokeDest - The invoke handler from the start of the cleanup
382     /// region.
383     llvm::BasicBlock *PreviousInvokeDest;
384 
385     /// EHOnly - Perform this only on the exceptional edge, not the main edge.
386     bool EHOnly;
387 
388     explicit CleanupEntry(llvm::BasicBlock *CleanupEntryBlock,
389                           llvm::BasicBlock *CleanupExitBlock,
390                           llvm::BasicBlock *PreviousInvokeDest,
391                           bool ehonly)
392       : CleanupEntryBlock(CleanupEntryBlock),
393         CleanupExitBlock(CleanupExitBlock),
394         PreviousInvokeDest(PreviousInvokeDest),
395         EHOnly(ehonly) {}
396   };
397 
398   /// CleanupEntries - Stack of cleanup entries.
399   llvm::SmallVector<CleanupEntry, 8> CleanupEntries;
400 
401   typedef llvm::DenseMap<llvm::BasicBlock*, size_t> BlockScopeMap;
402 
403   /// BlockScopes - Map of which "cleanup scope" scope basic blocks have.
404   BlockScopeMap BlockScopes;
405 
406   /// CXXThisDecl - When generating code for a C++ member function,
407   /// this will hold the implicit 'this' declaration.
408   ImplicitParamDecl *CXXThisDecl;
409   llvm::Value *CXXThisValue;
410 
411   /// CXXVTTDecl - When generating code for a base object constructor or
412   /// base object destructor with virtual bases, this will hold the implicit
413   /// VTT parameter.
414   ImplicitParamDecl *CXXVTTDecl;
415   llvm::Value *CXXVTTValue;
416 
417   /// CXXLiveTemporaryInfo - Holds information about a live C++ temporary.
418   struct CXXLiveTemporaryInfo {
419     /// Temporary - The live temporary.
420     const CXXTemporary *Temporary;
421 
422     /// ThisPtr - The pointer to the temporary.
423     llvm::Value *ThisPtr;
424 
425     /// DtorBlock - The destructor block.
426     llvm::BasicBlock *DtorBlock;
427 
428     /// CondPtr - If this is a conditional temporary, this is the pointer to the
429     /// condition variable that states whether the destructor should be called
430     /// or not.
431     llvm::Value *CondPtr;
432 
433     CXXLiveTemporaryInfo(const CXXTemporary *temporary,
434                          llvm::Value *thisptr, llvm::BasicBlock *dtorblock,
435                          llvm::Value *condptr)
436       : Temporary(temporary), ThisPtr(thisptr), DtorBlock(dtorblock),
437       CondPtr(condptr) { }
438   };
439 
440   llvm::SmallVector<CXXLiveTemporaryInfo, 4> LiveTemporaries;
441 
442   /// ConditionalBranchLevel - Contains the nesting level of the current
443   /// conditional branch. This is used so that we know if a temporary should be
444   /// destroyed conditionally.
445   unsigned ConditionalBranchLevel;
446 
447 
448   /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
449   /// type as well as the field number that contains the actual data.
450   llvm::DenseMap<const ValueDecl *, std::pair<const llvm::Type *,
451                                               unsigned> > ByRefValueInfo;
452 
453   /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
454   /// number that holds the value.
455   unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
456 
457   llvm::BasicBlock *TerminateHandler;
458   llvm::BasicBlock *TrapBB;
459 
460 public:
461   CodeGenFunction(CodeGenModule &cgm);
462 
463   ASTContext &getContext() const;
464   CGDebugInfo *getDebugInfo() { return DebugInfo; }
465 
466   llvm::BasicBlock *getInvokeDest() { return InvokeDest; }
467   void setInvokeDest(llvm::BasicBlock *B) { InvokeDest = B; }
468 
469   llvm::LLVMContext &getLLVMContext() { return VMContext; }
470 
471   //===--------------------------------------------------------------------===//
472   //                                  Objective-C
473   //===--------------------------------------------------------------------===//
474 
475   void GenerateObjCMethod(const ObjCMethodDecl *OMD);
476 
477   void StartObjCMethod(const ObjCMethodDecl *MD,
478                        const ObjCContainerDecl *CD);
479 
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);
485 
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);
492 
493   //===--------------------------------------------------------------------===//
494   //                                  Block Bits
495   //===--------------------------------------------------------------------===//
496 
497   llvm::Value *BuildBlockLiteralTmp(const BlockExpr *);
498   llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
499                                            bool BlockHasCopyDispose,
500                                            CharUnits Size,
501                                            const llvm::StructType *,
502                                            std::vector<HelperInfo> *);
503 
504   llvm::Function *GenerateBlockFunction(GlobalDecl GD,
505                                         const BlockExpr *BExpr,
506                                         CGBlockInfo &Info,
507                                         const Decl *OuterFuncDecl,
508                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm);
509 
510   llvm::Value *LoadBlockStruct();
511 
512   void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
513   void AllocateBlockDecl(const BlockDeclRefExpr *E);
514   llvm::Value *GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
515     return GetAddrOfBlockDecl(E->getDecl(), E->isByRef());
516   }
517   llvm::Value *GetAddrOfBlockDecl(const ValueDecl *D, bool ByRef);
518   const llvm::Type *BuildByRefType(const ValueDecl *D);
519 
520   void GenerateCode(GlobalDecl GD, llvm::Function *Fn);
521   void StartFunction(GlobalDecl GD, QualType RetTy,
522                      llvm::Function *Fn,
523                      const FunctionArgList &Args,
524                      SourceLocation StartLoc);
525 
526   void EmitConstructorBody(FunctionArgList &Args);
527   void EmitDestructorBody(FunctionArgList &Args);
528   void EmitFunctionBody(FunctionArgList &Args);
529 
530   /// EmitReturnBlock - Emit the unified return block, trying to avoid its
531   /// emission when possible.
532   void EmitReturnBlock();
533 
534   /// FinishFunction - Complete IR generation of the current function. It is
535   /// legal to call this function even if there is no current insertion point.
536   void FinishFunction(SourceLocation EndLoc=SourceLocation());
537 
538   /// GenerateThunk - Generate a thunk for the given method.
539   void GenerateThunk(llvm::Function *Fn, GlobalDecl GD, const ThunkInfo &Thunk);
540 
541   void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
542                         FunctionArgList &Args);
543 
544   /// InitializeVTablePointer - Initialize the vtable pointer of the given
545   /// subobject.
546   ///
547   void InitializeVTablePointer(BaseSubobject Base,
548                                const CXXRecordDecl *NearestVBase,
549                                uint64_t OffsetFromNearestVBase,
550                                llvm::Constant *VTable,
551                                const CXXRecordDecl *VTableClass);
552 
553   typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
554   void InitializeVTablePointers(BaseSubobject Base,
555                                 const CXXRecordDecl *NearestVBase,
556                                 uint64_t OffsetFromNearestVBase,
557                                 bool BaseIsNonVirtualPrimaryBase,
558                                 llvm::Constant *VTable,
559                                 const CXXRecordDecl *VTableClass,
560                                 VisitedVirtualBasesSetTy& VBases);
561 
562   void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
563 
564 
565   /// EmitDtorEpilogue - Emit all code that comes at the end of class's
566   /// destructor. This is to call destructors on members and base classes in
567   /// reverse order of their construction.
568   void EmitDtorEpilogue(const CXXDestructorDecl *Dtor,
569                         CXXDtorType Type);
570 
571   /// ShouldInstrumentFunction - Return true if the current function should be
572   /// instrumented with __cyg_profile_func_* calls
573   bool ShouldInstrumentFunction();
574 
575   /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
576   /// instrumentation function with the current function and the call site, if
577   /// function instrumentation is enabled.
578   void EmitFunctionInstrumentation(const char *Fn);
579 
580   /// EmitFunctionProlog - Emit the target specific LLVM code to load the
581   /// arguments for the given function. This is also responsible for naming the
582   /// LLVM function arguments.
583   void EmitFunctionProlog(const CGFunctionInfo &FI,
584                           llvm::Function *Fn,
585                           const FunctionArgList &Args);
586 
587   /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
588   /// given temporary.
589   void EmitFunctionEpilog(const CGFunctionInfo &FI);
590 
591   /// EmitStartEHSpec - Emit the start of the exception spec.
592   void EmitStartEHSpec(const Decl *D);
593 
594   /// EmitEndEHSpec - Emit the end of the exception spec.
595   void EmitEndEHSpec(const Decl *D);
596 
597   /// getTerminateHandler - Return a handler that just calls terminate.
598   llvm::BasicBlock *getTerminateHandler();
599 
600   const llvm::Type *ConvertTypeForMem(QualType T);
601   const llvm::Type *ConvertType(QualType T);
602   const llvm::Type *ConvertType(const TypeDecl *T) {
603     return ConvertType(getContext().getTypeDeclType(T));
604   }
605 
606   /// LoadObjCSelf - Load the value of self. This function is only valid while
607   /// generating code for an Objective-C method.
608   llvm::Value *LoadObjCSelf();
609 
610   /// TypeOfSelfObject - Return type of object that this self represents.
611   QualType TypeOfSelfObject();
612 
613   /// hasAggregateLLVMType - Return true if the specified AST type will map into
614   /// an aggregate LLVM type or is void.
615   static bool hasAggregateLLVMType(QualType T);
616 
617   /// createBasicBlock - Create an LLVM basic block.
618   llvm::BasicBlock *createBasicBlock(const char *Name="",
619                                      llvm::Function *Parent=0,
620                                      llvm::BasicBlock *InsertBefore=0) {
621 #ifdef NDEBUG
622     return llvm::BasicBlock::Create(VMContext, "", Parent, InsertBefore);
623 #else
624     return llvm::BasicBlock::Create(VMContext, Name, Parent, InsertBefore);
625 #endif
626   }
627 
628   /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
629   /// label maps to.
630   llvm::BasicBlock *getBasicBlockForLabel(const LabelStmt *S);
631 
632   /// SimplifyForwardingBlocks - If the given basic block is only a branch to
633   /// another basic block, simplify it. This assumes that no other code could
634   /// potentially reference the basic block.
635   void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
636 
637   /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
638   /// adding a fall-through branch from the current insert block if
639   /// necessary. It is legal to call this function even if there is no current
640   /// insertion point.
641   ///
642   /// IsFinished - If true, indicates that the caller has finished emitting
643   /// branches to the given block and does not expect to emit code into it. This
644   /// means the block can be ignored if it is unreachable.
645   void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
646 
647   /// EmitBranch - Emit a branch to the specified basic block from the current
648   /// insert block, taking care to avoid creation of branches from dummy
649   /// blocks. It is legal to call this function even if there is no current
650   /// insertion point.
651   ///
652   /// This function clears the current insertion point. The caller should follow
653   /// calls to this function with calls to Emit*Block prior to generation new
654   /// code.
655   void EmitBranch(llvm::BasicBlock *Block);
656 
657   /// HaveInsertPoint - True if an insertion point is defined. If not, this
658   /// indicates that the current code being emitted is unreachable.
659   bool HaveInsertPoint() const {
660     return Builder.GetInsertBlock() != 0;
661   }
662 
663   /// EnsureInsertPoint - Ensure that an insertion point is defined so that
664   /// emitted IR has a place to go. Note that by definition, if this function
665   /// creates a block then that block is unreachable; callers may do better to
666   /// detect when no insertion point is defined and simply skip IR generation.
667   void EnsureInsertPoint() {
668     if (!HaveInsertPoint())
669       EmitBlock(createBasicBlock());
670   }
671 
672   /// ErrorUnsupported - Print out an error that codegen doesn't support the
673   /// specified stmt yet.
674   void ErrorUnsupported(const Stmt *S, const char *Type,
675                         bool OmitOnError=false);
676 
677   //===--------------------------------------------------------------------===//
678   //                                  Helpers
679   //===--------------------------------------------------------------------===//
680 
681   Qualifiers MakeQualifiers(QualType T) {
682     Qualifiers Quals = getContext().getCanonicalType(T).getQualifiers();
683     Quals.setObjCGCAttr(getContext().getObjCGCAttrKind(T));
684     return Quals;
685   }
686 
687   /// CreateTempAlloca - This creates a alloca and inserts it into the entry
688   /// block. The caller is responsible for setting an appropriate alignment on
689   /// the alloca.
690   llvm::AllocaInst *CreateTempAlloca(const llvm::Type *Ty,
691                                      const llvm::Twine &Name = "tmp");
692 
693   /// InitTempAlloca - Provide an initial value for the given alloca.
694   void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
695 
696   /// CreateIRTemp - Create a temporary IR object of the given type, with
697   /// appropriate alignment. This routine should only be used when an temporary
698   /// value needs to be stored into an alloca (for example, to avoid explicit
699   /// PHI construction), but the type is the IR type, not the type appropriate
700   /// for storing in memory.
701   llvm::Value *CreateIRTemp(QualType T, const llvm::Twine &Name = "tmp");
702 
703   /// CreateMemTemp - Create a temporary memory object of the given type, with
704   /// appropriate alignment.
705   llvm::Value *CreateMemTemp(QualType T, const llvm::Twine &Name = "tmp");
706 
707   /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
708   /// expression and compare the result against zero, returning an Int1Ty value.
709   llvm::Value *EvaluateExprAsBool(const Expr *E);
710 
711   /// EmitAnyExpr - Emit code to compute the specified expression which can have
712   /// any type.  The result is returned as an RValue struct.  If this is an
713   /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
714   /// the result should be returned.
715   ///
716   /// \param IgnoreResult - True if the resulting value isn't used.
717   RValue EmitAnyExpr(const Expr *E, llvm::Value *AggLoc = 0,
718                      bool IsAggLocVolatile = false, bool IgnoreResult = false,
719                      bool IsInitializer = false);
720 
721   // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
722   // or the value of the expression, depending on how va_list is defined.
723   llvm::Value *EmitVAListRef(const Expr *E);
724 
725   /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
726   /// always be accessible even if no aggregate location is provided.
727   RValue EmitAnyExprToTemp(const Expr *E, bool IsAggLocVolatile = false,
728                            bool IsInitializer = false);
729 
730   /// EmitsAnyExprToMem - Emits the code necessary to evaluate an
731   /// arbitrary expression into the given memory location.
732   void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
733                         bool IsLocationVolatile = false,
734                         bool IsInitializer = false);
735 
736   /// EmitAggregateCopy - Emit an aggrate copy.
737   ///
738   /// \param isVolatile - True iff either the source or the destination is
739   /// volatile.
740   void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
741                          QualType EltTy, bool isVolatile=false);
742 
743   /// StartBlock - Start new block named N. If insert block is a dummy block
744   /// then reuse it.
745   void StartBlock(const char *N);
746 
747   /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
748   llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD);
749 
750   /// GetAddrOfLocalVar - Return the address of a local variable.
751   llvm::Value *GetAddrOfLocalVar(const VarDecl *VD);
752 
753   /// getAccessedFieldNo - Given an encoded value and a result number, return
754   /// the input field number being accessed.
755   static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
756 
757   llvm::BlockAddress *GetAddrOfLabel(const LabelStmt *L);
758   llvm::BasicBlock *GetIndirectGotoBlock();
759 
760   /// EmitNullInitialization - Generate code to set a value of the given type to
761   /// null, If the type contains data member pointers, they will be initialized
762   /// to -1 in accordance with the Itanium C++ ABI.
763   void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
764 
765   // EmitVAArg - Generate code to get an argument from the passed in pointer
766   // and update it accordingly. The return value is a pointer to the argument.
767   // FIXME: We should be able to get rid of this method and use the va_arg
768   // instruction in LLVM instead once it works well enough.
769   llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
770 
771   /// EmitVLASize - Generate code for any VLA size expressions that might occur
772   /// in a variably modified type. If Ty is a VLA, will return the value that
773   /// corresponds to the size in bytes of the VLA type. Will return 0 otherwise.
774   ///
775   /// This function can be called with a null (unreachable) insert point.
776   llvm::Value *EmitVLASize(QualType Ty);
777 
778   // GetVLASize - Returns an LLVM value that corresponds to the size in bytes
779   // of a variable length array type.
780   llvm::Value *GetVLASize(const VariableArrayType *);
781 
782   /// LoadCXXThis - Load the value of 'this'. This function is only valid while
783   /// generating code for an C++ member function.
784   llvm::Value *LoadCXXThis() {
785     assert(CXXThisValue && "no 'this' value for this function");
786     return CXXThisValue;
787   }
788 
789   /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
790   /// virtual bases.
791   llvm::Value *LoadCXXVTT() {
792     assert(CXXVTTValue && "no VTT value for this function");
793     return CXXVTTValue;
794   }
795 
796   /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
797   /// complete class to the given direct base.
798   llvm::Value *
799   GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
800                                         const CXXRecordDecl *Derived,
801                                         const CXXRecordDecl *Base,
802                                         bool BaseIsVirtual);
803 
804   /// GetAddressOfBaseClass - This function will add the necessary delta to the
805   /// load of 'this' and returns address of the base class.
806   llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
807                                      const CXXRecordDecl *Derived,
808                                      const CXXBaseSpecifierArray &BasePath,
809                                      bool NullCheckValue);
810 
811   llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
812                                         const CXXRecordDecl *Derived,
813                                         const CXXBaseSpecifierArray &BasePath,
814                                         bool NullCheckValue);
815 
816   llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
817                                          const CXXRecordDecl *ClassDecl,
818                                          const CXXRecordDecl *BaseClassDecl);
819 
820   void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
821                                       CXXCtorType CtorType,
822                                       const FunctionArgList &Args);
823   void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
824                               bool ForVirtualBase, llvm::Value *This,
825                               CallExpr::const_arg_iterator ArgBeg,
826                               CallExpr::const_arg_iterator ArgEnd);
827 
828   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
829                                   const ConstantArrayType *ArrayTy,
830                                   llvm::Value *ArrayPtr,
831                                   CallExpr::const_arg_iterator ArgBeg,
832                                   CallExpr::const_arg_iterator ArgEnd);
833 
834   void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
835                                   llvm::Value *NumElements,
836                                   llvm::Value *ArrayPtr,
837                                   CallExpr::const_arg_iterator ArgBeg,
838                                   CallExpr::const_arg_iterator ArgEnd);
839 
840   void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
841                                  const ArrayType *Array,
842                                  llvm::Value *This);
843 
844   void EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
845                                  llvm::Value *NumElements,
846                                  llvm::Value *This);
847 
848   llvm::Function *GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D,
849                                                   const ArrayType *Array,
850                                                   llvm::Value *This);
851 
852   void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
853                              bool ForVirtualBase, llvm::Value *This);
854 
855   void EmitNewArrayInitializer(const CXXNewExpr *E, llvm::Value *NewPtr,
856                                llvm::Value *NumElements);
857 
858   void PushCXXTemporary(const CXXTemporary *Temporary, llvm::Value *Ptr);
859   void PopCXXTemporary();
860 
861   llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
862   void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
863 
864   void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
865                       QualType DeleteTy);
866 
867   llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
868   llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
869 
870   void EmitCheck(llvm::Value *, unsigned Size);
871 
872   llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
873                                        bool isInc, bool isPre);
874   ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
875                                          bool isInc, bool isPre);
876   //===--------------------------------------------------------------------===//
877   //                            Declaration Emission
878   //===--------------------------------------------------------------------===//
879 
880   /// EmitDecl - Emit a declaration.
881   ///
882   /// This function can be called with a null (unreachable) insert point.
883   void EmitDecl(const Decl &D);
884 
885   /// EmitBlockVarDecl - Emit a block variable declaration.
886   ///
887   /// This function can be called with a null (unreachable) insert point.
888   void EmitBlockVarDecl(const VarDecl &D);
889 
890   /// EmitLocalBlockVarDecl - Emit a local block variable declaration.
891   ///
892   /// This function can be called with a null (unreachable) insert point.
893   void EmitLocalBlockVarDecl(const VarDecl &D);
894 
895   void EmitStaticBlockVarDecl(const VarDecl &D,
896                               llvm::GlobalValue::LinkageTypes Linkage);
897 
898   /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
899   void EmitParmDecl(const VarDecl &D, llvm::Value *Arg);
900 
901   //===--------------------------------------------------------------------===//
902   //                             Statement Emission
903   //===--------------------------------------------------------------------===//
904 
905   /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
906   void EmitStopPoint(const Stmt *S);
907 
908   /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
909   /// this function even if there is no current insertion point.
910   ///
911   /// This function may clear the current insertion point; callers should use
912   /// EnsureInsertPoint if they wish to subsequently generate code without first
913   /// calling EmitBlock, EmitBranch, or EmitStmt.
914   void EmitStmt(const Stmt *S);
915 
916   /// EmitSimpleStmt - Try to emit a "simple" statement which does not
917   /// necessarily require an insertion point or debug information; typically
918   /// because the statement amounts to a jump or a container of other
919   /// statements.
920   ///
921   /// \return True if the statement was handled.
922   bool EmitSimpleStmt(const Stmt *S);
923 
924   RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
925                           llvm::Value *AggLoc = 0, bool isAggVol = false);
926 
927   /// EmitLabel - Emit the block for the given label. It is legal to call this
928   /// function even if there is no current insertion point.
929   void EmitLabel(const LabelStmt &S); // helper for EmitLabelStmt.
930 
931   void EmitLabelStmt(const LabelStmt &S);
932   void EmitGotoStmt(const GotoStmt &S);
933   void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
934   void EmitIfStmt(const IfStmt &S);
935   void EmitWhileStmt(const WhileStmt &S);
936   void EmitDoStmt(const DoStmt &S);
937   void EmitForStmt(const ForStmt &S);
938   void EmitReturnStmt(const ReturnStmt &S);
939   void EmitDeclStmt(const DeclStmt &S);
940   void EmitBreakStmt(const BreakStmt &S);
941   void EmitContinueStmt(const ContinueStmt &S);
942   void EmitSwitchStmt(const SwitchStmt &S);
943   void EmitDefaultStmt(const DefaultStmt &S);
944   void EmitCaseStmt(const CaseStmt &S);
945   void EmitCaseStmtRange(const CaseStmt &S);
946   void EmitAsmStmt(const AsmStmt &S);
947 
948   void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
949   void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
950   void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
951   void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
952 
953   llvm::Constant *getUnwindResumeOrRethrowFn();
954   struct CXXTryStmtInfo {
955     llvm::BasicBlock *SavedLandingPad;
956     llvm::BasicBlock *HandlerBlock;
957     llvm::BasicBlock *FinallyBlock;
958   };
959   CXXTryStmtInfo EnterCXXTryStmt(const CXXTryStmt &S);
960   void ExitCXXTryStmt(const CXXTryStmt &S, CXXTryStmtInfo Info);
961 
962   void EmitCXXTryStmt(const CXXTryStmt &S);
963 
964   //===--------------------------------------------------------------------===//
965   //                         LValue Expression Emission
966   //===--------------------------------------------------------------------===//
967 
968   /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
969   RValue GetUndefRValue(QualType Ty);
970 
971   /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
972   /// and issue an ErrorUnsupported style diagnostic (using the
973   /// provided Name).
974   RValue EmitUnsupportedRValue(const Expr *E,
975                                const char *Name);
976 
977   /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
978   /// an ErrorUnsupported style diagnostic (using the provided Name).
979   LValue EmitUnsupportedLValue(const Expr *E,
980                                const char *Name);
981 
982   /// EmitLValue - Emit code to compute a designator that specifies the location
983   /// of the expression.
984   ///
985   /// This can return one of two things: a simple address or a bitfield
986   /// reference.  In either case, the LLVM Value* in the LValue structure is
987   /// guaranteed to be an LLVM pointer type.
988   ///
989   /// If this returns a bitfield reference, nothing about the pointee type of
990   /// the LLVM value is known: For example, it may not be a pointer to an
991   /// integer.
992   ///
993   /// If this returns a normal address, and if the lvalue's C type is fixed
994   /// size, this method guarantees that the returned pointer type will point to
995   /// an LLVM type of the same size of the lvalue's type.  If the lvalue has a
996   /// variable length type, this is not possible.
997   ///
998   LValue EmitLValue(const Expr *E);
999 
1000   /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
1001   /// checking code to guard against undefined behavior.  This is only
1002   /// suitable when we know that the address will be used to access the
1003   /// object.
1004   LValue EmitCheckedLValue(const Expr *E);
1005 
1006   /// EmitLoadOfScalar - Load a scalar value from an address, taking
1007   /// care to appropriately convert from the memory representation to
1008   /// the LLVM value representation.
1009   llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1010                                 QualType Ty);
1011 
1012   /// EmitStoreOfScalar - Store a scalar value to an address, taking
1013   /// care to appropriately convert from the memory representation to
1014   /// the LLVM value representation.
1015   void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1016                          bool Volatile, QualType Ty);
1017 
1018   /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
1019   /// this method emits the address of the lvalue, then loads the result as an
1020   /// rvalue, returning the rvalue.
1021   RValue EmitLoadOfLValue(LValue V, QualType LVType);
1022   RValue EmitLoadOfExtVectorElementLValue(LValue V, QualType LVType);
1023   RValue EmitLoadOfBitfieldLValue(LValue LV, QualType ExprType);
1024   RValue EmitLoadOfPropertyRefLValue(LValue LV, QualType ExprType);
1025   RValue EmitLoadOfKVCRefLValue(LValue LV, QualType ExprType);
1026 
1027 
1028   /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1029   /// lvalue, where both are guaranteed to the have the same type, and that type
1030   /// is 'Ty'.
1031   void EmitStoreThroughLValue(RValue Src, LValue Dst, QualType Ty);
1032   void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst,
1033                                                 QualType Ty);
1034   void EmitStoreThroughPropertyRefLValue(RValue Src, LValue Dst, QualType Ty);
1035   void EmitStoreThroughKVCRefLValue(RValue Src, LValue Dst, QualType Ty);
1036 
1037   /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
1038   /// EmitStoreThroughLValue.
1039   ///
1040   /// \param Result [out] - If non-null, this will be set to a Value* for the
1041   /// bit-field contents after the store, appropriate for use as the result of
1042   /// an assignment to the bit-field.
1043   void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, QualType Ty,
1044                                       llvm::Value **Result=0);
1045 
1046   // Note: only availabe for agg return types
1047   LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
1048   LValue EmitCompoundAssignOperatorLValue(const CompoundAssignOperator *E);
1049   // Note: only available for agg return types
1050   LValue EmitCallExprLValue(const CallExpr *E);
1051   // Note: only available for agg return types
1052   LValue EmitVAArgExprLValue(const VAArgExpr *E);
1053   LValue EmitDeclRefLValue(const DeclRefExpr *E);
1054   LValue EmitStringLiteralLValue(const StringLiteral *E);
1055   LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
1056   LValue EmitPredefinedFunctionName(unsigned Type);
1057   LValue EmitPredefinedLValue(const PredefinedExpr *E);
1058   LValue EmitUnaryOpLValue(const UnaryOperator *E);
1059   LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
1060   LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
1061   LValue EmitMemberExpr(const MemberExpr *E);
1062   LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
1063   LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
1064   LValue EmitConditionalOperatorLValue(const ConditionalOperator *E);
1065   LValue EmitCastLValue(const CastExpr *E);
1066   LValue EmitNullInitializationLValue(const CXXZeroInitValueExpr *E);
1067 
1068   llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
1069                               const ObjCIvarDecl *Ivar);
1070   LValue EmitLValueForAnonRecordField(llvm::Value* Base,
1071                                       const FieldDecl* Field,
1072                                       unsigned CVRQualifiers);
1073   LValue EmitLValueForField(llvm::Value* Base, const FieldDecl* Field,
1074                             unsigned CVRQualifiers);
1075 
1076   /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
1077   /// if the Field is a reference, this will return the address of the reference
1078   /// and not the address of the value stored in the reference.
1079   LValue EmitLValueForFieldInitialization(llvm::Value* Base,
1080                                           const FieldDecl* Field,
1081                                           unsigned CVRQualifiers);
1082 
1083   LValue EmitLValueForIvar(QualType ObjectTy,
1084                            llvm::Value* Base, const ObjCIvarDecl *Ivar,
1085                            unsigned CVRQualifiers);
1086 
1087   LValue EmitLValueForBitfield(llvm::Value* Base, const FieldDecl* Field,
1088                                 unsigned CVRQualifiers);
1089 
1090   LValue EmitBlockDeclRefLValue(const BlockDeclRefExpr *E);
1091 
1092   LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
1093   LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
1094   LValue EmitCXXExprWithTemporariesLValue(const CXXExprWithTemporaries *E);
1095   LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
1096 
1097   LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
1098   LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
1099   LValue EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E);
1100   LValue EmitObjCKVCRefLValue(const ObjCImplicitSetterGetterRefExpr *E);
1101   LValue EmitObjCSuperExprLValue(const ObjCSuperExpr *E);
1102   LValue EmitStmtExprLValue(const StmtExpr *E);
1103   LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
1104   LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
1105 
1106   //===--------------------------------------------------------------------===//
1107   //                         Scalar Expression Emission
1108   //===--------------------------------------------------------------------===//
1109 
1110   /// EmitCall - Generate a call of the given function, expecting the given
1111   /// result type, and using the given argument list which specifies both the
1112   /// LLVM arguments and the types they were derived from.
1113   ///
1114   /// \param TargetDecl - If given, the decl of the function in a direct call;
1115   /// used to set attributes on the call (noreturn, etc.).
1116   RValue EmitCall(const CGFunctionInfo &FnInfo,
1117                   llvm::Value *Callee,
1118                   ReturnValueSlot ReturnValue,
1119                   const CallArgList &Args,
1120                   const Decl *TargetDecl = 0,
1121                   llvm::Instruction **callOrInvoke = 0);
1122 
1123   RValue EmitCall(QualType FnType, llvm::Value *Callee,
1124                   ReturnValueSlot ReturnValue,
1125                   CallExpr::const_arg_iterator ArgBeg,
1126                   CallExpr::const_arg_iterator ArgEnd,
1127                   const Decl *TargetDecl = 0);
1128   RValue EmitCallExpr(const CallExpr *E,
1129                       ReturnValueSlot ReturnValue = ReturnValueSlot());
1130 
1131   llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
1132                                 const llvm::Type *Ty);
1133   llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
1134                                 llvm::Value *&This, const llvm::Type *Ty);
1135 
1136   RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
1137                            llvm::Value *Callee,
1138                            ReturnValueSlot ReturnValue,
1139                            llvm::Value *This,
1140                            llvm::Value *VTT,
1141                            CallExpr::const_arg_iterator ArgBeg,
1142                            CallExpr::const_arg_iterator ArgEnd);
1143   RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
1144                                ReturnValueSlot ReturnValue);
1145   RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
1146                                       ReturnValueSlot ReturnValue);
1147 
1148   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
1149                                        const CXXMethodDecl *MD,
1150                                        ReturnValueSlot ReturnValue);
1151 
1152 
1153   RValue EmitBuiltinExpr(const FunctionDecl *FD,
1154                          unsigned BuiltinID, const CallExpr *E);
1155 
1156   RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
1157 
1158   /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
1159   /// is unhandled by the current target.
1160   llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1161 
1162   llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1163   llvm::Value *EmitNeonCall(llvm::Function *F,
1164                             llvm::SmallVectorImpl<llvm::Value*> &O,
1165                             const char *name, bool splat = false,
1166                             unsigned shift = 0, bool rightshift = false);
1167   llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
1168   llvm::Value *EmitNeonShiftVector(llvm::Value *V, const llvm::Type *Ty,
1169                                    bool negateForRightShift);
1170 
1171   llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1172   llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
1173 
1174   llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
1175   llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
1176   llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
1177   RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
1178                              ReturnValueSlot Return = ReturnValueSlot());
1179   RValue EmitObjCPropertyGet(const Expr *E,
1180                              ReturnValueSlot Return = ReturnValueSlot());
1181   RValue EmitObjCSuperPropertyGet(const Expr *Exp, const Selector &S,
1182                                   ReturnValueSlot Return = ReturnValueSlot());
1183   void EmitObjCPropertySet(const Expr *E, RValue Src);
1184   void EmitObjCSuperPropertySet(const Expr *E, const Selector &S, RValue Src);
1185 
1186 
1187   /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
1188   /// expression. Will emit a temporary variable if E is not an LValue.
1189   RValue EmitReferenceBindingToExpr(const Expr* E,
1190                                     const NamedDecl *InitializedDecl);
1191 
1192   //===--------------------------------------------------------------------===//
1193   //                           Expression Emission
1194   //===--------------------------------------------------------------------===//
1195 
1196   // Expressions are broken into three classes: scalar, complex, aggregate.
1197 
1198   /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
1199   /// scalar type, returning the result.
1200   llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
1201 
1202   /// EmitScalarConversion - Emit a conversion from the specified type to the
1203   /// specified destination type, both of which are LLVM scalar types.
1204   llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
1205                                     QualType DstTy);
1206 
1207   /// EmitComplexToScalarConversion - Emit a conversion from the specified
1208   /// complex type to the specified destination type, where the destination type
1209   /// is an LLVM scalar type.
1210   llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
1211                                              QualType DstTy);
1212 
1213 
1214   /// EmitAggExpr - Emit the computation of the specified expression of
1215   /// aggregate type.  The result is computed into DestPtr.  Note that if
1216   /// DestPtr is null, the value of the aggregate expression is not needed.
1217   void EmitAggExpr(const Expr *E, llvm::Value *DestPtr, bool VolatileDest,
1218                    bool IgnoreResult = false, bool IsInitializer = false,
1219                    bool RequiresGCollection = false);
1220 
1221   /// EmitAggExprToLValue - Emit the computation of the specified expression of
1222   /// aggregate type into a temporary LValue.
1223   LValue EmitAggExprToLValue(const Expr *E);
1224 
1225   /// EmitGCMemmoveCollectable - Emit special API for structs with object
1226   /// pointers.
1227   void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
1228                                 QualType Ty);
1229 
1230   /// EmitComplexExpr - Emit the computation of the specified expression of
1231   /// complex type, returning the result.
1232   ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal = false,
1233                                 bool IgnoreImag = false,
1234                                 bool IgnoreRealAssign = false,
1235                                 bool IgnoreImagAssign = false);
1236 
1237   /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
1238   /// of complex type, storing into the specified Value*.
1239   void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
1240                                bool DestIsVolatile);
1241 
1242   /// StoreComplexToAddr - Store a complex number into the specified address.
1243   void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
1244                           bool DestIsVolatile);
1245   /// LoadComplexFromAddr - Load a complex number from the specified address.
1246   ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
1247 
1248   /// CreateStaticBlockVarDecl - Create a zero-initialized LLVM global for a
1249   /// static block var decl.
1250   llvm::GlobalVariable *CreateStaticBlockVarDecl(const VarDecl &D,
1251                                                  const char *Separator,
1252                                        llvm::GlobalValue::LinkageTypes Linkage);
1253 
1254   /// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
1255   /// global variable that has already been created for it.  If the initializer
1256   /// has a different type than GV does, this may free GV and return a different
1257   /// one.  Otherwise it just returns GV.
1258   llvm::GlobalVariable *
1259   AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
1260                                      llvm::GlobalVariable *GV);
1261 
1262 
1263   /// EmitStaticCXXBlockVarDeclInit - Create the initializer for a C++ runtime
1264   /// initialized static block var decl.
1265   void EmitStaticCXXBlockVarDeclInit(const VarDecl &D,
1266                                      llvm::GlobalVariable *GV);
1267 
1268   /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
1269   /// variable with global storage.
1270   void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr);
1271 
1272   /// EmitCXXGlobalDtorRegistration - Emits a call to register the global ptr
1273   /// with the C++ runtime so that its destructor will be called at exit.
1274   void EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn,
1275                                      llvm::Constant *DeclPtr);
1276 
1277   /// GenerateCXXGlobalInitFunc - Generates code for initializing global
1278   /// variables.
1279   void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1280                                  llvm::Constant **Decls,
1281                                  unsigned NumDecls);
1282 
1283   /// GenerateCXXGlobalDtorFunc - Generates code for destroying global
1284   /// variables.
1285   void GenerateCXXGlobalDtorFunc(llvm::Function *Fn,
1286                                  const std::vector<std::pair<llvm::WeakVH,
1287                                    llvm::Constant*> > &DtorsAndObjects);
1288 
1289   void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, const VarDecl *D);
1290 
1291   void EmitCXXConstructExpr(llvm::Value *Dest, const CXXConstructExpr *E);
1292 
1293   RValue EmitCXXExprWithTemporaries(const CXXExprWithTemporaries *E,
1294                                     llvm::Value *AggLoc = 0,
1295                                     bool IsAggLocVolatile = false,
1296                                     bool IsInitializer = false);
1297 
1298   void EmitCXXThrowExpr(const CXXThrowExpr *E);
1299 
1300   //===--------------------------------------------------------------------===//
1301   //                             Internal Helpers
1302   //===--------------------------------------------------------------------===//
1303 
1304   /// ContainsLabel - Return true if the statement contains a label in it.  If
1305   /// this statement is not executed normally, it not containing a label means
1306   /// that we can just remove the code.
1307   static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
1308 
1309   /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
1310   /// to a constant, or if it does but contains a label, return 0.  If it
1311   /// constant folds to 'true' and does not contain a label, return 1, if it
1312   /// constant folds to 'false' and does not contain a label, return -1.
1313   int ConstantFoldsToSimpleInteger(const Expr *Cond);
1314 
1315   /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
1316   /// if statement) to the specified blocks.  Based on the condition, this might
1317   /// try to simplify the codegen of the conditional based on the branch.
1318   void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
1319                             llvm::BasicBlock *FalseBlock);
1320 
1321   /// getTrapBB - Create a basic block that will call the trap intrinsic.  We'll
1322   /// generate a branch around the created basic block as necessary.
1323   llvm::BasicBlock* getTrapBB();
1324 
1325   /// EmitCallArg - Emit a single call argument.
1326   RValue EmitCallArg(const Expr *E, QualType ArgType);
1327 
1328   /// EmitDelegateCallArg - We are performing a delegate call; that
1329   /// is, the current function is delegating to another one.  Produce
1330   /// a r-value suitable for passing the given parameter.
1331   RValue EmitDelegateCallArg(const VarDecl *Param);
1332 
1333 private:
1334 
1335   void EmitReturnOfRValue(RValue RV, QualType Ty);
1336 
1337   /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
1338   /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
1339   ///
1340   /// \param AI - The first function argument of the expansion.
1341   /// \return The argument following the last expanded function
1342   /// argument.
1343   llvm::Function::arg_iterator
1344   ExpandTypeFromArgs(QualType Ty, LValue Dst,
1345                      llvm::Function::arg_iterator AI);
1346 
1347   /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
1348   /// Ty, into individual arguments on the provided vector \arg Args. See
1349   /// ABIArgInfo::Expand.
1350   void ExpandTypeToArgs(QualType Ty, RValue Src,
1351                         llvm::SmallVector<llvm::Value*, 16> &Args);
1352 
1353   llvm::Value* EmitAsmInput(const AsmStmt &S,
1354                             const TargetInfo::ConstraintInfo &Info,
1355                             const Expr *InputExpr, std::string &ConstraintStr);
1356 
1357   /// EmitCleanupBlock - emits a single cleanup block.
1358   void EmitCleanupBlock();
1359 
1360   /// AddBranchFixup - adds a branch instruction to the list of fixups for the
1361   /// current cleanup scope.
1362   void AddBranchFixup(llvm::BranchInst *BI);
1363 
1364   /// EmitCallArgs - Emit call arguments for a function.
1365   /// The CallArgTypeInfo parameter is used for iterating over the known
1366   /// argument types of the function being called.
1367   template<typename T>
1368   void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
1369                     CallExpr::const_arg_iterator ArgBeg,
1370                     CallExpr::const_arg_iterator ArgEnd) {
1371       CallExpr::const_arg_iterator Arg = ArgBeg;
1372 
1373     // First, use the argument types that the type info knows about
1374     if (CallArgTypeInfo) {
1375       for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
1376            E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
1377         assert(Arg != ArgEnd && "Running over edge of argument list!");
1378         QualType ArgType = *I;
1379 
1380         assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1381                getTypePtr() ==
1382                getContext().getCanonicalType(Arg->getType()).getTypePtr() &&
1383                "type mismatch in call argument!");
1384 
1385         Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1386                                       ArgType));
1387       }
1388 
1389       // Either we've emitted all the call args, or we have a call to a
1390       // variadic function.
1391       assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
1392              "Extra arguments in non-variadic function!");
1393 
1394     }
1395 
1396     // If we still have any arguments, emit them using the type of the argument.
1397     for (; Arg != ArgEnd; ++Arg) {
1398       QualType ArgType = Arg->getType();
1399       Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1400                                     ArgType));
1401     }
1402   }
1403 
1404   const TargetCodeGenInfo &getTargetHooks() const {
1405     return CGM.getTargetCodeGenInfo();
1406   }
1407 };
1408 
1409 
1410 }  // end namespace CodeGen
1411 }  // end namespace clang
1412 
1413 #endif
1414