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