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