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