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 "CGBuilder.h" 18 #include "CGDebugInfo.h" 19 #include "CGValue.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "EHScopeStack.h" 23 #include "clang/AST/CharUnits.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/Type.h" 27 #include "clang/Basic/ABI.h" 28 #include "clang/Basic/CapturedStmt.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Frontend/CodeGenOptions.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/DenseMap.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ValueHandle.h" 36 37 namespace llvm { 38 class BasicBlock; 39 class LLVMContext; 40 class MDNode; 41 class Module; 42 class SwitchInst; 43 class Twine; 44 class Value; 45 class CallSite; 46 } 47 48 namespace clang { 49 class ASTContext; 50 class BlockDecl; 51 class CXXDestructorDecl; 52 class CXXForRangeStmt; 53 class CXXTryStmt; 54 class Decl; 55 class LabelDecl; 56 class EnumConstantDecl; 57 class FunctionDecl; 58 class FunctionProtoType; 59 class LabelStmt; 60 class ObjCContainerDecl; 61 class ObjCInterfaceDecl; 62 class ObjCIvarDecl; 63 class ObjCMethodDecl; 64 class ObjCImplementationDecl; 65 class ObjCPropertyImplDecl; 66 class TargetInfo; 67 class TargetCodeGenInfo; 68 class VarDecl; 69 class ObjCForCollectionStmt; 70 class ObjCAtTryStmt; 71 class ObjCAtThrowStmt; 72 class ObjCAtSynchronizedStmt; 73 class ObjCAutoreleasePoolStmt; 74 75 namespace CodeGen { 76 class CodeGenTypes; 77 class CGFunctionInfo; 78 class CGRecordLayout; 79 class CGBlockInfo; 80 class CGCXXABI; 81 class BlockFlags; 82 class BlockFieldFlags; 83 84 /// The kind of evaluation to perform on values of a particular 85 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 86 /// CGExprAgg? 87 /// 88 /// TODO: should vectors maybe be split out into their own thing? 89 enum TypeEvaluationKind { 90 TEK_Scalar, 91 TEK_Complex, 92 TEK_Aggregate 93 }; 94 95 /// CodeGenFunction - This class organizes the per-function state that is used 96 /// while generating LLVM code. 97 class CodeGenFunction : public CodeGenTypeCache { 98 CodeGenFunction(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 99 void operator=(const CodeGenFunction &) LLVM_DELETED_FUNCTION; 100 101 friend class CGCXXABI; 102 public: 103 /// A jump destination is an abstract label, branching to which may 104 /// require a jump out through normal cleanups. 105 struct JumpDest { 106 JumpDest() : Block(0), ScopeDepth(), Index(0) {} 107 JumpDest(llvm::BasicBlock *Block, 108 EHScopeStack::stable_iterator Depth, 109 unsigned Index) 110 : Block(Block), ScopeDepth(Depth), Index(Index) {} 111 112 bool isValid() const { return Block != 0; } 113 llvm::BasicBlock *getBlock() const { return Block; } 114 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 115 unsigned getDestIndex() const { return Index; } 116 117 // This should be used cautiously. 118 void setScopeDepth(EHScopeStack::stable_iterator depth) { 119 ScopeDepth = depth; 120 } 121 122 private: 123 llvm::BasicBlock *Block; 124 EHScopeStack::stable_iterator ScopeDepth; 125 unsigned Index; 126 }; 127 128 CodeGenModule &CGM; // Per-module state. 129 const TargetInfo &Target; 130 131 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 132 CGBuilderTy Builder; 133 134 /// CurFuncDecl - Holds the Decl for the current outermost 135 /// non-closure context. 136 const Decl *CurFuncDecl; 137 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 138 const Decl *CurCodeDecl; 139 const CGFunctionInfo *CurFnInfo; 140 QualType FnRetTy; 141 llvm::Function *CurFn; 142 143 /// CurGD - The GlobalDecl for the current function being compiled. 144 GlobalDecl CurGD; 145 146 /// PrologueCleanupDepth - The cleanup depth enclosing all the 147 /// cleanups associated with the parameters. 148 EHScopeStack::stable_iterator PrologueCleanupDepth; 149 150 /// ReturnBlock - Unified return block. 151 JumpDest ReturnBlock; 152 153 /// ReturnValue - The temporary alloca to hold the return value. This is null 154 /// iff the function has no return value. 155 llvm::Value *ReturnValue; 156 157 /// AllocaInsertPoint - This is an instruction in the entry block before which 158 /// we prefer to insert allocas. 159 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 160 161 /// \brief API for captured statement code generation. 162 class CGCapturedStmtInfo { 163 public: 164 explicit CGCapturedStmtInfo(const CapturedStmt &S, 165 CapturedRegionKind K = CR_Default) 166 : Kind(K), ThisValue(0), CXXThisFieldDecl(0) { 167 168 RecordDecl::field_iterator Field = 169 S.getCapturedRecordDecl()->field_begin(); 170 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 171 E = S.capture_end(); 172 I != E; ++I, ++Field) { 173 if (I->capturesThis()) 174 CXXThisFieldDecl = *Field; 175 else 176 CaptureFields[I->getCapturedVar()] = *Field; 177 } 178 } 179 180 virtual ~CGCapturedStmtInfo(); 181 182 CapturedRegionKind getKind() const { return Kind; } 183 184 void setContextValue(llvm::Value *V) { ThisValue = V; } 185 // \brief Retrieve the value of the context parameter. 186 llvm::Value *getContextValue() const { return ThisValue; } 187 188 /// \brief Lookup the captured field decl for a variable. 189 const FieldDecl *lookup(const VarDecl *VD) const { 190 return CaptureFields.lookup(VD); 191 } 192 193 bool isCXXThisExprCaptured() const { return CXXThisFieldDecl != 0; } 194 FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 195 196 /// \brief Emit the captured statement body. 197 virtual void EmitBody(CodeGenFunction &CGF, Stmt *S) { 198 CGF.EmitStmt(S); 199 } 200 201 /// \brief Get the name of the capture helper. 202 virtual StringRef getHelperName() const { return "__captured_stmt"; } 203 204 private: 205 /// \brief The kind of captured statement being generated. 206 CapturedRegionKind Kind; 207 208 /// \brief Keep the map between VarDecl and FieldDecl. 209 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 210 211 /// \brief The base address of the captured record, passed in as the first 212 /// argument of the parallel region function. 213 llvm::Value *ThisValue; 214 215 /// \brief Captured 'this' type. 216 FieldDecl *CXXThisFieldDecl; 217 }; 218 CGCapturedStmtInfo *CapturedStmtInfo; 219 220 /// BoundsChecking - Emit run-time bounds checks. Higher values mean 221 /// potentially higher performance penalties. 222 unsigned char BoundsChecking; 223 224 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 225 /// calls to EmitTypeCheck can be skipped. 226 bool SanitizePerformTypeCheck; 227 228 /// \brief Sanitizer options to use for this function. 229 const SanitizerOptions *SanOpts; 230 231 /// In ARC, whether we should autorelease the return value. 232 bool AutoreleaseResult; 233 234 const CodeGen::CGBlockInfo *BlockInfo; 235 llvm::Value *BlockPointer; 236 237 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 238 FieldDecl *LambdaThisCaptureField; 239 240 /// \brief A mapping from NRVO variables to the flags used to indicate 241 /// when the NRVO has been applied to this variable. 242 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 243 244 EHScopeStack EHStack; 245 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 246 247 /// Header for data within LifetimeExtendedCleanupStack. 248 struct LifetimeExtendedCleanupHeader { 249 /// The size of the following cleanup object. 250 size_t Size : 29; 251 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 252 unsigned Kind : 3; 253 254 size_t getSize() const { return Size; } 255 CleanupKind getKind() const { return static_cast<CleanupKind>(Kind); } 256 }; 257 258 /// i32s containing the indexes of the cleanup destinations. 259 llvm::AllocaInst *NormalCleanupDest; 260 261 unsigned NextCleanupDestIndex; 262 263 /// FirstBlockInfo - The head of a singly-linked-list of block layouts. 264 CGBlockInfo *FirstBlockInfo; 265 266 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 267 llvm::BasicBlock *EHResumeBlock; 268 269 /// The exception slot. All landing pads write the current exception pointer 270 /// into this alloca. 271 llvm::Value *ExceptionSlot; 272 273 /// The selector slot. Under the MandatoryCleanup model, all landing pads 274 /// write the current selector value into this alloca. 275 llvm::AllocaInst *EHSelectorSlot; 276 277 /// Emits a landing pad for the current EH stack. 278 llvm::BasicBlock *EmitLandingPad(); 279 280 llvm::BasicBlock *getInvokeDestImpl(); 281 282 template <class T> 283 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 284 return DominatingValue<T>::save(*this, value); 285 } 286 287 public: 288 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 289 /// rethrows. 290 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 291 292 /// A class controlling the emission of a finally block. 293 class FinallyInfo { 294 /// Where the catchall's edge through the cleanup should go. 295 JumpDest RethrowDest; 296 297 /// A function to call to enter the catch. 298 llvm::Constant *BeginCatchFn; 299 300 /// An i1 variable indicating whether or not the @finally is 301 /// running for an exception. 302 llvm::AllocaInst *ForEHVar; 303 304 /// An i8* variable into which the exception pointer to rethrow 305 /// has been saved. 306 llvm::AllocaInst *SavedExnVar; 307 308 public: 309 void enter(CodeGenFunction &CGF, const Stmt *Finally, 310 llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn, 311 llvm::Constant *rethrowFn); 312 void exit(CodeGenFunction &CGF); 313 }; 314 315 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 316 /// current full-expression. Safe against the possibility that 317 /// we're currently inside a conditionally-evaluated expression. 318 template <class T, class A0> 319 void pushFullExprCleanup(CleanupKind kind, A0 a0) { 320 // If we're not in a conditional branch, or if none of the 321 // arguments requires saving, then use the unconditional cleanup. 322 if (!isInConditionalBranch()) 323 return EHStack.pushCleanup<T>(kind, a0); 324 325 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 326 327 typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType; 328 EHStack.pushCleanup<CleanupType>(kind, a0_saved); 329 initFullExprCleanup(); 330 } 331 332 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 333 /// current full-expression. Safe against the possibility that 334 /// we're currently inside a conditionally-evaluated expression. 335 template <class T, class A0, class A1> 336 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) { 337 // If we're not in a conditional branch, or if none of the 338 // arguments requires saving, then use the unconditional cleanup. 339 if (!isInConditionalBranch()) 340 return EHStack.pushCleanup<T>(kind, a0, a1); 341 342 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 343 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 344 345 typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType; 346 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved); 347 initFullExprCleanup(); 348 } 349 350 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 351 /// current full-expression. Safe against the possibility that 352 /// we're currently inside a conditionally-evaluated expression. 353 template <class T, class A0, class A1, class A2> 354 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) { 355 // If we're not in a conditional branch, or if none of the 356 // arguments requires saving, then use the unconditional cleanup. 357 if (!isInConditionalBranch()) { 358 return EHStack.pushCleanup<T>(kind, a0, a1, a2); 359 } 360 361 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 362 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 363 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 364 365 typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType; 366 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved); 367 initFullExprCleanup(); 368 } 369 370 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 371 /// current full-expression. Safe against the possibility that 372 /// we're currently inside a conditionally-evaluated expression. 373 template <class T, class A0, class A1, class A2, class A3> 374 void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) { 375 // If we're not in a conditional branch, or if none of the 376 // arguments requires saving, then use the unconditional cleanup. 377 if (!isInConditionalBranch()) { 378 return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3); 379 } 380 381 typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0); 382 typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1); 383 typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2); 384 typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3); 385 386 typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType; 387 EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, 388 a2_saved, a3_saved); 389 initFullExprCleanup(); 390 } 391 392 /// \brief Queue a cleanup to be pushed after finishing the current 393 /// full-expression. 394 template <class T, class A0, class A1, class A2, class A3> 395 void pushCleanupAfterFullExpr(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) { 396 assert(!isInConditionalBranch() && "can't defer conditional cleanup"); 397 398 LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind }; 399 400 size_t OldSize = LifetimeExtendedCleanupStack.size(); 401 LifetimeExtendedCleanupStack.resize( 402 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size); 403 404 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 405 new (Buffer) LifetimeExtendedCleanupHeader(Header); 406 new (Buffer + sizeof(Header)) T(a0, a1, a2, a3); 407 } 408 409 /// Set up the last cleaup that was pushed as a conditional 410 /// full-expression cleanup. 411 void initFullExprCleanup(); 412 413 /// PushDestructorCleanup - Push a cleanup to call the 414 /// complete-object destructor of an object of the given type at the 415 /// given address. Does nothing if T is not a C++ class type with a 416 /// non-trivial destructor. 417 void PushDestructorCleanup(QualType T, llvm::Value *Addr); 418 419 /// PushDestructorCleanup - Push a cleanup to call the 420 /// complete-object variant of the given destructor on the object at 421 /// the given address. 422 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, 423 llvm::Value *Addr); 424 425 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 426 /// process all branch fixups. 427 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 428 429 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 430 /// The block cannot be reactivated. Pops it if it's the top of the 431 /// stack. 432 /// 433 /// \param DominatingIP - An instruction which is known to 434 /// dominate the current IP (if set) and which lies along 435 /// all paths of execution between the current IP and the 436 /// the point at which the cleanup comes into scope. 437 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 438 llvm::Instruction *DominatingIP); 439 440 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 441 /// Cannot be used to resurrect a deactivated cleanup. 442 /// 443 /// \param DominatingIP - An instruction which is known to 444 /// dominate the current IP (if set) and which lies along 445 /// all paths of execution between the current IP and the 446 /// the point at which the cleanup comes into scope. 447 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 448 llvm::Instruction *DominatingIP); 449 450 /// \brief Enters a new scope for capturing cleanups, all of which 451 /// will be executed once the scope is exited. 452 class RunCleanupsScope { 453 EHScopeStack::stable_iterator CleanupStackDepth; 454 size_t LifetimeExtendedCleanupStackSize; 455 bool OldDidCallStackSave; 456 protected: 457 bool PerformCleanup; 458 private: 459 460 RunCleanupsScope(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 461 void operator=(const RunCleanupsScope &) LLVM_DELETED_FUNCTION; 462 463 protected: 464 CodeGenFunction& CGF; 465 466 public: 467 /// \brief Enter a new cleanup scope. 468 explicit RunCleanupsScope(CodeGenFunction &CGF) 469 : PerformCleanup(true), CGF(CGF) 470 { 471 CleanupStackDepth = CGF.EHStack.stable_begin(); 472 LifetimeExtendedCleanupStackSize = 473 CGF.LifetimeExtendedCleanupStack.size(); 474 OldDidCallStackSave = CGF.DidCallStackSave; 475 CGF.DidCallStackSave = false; 476 } 477 478 /// \brief Exit this cleanup scope, emitting any accumulated 479 /// cleanups. 480 ~RunCleanupsScope() { 481 if (PerformCleanup) { 482 CGF.DidCallStackSave = OldDidCallStackSave; 483 CGF.PopCleanupBlocks(CleanupStackDepth, 484 LifetimeExtendedCleanupStackSize); 485 } 486 } 487 488 /// \brief Determine whether this scope requires any cleanups. 489 bool requiresCleanups() const { 490 return CGF.EHStack.stable_begin() != CleanupStackDepth; 491 } 492 493 /// \brief Force the emission of cleanups now, instead of waiting 494 /// until this object is destroyed. 495 void ForceCleanup() { 496 assert(PerformCleanup && "Already forced cleanup"); 497 CGF.DidCallStackSave = OldDidCallStackSave; 498 CGF.PopCleanupBlocks(CleanupStackDepth, 499 LifetimeExtendedCleanupStackSize); 500 PerformCleanup = false; 501 } 502 }; 503 504 class LexicalScope: protected RunCleanupsScope { 505 SourceRange Range; 506 SmallVector<const LabelDecl*, 4> Labels; 507 LexicalScope *ParentScope; 508 509 LexicalScope(const LexicalScope &) LLVM_DELETED_FUNCTION; 510 void operator=(const LexicalScope &) LLVM_DELETED_FUNCTION; 511 512 public: 513 /// \brief Enter a new cleanup scope. 514 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 515 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 516 CGF.CurLexicalScope = this; 517 if (CGDebugInfo *DI = CGF.getDebugInfo()) 518 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 519 } 520 521 void addLabel(const LabelDecl *label) { 522 assert(PerformCleanup && "adding label to dead scope?"); 523 Labels.push_back(label); 524 } 525 526 /// \brief Exit this cleanup scope, emitting any accumulated 527 /// cleanups. 528 ~LexicalScope() { 529 if (CGDebugInfo *DI = CGF.getDebugInfo()) 530 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 531 532 // If we should perform a cleanup, force them now. Note that 533 // this ends the cleanup scope before rescoping any labels. 534 if (PerformCleanup) ForceCleanup(); 535 } 536 537 /// \brief Force the emission of cleanups now, instead of waiting 538 /// until this object is destroyed. 539 void ForceCleanup() { 540 CGF.CurLexicalScope = ParentScope; 541 RunCleanupsScope::ForceCleanup(); 542 543 if (!Labels.empty()) 544 rescopeLabels(); 545 } 546 547 void rescopeLabels(); 548 }; 549 550 551 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 552 /// that have been added. 553 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize); 554 555 /// \brief Takes the old cleanup stack size and emits the cleanup blocks 556 /// that have been added, then adds all lifetime-extended cleanups from 557 /// the given position to the stack. 558 void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 559 size_t OldLifetimeExtendedStackSize); 560 561 void ResolveBranchFixups(llvm::BasicBlock *Target); 562 563 /// The given basic block lies in the current EH scope, but may be a 564 /// target of a potentially scope-crossing jump; get a stable handle 565 /// to which we can perform this jump later. 566 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 567 return JumpDest(Target, 568 EHStack.getInnermostNormalCleanup(), 569 NextCleanupDestIndex++); 570 } 571 572 /// The given basic block lies in the current EH scope, but may be a 573 /// target of a potentially scope-crossing jump; get a stable handle 574 /// to which we can perform this jump later. 575 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 576 return getJumpDestInCurrentScope(createBasicBlock(Name)); 577 } 578 579 /// EmitBranchThroughCleanup - Emit a branch from the current insert 580 /// block through the normal cleanup handling code (if any) and then 581 /// on to \arg Dest. 582 void EmitBranchThroughCleanup(JumpDest Dest); 583 584 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 585 /// specified destination obviously has no cleanups to run. 'false' is always 586 /// a conservatively correct answer for this method. 587 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 588 589 /// popCatchScope - Pops the catch scope at the top of the EHScope 590 /// stack, emitting any required code (other than the catch handlers 591 /// themselves). 592 void popCatchScope(); 593 594 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 595 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 596 597 /// An object to manage conditionally-evaluated expressions. 598 class ConditionalEvaluation { 599 llvm::BasicBlock *StartBB; 600 601 public: 602 ConditionalEvaluation(CodeGenFunction &CGF) 603 : StartBB(CGF.Builder.GetInsertBlock()) {} 604 605 void begin(CodeGenFunction &CGF) { 606 assert(CGF.OutermostConditional != this); 607 if (!CGF.OutermostConditional) 608 CGF.OutermostConditional = this; 609 } 610 611 void end(CodeGenFunction &CGF) { 612 assert(CGF.OutermostConditional != 0); 613 if (CGF.OutermostConditional == this) 614 CGF.OutermostConditional = 0; 615 } 616 617 /// Returns a block which will be executed prior to each 618 /// evaluation of the conditional code. 619 llvm::BasicBlock *getStartingBlock() const { 620 return StartBB; 621 } 622 }; 623 624 /// isInConditionalBranch - Return true if we're currently emitting 625 /// one branch or the other of a conditional expression. 626 bool isInConditionalBranch() const { return OutermostConditional != 0; } 627 628 void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) { 629 assert(isInConditionalBranch()); 630 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 631 new llvm::StoreInst(value, addr, &block->back()); 632 } 633 634 /// An RAII object to record that we're evaluating a statement 635 /// expression. 636 class StmtExprEvaluation { 637 CodeGenFunction &CGF; 638 639 /// We have to save the outermost conditional: cleanups in a 640 /// statement expression aren't conditional just because the 641 /// StmtExpr is. 642 ConditionalEvaluation *SavedOutermostConditional; 643 644 public: 645 StmtExprEvaluation(CodeGenFunction &CGF) 646 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 647 CGF.OutermostConditional = 0; 648 } 649 650 ~StmtExprEvaluation() { 651 CGF.OutermostConditional = SavedOutermostConditional; 652 CGF.EnsureInsertPoint(); 653 } 654 }; 655 656 /// An object which temporarily prevents a value from being 657 /// destroyed by aggressive peephole optimizations that assume that 658 /// all uses of a value have been realized in the IR. 659 class PeepholeProtection { 660 llvm::Instruction *Inst; 661 friend class CodeGenFunction; 662 663 public: 664 PeepholeProtection() : Inst(0) {} 665 }; 666 667 /// A non-RAII class containing all the information about a bound 668 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 669 /// this which makes individual mappings very simple; using this 670 /// class directly is useful when you have a variable number of 671 /// opaque values or don't want the RAII functionality for some 672 /// reason. 673 class OpaqueValueMappingData { 674 const OpaqueValueExpr *OpaqueValue; 675 bool BoundLValue; 676 CodeGenFunction::PeepholeProtection Protection; 677 678 OpaqueValueMappingData(const OpaqueValueExpr *ov, 679 bool boundLValue) 680 : OpaqueValue(ov), BoundLValue(boundLValue) {} 681 public: 682 OpaqueValueMappingData() : OpaqueValue(0) {} 683 684 static bool shouldBindAsLValue(const Expr *expr) { 685 // gl-values should be bound as l-values for obvious reasons. 686 // Records should be bound as l-values because IR generation 687 // always keeps them in memory. Expressions of function type 688 // act exactly like l-values but are formally required to be 689 // r-values in C. 690 return expr->isGLValue() || 691 expr->getType()->isRecordType() || 692 expr->getType()->isFunctionType(); 693 } 694 695 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 696 const OpaqueValueExpr *ov, 697 const Expr *e) { 698 if (shouldBindAsLValue(ov)) 699 return bind(CGF, ov, CGF.EmitLValue(e)); 700 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 701 } 702 703 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 704 const OpaqueValueExpr *ov, 705 const LValue &lv) { 706 assert(shouldBindAsLValue(ov)); 707 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 708 return OpaqueValueMappingData(ov, true); 709 } 710 711 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 712 const OpaqueValueExpr *ov, 713 const RValue &rv) { 714 assert(!shouldBindAsLValue(ov)); 715 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 716 717 OpaqueValueMappingData data(ov, false); 718 719 // Work around an extremely aggressive peephole optimization in 720 // EmitScalarConversion which assumes that all other uses of a 721 // value are extant. 722 data.Protection = CGF.protectFromPeepholes(rv); 723 724 return data; 725 } 726 727 bool isValid() const { return OpaqueValue != 0; } 728 void clear() { OpaqueValue = 0; } 729 730 void unbind(CodeGenFunction &CGF) { 731 assert(OpaqueValue && "no data to unbind!"); 732 733 if (BoundLValue) { 734 CGF.OpaqueLValues.erase(OpaqueValue); 735 } else { 736 CGF.OpaqueRValues.erase(OpaqueValue); 737 CGF.unprotectFromPeepholes(Protection); 738 } 739 } 740 }; 741 742 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 743 class OpaqueValueMapping { 744 CodeGenFunction &CGF; 745 OpaqueValueMappingData Data; 746 747 public: 748 static bool shouldBindAsLValue(const Expr *expr) { 749 return OpaqueValueMappingData::shouldBindAsLValue(expr); 750 } 751 752 /// Build the opaque value mapping for the given conditional 753 /// operator if it's the GNU ?: extension. This is a common 754 /// enough pattern that the convenience operator is really 755 /// helpful. 756 /// 757 OpaqueValueMapping(CodeGenFunction &CGF, 758 const AbstractConditionalOperator *op) : CGF(CGF) { 759 if (isa<ConditionalOperator>(op)) 760 // Leave Data empty. 761 return; 762 763 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 764 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 765 e->getCommon()); 766 } 767 768 OpaqueValueMapping(CodeGenFunction &CGF, 769 const OpaqueValueExpr *opaqueValue, 770 LValue lvalue) 771 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 772 } 773 774 OpaqueValueMapping(CodeGenFunction &CGF, 775 const OpaqueValueExpr *opaqueValue, 776 RValue rvalue) 777 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 778 } 779 780 void pop() { 781 Data.unbind(CGF); 782 Data.clear(); 783 } 784 785 ~OpaqueValueMapping() { 786 if (Data.isValid()) Data.unbind(CGF); 787 } 788 }; 789 790 /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field 791 /// number that holds the value. 792 unsigned getByRefValueLLVMField(const ValueDecl *VD) const; 793 794 /// BuildBlockByrefAddress - Computes address location of the 795 /// variable which is declared as __block. 796 llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr, 797 const VarDecl *V); 798 private: 799 CGDebugInfo *DebugInfo; 800 bool DisableDebugInfo; 801 802 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 803 /// calling llvm.stacksave for multiple VLAs in the same scope. 804 bool DidCallStackSave; 805 806 /// IndirectBranch - The first time an indirect goto is seen we create a block 807 /// with an indirect branch. Every time we see the address of a label taken, 808 /// we add the label to the indirect goto. Every subsequent indirect goto is 809 /// codegen'd as a jump to the IndirectBranch's basic block. 810 llvm::IndirectBrInst *IndirectBranch; 811 812 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 813 /// decls. 814 typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy; 815 DeclMapTy LocalDeclMap; 816 817 /// LabelMap - This keeps track of the LLVM basic block for each C label. 818 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 819 820 // BreakContinueStack - This keeps track of where break and continue 821 // statements should jump to and the associated base counter for 822 // instrumentation. 823 struct BreakContinue { 824 BreakContinue(JumpDest Break, JumpDest Continue, RegionCounter *LoopCnt, 825 bool CountBreak = true) 826 : BreakBlock(Break), ContinueBlock(Continue), LoopCnt(LoopCnt), 827 CountBreak(CountBreak) {} 828 829 JumpDest BreakBlock; 830 JumpDest ContinueBlock; 831 RegionCounter *LoopCnt; 832 bool CountBreak; 833 }; 834 SmallVector<BreakContinue, 8> BreakContinueStack; 835 836 CodeGenPGO PGO; 837 838 public: 839 /// Get a counter for instrumentation of the region associated with the given 840 /// statement. 841 RegionCounter getPGORegionCounter(const Stmt *S) { 842 return RegionCounter(PGO, S); 843 } 844 private: 845 846 /// SwitchInsn - This is nearest current switch instruction. It is null if 847 /// current context is not in a switch. 848 llvm::SwitchInst *SwitchInsn; 849 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 850 SmallVector<uint64_t, 16> *SwitchWeights; 851 852 /// CaseRangeBlock - This block holds if condition check for last case 853 /// statement range in current switch instruction. 854 llvm::BasicBlock *CaseRangeBlock; 855 856 /// OpaqueLValues - Keeps track of the current set of opaque value 857 /// expressions. 858 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 859 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 860 861 // VLASizeMap - This keeps track of the associated size for each VLA type. 862 // We track this by the size expression rather than the type itself because 863 // in certain situations, like a const qualifier applied to an VLA typedef, 864 // multiple VLA types can share the same size expression. 865 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 866 // enter/leave scopes. 867 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 868 869 /// A block containing a single 'unreachable' instruction. Created 870 /// lazily by getUnreachableBlock(). 871 llvm::BasicBlock *UnreachableBlock; 872 873 /// Counts of the number return expressions in the function. 874 unsigned NumReturnExprs; 875 876 /// Count the number of simple (constant) return expressions in the function. 877 unsigned NumSimpleReturnExprs; 878 879 /// The last regular (non-return) debug location (breakpoint) in the function. 880 SourceLocation LastStopPoint; 881 882 public: 883 /// A scope within which we are constructing the fields of an object which 884 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 885 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 886 class FieldConstructionScope { 887 public: 888 FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This) 889 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 890 CGF.CXXDefaultInitExprThis = This; 891 } 892 ~FieldConstructionScope() { 893 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 894 } 895 896 private: 897 CodeGenFunction &CGF; 898 llvm::Value *OldCXXDefaultInitExprThis; 899 }; 900 901 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 902 /// is overridden to be the object under construction. 903 class CXXDefaultInitExprScope { 904 public: 905 CXXDefaultInitExprScope(CodeGenFunction &CGF) 906 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) { 907 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis; 908 } 909 ~CXXDefaultInitExprScope() { 910 CGF.CXXThisValue = OldCXXThisValue; 911 } 912 913 public: 914 CodeGenFunction &CGF; 915 llvm::Value *OldCXXThisValue; 916 }; 917 918 private: 919 /// CXXThisDecl - When generating code for a C++ member function, 920 /// this will hold the implicit 'this' declaration. 921 ImplicitParamDecl *CXXABIThisDecl; 922 llvm::Value *CXXABIThisValue; 923 llvm::Value *CXXThisValue; 924 925 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 926 /// this expression. 927 llvm::Value *CXXDefaultInitExprThis; 928 929 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 930 /// destructor, this will hold the implicit argument (e.g. VTT). 931 ImplicitParamDecl *CXXStructorImplicitParamDecl; 932 llvm::Value *CXXStructorImplicitParamValue; 933 934 /// OutermostConditional - Points to the outermost active 935 /// conditional control. This is used so that we know if a 936 /// temporary should be destroyed conditionally. 937 ConditionalEvaluation *OutermostConditional; 938 939 /// The current lexical scope. 940 LexicalScope *CurLexicalScope; 941 942 /// The current source location that should be used for exception 943 /// handling code. 944 SourceLocation CurEHLocation; 945 946 /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM 947 /// type as well as the field number that contains the actual data. 948 llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *, 949 unsigned> > ByRefValueInfo; 950 951 llvm::BasicBlock *TerminateLandingPad; 952 llvm::BasicBlock *TerminateHandler; 953 llvm::BasicBlock *TrapBB; 954 955 /// Add a kernel metadata node to the named metadata node 'opencl.kernels'. 956 /// In the kernel metadata node, reference the kernel function and metadata 957 /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2): 958 /// - A node for the vec_type_hint(<type>) qualifier contains string 959 /// "vec_type_hint", an undefined value of the <type> data type, 960 /// and a Boolean that is true if the <type> is integer and signed. 961 /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string 962 /// "work_group_size_hint", and three 32-bit integers X, Y and Z. 963 /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string 964 /// "reqd_work_group_size", and three 32-bit integers X, Y and Z. 965 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 966 llvm::Function *Fn); 967 968 public: 969 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 970 ~CodeGenFunction(); 971 972 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 973 ASTContext &getContext() const { return CGM.getContext(); } 974 CGDebugInfo *getDebugInfo() { 975 if (DisableDebugInfo) 976 return NULL; 977 return DebugInfo; 978 } 979 void disableDebugInfo() { DisableDebugInfo = true; } 980 void enableDebugInfo() { DisableDebugInfo = false; } 981 982 bool shouldUseFusedARCCalls() { 983 return CGM.getCodeGenOpts().OptimizationLevel == 0; 984 } 985 986 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 987 988 /// Returns a pointer to the function's exception object and selector slot, 989 /// which is assigned in every landing pad. 990 llvm::Value *getExceptionSlot(); 991 llvm::Value *getEHSelectorSlot(); 992 993 /// Returns the contents of the function's exception object and selector 994 /// slots. 995 llvm::Value *getExceptionFromSlot(); 996 llvm::Value *getSelectorFromSlot(); 997 998 llvm::Value *getNormalCleanupDestSlot(); 999 1000 llvm::BasicBlock *getUnreachableBlock() { 1001 if (!UnreachableBlock) { 1002 UnreachableBlock = createBasicBlock("unreachable"); 1003 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 1004 } 1005 return UnreachableBlock; 1006 } 1007 1008 llvm::BasicBlock *getInvokeDest() { 1009 if (!EHStack.requiresLandingPad()) return 0; 1010 return getInvokeDestImpl(); 1011 } 1012 1013 const TargetInfo &getTarget() const { return Target; } 1014 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 1015 1016 //===--------------------------------------------------------------------===// 1017 // Cleanups 1018 //===--------------------------------------------------------------------===// 1019 1020 typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty); 1021 1022 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1023 llvm::Value *arrayEndPointer, 1024 QualType elementType, 1025 Destroyer *destroyer); 1026 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1027 llvm::Value *arrayEnd, 1028 QualType elementType, 1029 Destroyer *destroyer); 1030 1031 void pushDestroy(QualType::DestructionKind dtorKind, 1032 llvm::Value *addr, QualType type); 1033 void pushEHDestroy(QualType::DestructionKind dtorKind, 1034 llvm::Value *addr, QualType type); 1035 void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type, 1036 Destroyer *destroyer, bool useEHCleanupForArray); 1037 void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr, 1038 QualType type, Destroyer *destroyer, 1039 bool useEHCleanupForArray); 1040 void pushStackRestore(CleanupKind kind, llvm::Value *SPMem); 1041 void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer, 1042 bool useEHCleanupForArray); 1043 llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type, 1044 Destroyer *destroyer, 1045 bool useEHCleanupForArray, 1046 const VarDecl *VD); 1047 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1048 QualType type, Destroyer *destroyer, 1049 bool checkZeroLength, bool useEHCleanup); 1050 1051 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1052 1053 /// Determines whether an EH cleanup is required to destroy a type 1054 /// with the given destruction kind. 1055 bool needsEHCleanup(QualType::DestructionKind kind) { 1056 switch (kind) { 1057 case QualType::DK_none: 1058 return false; 1059 case QualType::DK_cxx_destructor: 1060 case QualType::DK_objc_weak_lifetime: 1061 return getLangOpts().Exceptions; 1062 case QualType::DK_objc_strong_lifetime: 1063 return getLangOpts().Exceptions && 1064 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1065 } 1066 llvm_unreachable("bad destruction kind"); 1067 } 1068 1069 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1070 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1071 } 1072 1073 //===--------------------------------------------------------------------===// 1074 // Objective-C 1075 //===--------------------------------------------------------------------===// 1076 1077 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1078 1079 void StartObjCMethod(const ObjCMethodDecl *MD, 1080 const ObjCContainerDecl *CD, 1081 SourceLocation StartLoc); 1082 1083 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1084 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1085 const ObjCPropertyImplDecl *PID); 1086 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1087 const ObjCPropertyImplDecl *propImpl, 1088 const ObjCMethodDecl *GetterMothodDecl, 1089 llvm::Constant *AtomicHelperFn); 1090 1091 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1092 ObjCMethodDecl *MD, bool ctor); 1093 1094 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1095 /// for the given property. 1096 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1097 const ObjCPropertyImplDecl *PID); 1098 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1099 const ObjCPropertyImplDecl *propImpl, 1100 llvm::Constant *AtomicHelperFn); 1101 bool IndirectObjCSetterArg(const CGFunctionInfo &FI); 1102 bool IvarTypeWithAggrGCObjects(QualType Ty); 1103 1104 //===--------------------------------------------------------------------===// 1105 // Block Bits 1106 //===--------------------------------------------------------------------===// 1107 1108 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1109 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 1110 static void destroyBlockInfos(CGBlockInfo *info); 1111 llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *, 1112 const CGBlockInfo &Info, 1113 llvm::StructType *, 1114 llvm::Constant *BlockVarLayout); 1115 1116 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1117 const CGBlockInfo &Info, 1118 const DeclMapTy &ldm, 1119 bool IsLambdaConversionToBlock); 1120 1121 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1122 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1123 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1124 const ObjCPropertyImplDecl *PID); 1125 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1126 const ObjCPropertyImplDecl *PID); 1127 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1128 1129 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1130 1131 class AutoVarEmission; 1132 1133 void emitByrefStructureInit(const AutoVarEmission &emission); 1134 void enterByrefCleanup(const AutoVarEmission &emission); 1135 1136 llvm::Value *LoadBlockStruct() { 1137 assert(BlockPointer && "no block pointer set!"); 1138 return BlockPointer; 1139 } 1140 1141 void AllocateBlockCXXThisPointer(const CXXThisExpr *E); 1142 void AllocateBlockDecl(const DeclRefExpr *E); 1143 llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1144 llvm::Type *BuildByRefType(const VarDecl *var); 1145 1146 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1147 const CGFunctionInfo &FnInfo); 1148 void StartFunction(GlobalDecl GD, 1149 QualType RetTy, 1150 llvm::Function *Fn, 1151 const CGFunctionInfo &FnInfo, 1152 const FunctionArgList &Args, 1153 SourceLocation StartLoc); 1154 1155 void EmitConstructorBody(FunctionArgList &Args); 1156 void EmitDestructorBody(FunctionArgList &Args); 1157 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1158 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1159 1160 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1161 CallArgList &CallArgs); 1162 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1163 void EmitLambdaBlockInvokeBody(); 1164 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1165 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1166 1167 /// EmitReturnBlock - Emit the unified return block, trying to avoid its 1168 /// emission when possible. 1169 void EmitReturnBlock(); 1170 1171 /// FinishFunction - Complete IR generation of the current function. It is 1172 /// legal to call this function even if there is no current insertion point. 1173 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1174 1175 void StartThunk(llvm::Function *Fn, GlobalDecl GD, const CGFunctionInfo &FnInfo); 1176 1177 void EmitCallAndReturnForThunk(GlobalDecl GD, llvm::Value *Callee, 1178 const ThunkInfo *Thunk); 1179 1180 /// GenerateThunk - Generate a thunk for the given method. 1181 void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1182 GlobalDecl GD, const ThunkInfo &Thunk); 1183 1184 void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1185 GlobalDecl GD, const ThunkInfo &Thunk); 1186 1187 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1188 FunctionArgList &Args); 1189 1190 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init, 1191 ArrayRef<VarDecl *> ArrayIndexes); 1192 1193 /// InitializeVTablePointer - Initialize the vtable pointer of the given 1194 /// subobject. 1195 /// 1196 void InitializeVTablePointer(BaseSubobject Base, 1197 const CXXRecordDecl *NearestVBase, 1198 CharUnits OffsetFromNearestVBase, 1199 const CXXRecordDecl *VTableClass); 1200 1201 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1202 void InitializeVTablePointers(BaseSubobject Base, 1203 const CXXRecordDecl *NearestVBase, 1204 CharUnits OffsetFromNearestVBase, 1205 bool BaseIsNonVirtualPrimaryBase, 1206 const CXXRecordDecl *VTableClass, 1207 VisitedVirtualBasesSetTy& VBases); 1208 1209 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1210 1211 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1212 /// to by This. 1213 llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty); 1214 1215 1216 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1217 /// expr can be devirtualized. 1218 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1219 const CXXMethodDecl *MD); 1220 1221 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1222 /// given phase of destruction for a destructor. The end result 1223 /// should call destructors on members and base classes in reverse 1224 /// order of their construction. 1225 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1226 1227 /// ShouldInstrumentFunction - Return true if the current function should be 1228 /// instrumented with __cyg_profile_func_* calls 1229 bool ShouldInstrumentFunction(); 1230 1231 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1232 /// instrumentation function with the current function and the call site, if 1233 /// function instrumentation is enabled. 1234 void EmitFunctionInstrumentation(const char *Fn); 1235 1236 /// EmitMCountInstrumentation - Emit call to .mcount. 1237 void EmitMCountInstrumentation(); 1238 1239 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1240 /// arguments for the given function. This is also responsible for naming the 1241 /// LLVM function arguments. 1242 void EmitFunctionProlog(const CGFunctionInfo &FI, 1243 llvm::Function *Fn, 1244 const FunctionArgList &Args); 1245 1246 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1247 /// given temporary. 1248 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1249 SourceLocation EndLoc); 1250 1251 /// EmitStartEHSpec - Emit the start of the exception spec. 1252 void EmitStartEHSpec(const Decl *D); 1253 1254 /// EmitEndEHSpec - Emit the end of the exception spec. 1255 void EmitEndEHSpec(const Decl *D); 1256 1257 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1258 llvm::BasicBlock *getTerminateLandingPad(); 1259 1260 /// getTerminateHandler - Return a handler (not a landing pad, just 1261 /// a catch handler) that just calls terminate. This is used when 1262 /// a terminate scope encloses a try. 1263 llvm::BasicBlock *getTerminateHandler(); 1264 1265 llvm::Type *ConvertTypeForMem(QualType T); 1266 llvm::Type *ConvertType(QualType T); 1267 llvm::Type *ConvertType(const TypeDecl *T) { 1268 return ConvertType(getContext().getTypeDeclType(T)); 1269 } 1270 1271 /// LoadObjCSelf - Load the value of self. This function is only valid while 1272 /// generating code for an Objective-C method. 1273 llvm::Value *LoadObjCSelf(); 1274 1275 /// TypeOfSelfObject - Return type of object that this self represents. 1276 QualType TypeOfSelfObject(); 1277 1278 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1279 /// an aggregate LLVM type or is void. 1280 static TypeEvaluationKind getEvaluationKind(QualType T); 1281 1282 static bool hasScalarEvaluationKind(QualType T) { 1283 return getEvaluationKind(T) == TEK_Scalar; 1284 } 1285 1286 static bool hasAggregateEvaluationKind(QualType T) { 1287 return getEvaluationKind(T) == TEK_Aggregate; 1288 } 1289 1290 /// createBasicBlock - Create an LLVM basic block. 1291 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1292 llvm::Function *parent = 0, 1293 llvm::BasicBlock *before = 0) { 1294 #ifdef NDEBUG 1295 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1296 #else 1297 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1298 #endif 1299 } 1300 1301 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1302 /// label maps to. 1303 JumpDest getJumpDestForLabel(const LabelDecl *S); 1304 1305 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1306 /// another basic block, simplify it. This assumes that no other code could 1307 /// potentially reference the basic block. 1308 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1309 1310 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1311 /// adding a fall-through branch from the current insert block if 1312 /// necessary. It is legal to call this function even if there is no current 1313 /// insertion point. 1314 /// 1315 /// IsFinished - If true, indicates that the caller has finished emitting 1316 /// branches to the given block and does not expect to emit code into it. This 1317 /// means the block can be ignored if it is unreachable. 1318 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1319 1320 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1321 /// near its uses, and leave the insertion point in it. 1322 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1323 1324 /// EmitBranch - Emit a branch to the specified basic block from the current 1325 /// insert block, taking care to avoid creation of branches from dummy 1326 /// blocks. It is legal to call this function even if there is no current 1327 /// insertion point. 1328 /// 1329 /// This function clears the current insertion point. The caller should follow 1330 /// calls to this function with calls to Emit*Block prior to generation new 1331 /// code. 1332 void EmitBranch(llvm::BasicBlock *Block); 1333 1334 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1335 /// indicates that the current code being emitted is unreachable. 1336 bool HaveInsertPoint() const { 1337 return Builder.GetInsertBlock() != 0; 1338 } 1339 1340 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1341 /// emitted IR has a place to go. Note that by definition, if this function 1342 /// creates a block then that block is unreachable; callers may do better to 1343 /// detect when no insertion point is defined and simply skip IR generation. 1344 void EnsureInsertPoint() { 1345 if (!HaveInsertPoint()) 1346 EmitBlock(createBasicBlock()); 1347 } 1348 1349 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1350 /// specified stmt yet. 1351 void ErrorUnsupported(const Stmt *S, const char *Type); 1352 1353 //===--------------------------------------------------------------------===// 1354 // Helpers 1355 //===--------------------------------------------------------------------===// 1356 1357 LValue MakeAddrLValue(llvm::Value *V, QualType T, 1358 CharUnits Alignment = CharUnits()) { 1359 return LValue::MakeAddr(V, T, Alignment, getContext(), 1360 CGM.getTBAAInfo(T)); 1361 } 1362 1363 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 1364 CharUnits Alignment; 1365 if (!T->isIncompleteType()) 1366 Alignment = getContext().getTypeAlignInChars(T); 1367 return LValue::MakeAddr(V, T, Alignment, getContext(), 1368 CGM.getTBAAInfo(T)); 1369 } 1370 1371 /// CreateTempAlloca - This creates a alloca and inserts it into the entry 1372 /// block. The caller is responsible for setting an appropriate alignment on 1373 /// the alloca. 1374 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, 1375 const Twine &Name = "tmp"); 1376 1377 /// InitTempAlloca - Provide an initial value for the given alloca. 1378 void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value); 1379 1380 /// CreateIRTemp - Create a temporary IR object of the given type, with 1381 /// appropriate alignment. This routine should only be used when an temporary 1382 /// value needs to be stored into an alloca (for example, to avoid explicit 1383 /// PHI construction), but the type is the IR type, not the type appropriate 1384 /// for storing in memory. 1385 llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1386 1387 /// CreateMemTemp - Create a temporary memory object of the given type, with 1388 /// appropriate alignment. 1389 llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp"); 1390 1391 /// CreateAggTemp - Create a temporary memory object for the given 1392 /// aggregate type. 1393 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 1394 CharUnits Alignment = getContext().getTypeAlignInChars(T); 1395 return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment, 1396 T.getQualifiers(), 1397 AggValueSlot::IsNotDestructed, 1398 AggValueSlot::DoesNotNeedGCBarriers, 1399 AggValueSlot::IsNotAliased); 1400 } 1401 1402 /// CreateInAllocaTmp - Create a temporary memory object for the given 1403 /// aggregate type. 1404 AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca"); 1405 1406 /// Emit a cast to void* in the appropriate address space. 1407 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 1408 1409 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 1410 /// expression and compare the result against zero, returning an Int1Ty value. 1411 llvm::Value *EvaluateExprAsBool(const Expr *E); 1412 1413 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 1414 void EmitIgnoredExpr(const Expr *E); 1415 1416 /// EmitAnyExpr - Emit code to compute the specified expression which can have 1417 /// any type. The result is returned as an RValue struct. If this is an 1418 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 1419 /// the result should be returned. 1420 /// 1421 /// \param ignoreResult True if the resulting value isn't used. 1422 RValue EmitAnyExpr(const Expr *E, 1423 AggValueSlot aggSlot = AggValueSlot::ignored(), 1424 bool ignoreResult = false); 1425 1426 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 1427 // or the value of the expression, depending on how va_list is defined. 1428 llvm::Value *EmitVAListRef(const Expr *E); 1429 1430 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will 1431 /// always be accessible even if no aggregate location is provided. 1432 RValue EmitAnyExprToTemp(const Expr *E); 1433 1434 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 1435 /// arbitrary expression into the given memory location. 1436 void EmitAnyExprToMem(const Expr *E, llvm::Value *Location, 1437 Qualifiers Quals, bool IsInitializer); 1438 1439 /// EmitExprAsInit - Emits the code necessary to initialize a 1440 /// location in memory with the given initializer. 1441 void EmitExprAsInit(const Expr *init, const ValueDecl *D, 1442 LValue lvalue, bool capturedByInit); 1443 1444 /// hasVolatileMember - returns true if aggregate type has a volatile 1445 /// member. 1446 bool hasVolatileMember(QualType T) { 1447 if (const RecordType *RT = T->getAs<RecordType>()) { 1448 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 1449 return RD->hasVolatileMember(); 1450 } 1451 return false; 1452 } 1453 /// EmitAggregateCopy - Emit an aggregate assignment. 1454 /// 1455 /// The difference to EmitAggregateCopy is that tail padding is not copied. 1456 /// This is required for correctness when assigning non-POD structures in C++. 1457 void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1458 QualType EltTy) { 1459 bool IsVolatile = hasVolatileMember(EltTy); 1460 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(), 1461 true); 1462 } 1463 1464 /// EmitAggregateCopy - Emit an aggregate copy. 1465 /// 1466 /// \param isVolatile - True iff either the source or the destination is 1467 /// volatile. 1468 /// \param isAssignment - If false, allow padding to be copied. This often 1469 /// yields more efficient. 1470 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 1471 QualType EltTy, bool isVolatile=false, 1472 CharUnits Alignment = CharUnits::Zero(), 1473 bool isAssignment = false); 1474 1475 /// StartBlock - Start new block named N. If insert block is a dummy block 1476 /// then reuse it. 1477 void StartBlock(const char *N); 1478 1479 /// GetAddrOfLocalVar - Return the address of a local variable. 1480 llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) { 1481 llvm::Value *Res = LocalDeclMap[VD]; 1482 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!"); 1483 return Res; 1484 } 1485 1486 /// getOpaqueLValueMapping - Given an opaque value expression (which 1487 /// must be mapped to an l-value), return its mapping. 1488 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 1489 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 1490 1491 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 1492 it = OpaqueLValues.find(e); 1493 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 1494 return it->second; 1495 } 1496 1497 /// getOpaqueRValueMapping - Given an opaque value expression (which 1498 /// must be mapped to an r-value), return its mapping. 1499 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 1500 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 1501 1502 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 1503 it = OpaqueRValues.find(e); 1504 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 1505 return it->second; 1506 } 1507 1508 /// getAccessedFieldNo - Given an encoded value and a result number, return 1509 /// the input field number being accessed. 1510 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 1511 1512 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 1513 llvm::BasicBlock *GetIndirectGotoBlock(); 1514 1515 /// EmitNullInitialization - Generate code to set a value of the given type to 1516 /// null, If the type contains data member pointers, they will be initialized 1517 /// to -1 in accordance with the Itanium C++ ABI. 1518 void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty); 1519 1520 // EmitVAArg - Generate code to get an argument from the passed in pointer 1521 // and update it accordingly. The return value is a pointer to the argument. 1522 // FIXME: We should be able to get rid of this method and use the va_arg 1523 // instruction in LLVM instead once it works well enough. 1524 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty); 1525 1526 /// emitArrayLength - Compute the length of an array, even if it's a 1527 /// VLA, and drill down to the base element type. 1528 llvm::Value *emitArrayLength(const ArrayType *arrayType, 1529 QualType &baseType, 1530 llvm::Value *&addr); 1531 1532 /// EmitVLASize - Capture all the sizes for the VLA expressions in 1533 /// the given variably-modified type and store them in the VLASizeMap. 1534 /// 1535 /// This function can be called with a null (unreachable) insert point. 1536 void EmitVariablyModifiedType(QualType Ty); 1537 1538 /// getVLASize - Returns an LLVM value that corresponds to the size, 1539 /// in non-variably-sized elements, of a variable length array type, 1540 /// plus that largest non-variably-sized element type. Assumes that 1541 /// the type has already been emitted with EmitVariablyModifiedType. 1542 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 1543 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 1544 1545 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 1546 /// generating code for an C++ member function. 1547 llvm::Value *LoadCXXThis() { 1548 assert(CXXThisValue && "no 'this' value for this function"); 1549 return CXXThisValue; 1550 } 1551 1552 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 1553 /// virtual bases. 1554 // FIXME: Every place that calls LoadCXXVTT is something 1555 // that needs to be abstracted properly. 1556 llvm::Value *LoadCXXVTT() { 1557 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 1558 return CXXStructorImplicitParamValue; 1559 } 1560 1561 /// LoadCXXStructorImplicitParam - Load the implicit parameter 1562 /// for a constructor/destructor. 1563 llvm::Value *LoadCXXStructorImplicitParam() { 1564 assert(CXXStructorImplicitParamValue && 1565 "no implicit argument value for this function"); 1566 return CXXStructorImplicitParamValue; 1567 } 1568 1569 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 1570 /// complete class to the given direct base. 1571 llvm::Value * 1572 GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value, 1573 const CXXRecordDecl *Derived, 1574 const CXXRecordDecl *Base, 1575 bool BaseIsVirtual); 1576 1577 /// GetAddressOfBaseClass - This function will add the necessary delta to the 1578 /// load of 'this' and returns address of the base class. 1579 llvm::Value *GetAddressOfBaseClass(llvm::Value *Value, 1580 const CXXRecordDecl *Derived, 1581 CastExpr::path_const_iterator PathBegin, 1582 CastExpr::path_const_iterator PathEnd, 1583 bool NullCheckValue); 1584 1585 llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value, 1586 const CXXRecordDecl *Derived, 1587 CastExpr::path_const_iterator PathBegin, 1588 CastExpr::path_const_iterator PathEnd, 1589 bool NullCheckValue); 1590 1591 /// GetVTTParameter - Return the VTT parameter that should be passed to a 1592 /// base constructor/destructor with virtual bases. 1593 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 1594 /// to ItaniumCXXABI.cpp together with all the references to VTT. 1595 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 1596 bool Delegating); 1597 1598 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1599 CXXCtorType CtorType, 1600 const FunctionArgList &Args, 1601 SourceLocation Loc); 1602 // It's important not to confuse this and the previous function. Delegating 1603 // constructors are the C++0x feature. The constructor delegate optimization 1604 // is used to reduce duplication in the base and complete consturctors where 1605 // they are substantially the same. 1606 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1607 const FunctionArgList &Args); 1608 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 1609 bool ForVirtualBase, bool Delegating, 1610 llvm::Value *This, 1611 CallExpr::const_arg_iterator ArgBeg, 1612 CallExpr::const_arg_iterator ArgEnd); 1613 1614 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1615 llvm::Value *This, llvm::Value *Src, 1616 CallExpr::const_arg_iterator ArgBeg, 1617 CallExpr::const_arg_iterator ArgEnd); 1618 1619 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1620 const ConstantArrayType *ArrayTy, 1621 llvm::Value *ArrayPtr, 1622 CallExpr::const_arg_iterator ArgBeg, 1623 CallExpr::const_arg_iterator ArgEnd, 1624 bool ZeroInitialization = false); 1625 1626 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1627 llvm::Value *NumElements, 1628 llvm::Value *ArrayPtr, 1629 CallExpr::const_arg_iterator ArgBeg, 1630 CallExpr::const_arg_iterator ArgEnd, 1631 bool ZeroInitialization = false); 1632 1633 static Destroyer destroyCXXObject; 1634 1635 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 1636 bool ForVirtualBase, bool Delegating, 1637 llvm::Value *This); 1638 1639 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 1640 llvm::Value *NewPtr, llvm::Value *NumElements); 1641 1642 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 1643 llvm::Value *Ptr); 1644 1645 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 1646 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 1647 1648 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 1649 QualType DeleteTy); 1650 1651 llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E); 1652 llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE); 1653 llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E); 1654 1655 /// \brief Situations in which we might emit a check for the suitability of a 1656 /// pointer or glvalue. 1657 enum TypeCheckKind { 1658 /// Checking the operand of a load. Must be suitably sized and aligned. 1659 TCK_Load, 1660 /// Checking the destination of a store. Must be suitably sized and aligned. 1661 TCK_Store, 1662 /// Checking the bound value in a reference binding. Must be suitably sized 1663 /// and aligned, but is not required to refer to an object (until the 1664 /// reference is used), per core issue 453. 1665 TCK_ReferenceBinding, 1666 /// Checking the object expression in a non-static data member access. Must 1667 /// be an object within its lifetime. 1668 TCK_MemberAccess, 1669 /// Checking the 'this' pointer for a call to a non-static member function. 1670 /// Must be an object within its lifetime. 1671 TCK_MemberCall, 1672 /// Checking the 'this' pointer for a constructor call. 1673 TCK_ConstructorCall, 1674 /// Checking the operand of a static_cast to a derived pointer type. Must be 1675 /// null or an object within its lifetime. 1676 TCK_DowncastPointer, 1677 /// Checking the operand of a static_cast to a derived reference type. Must 1678 /// be an object within its lifetime. 1679 TCK_DowncastReference 1680 }; 1681 1682 /// \brief Emit a check that \p V is the address of storage of the 1683 /// appropriate size and alignment for an object of type \p Type. 1684 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 1685 QualType Type, CharUnits Alignment = CharUnits::Zero()); 1686 1687 /// \brief Emit a check that \p Base points into an array object, which 1688 /// we can access at index \p Index. \p Accessed should be \c false if we 1689 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 1690 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 1691 QualType IndexType, bool Accessed); 1692 1693 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 1694 bool isInc, bool isPre); 1695 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 1696 bool isInc, bool isPre); 1697 //===--------------------------------------------------------------------===// 1698 // Declaration Emission 1699 //===--------------------------------------------------------------------===// 1700 1701 /// EmitDecl - Emit a declaration. 1702 /// 1703 /// This function can be called with a null (unreachable) insert point. 1704 void EmitDecl(const Decl &D); 1705 1706 /// EmitVarDecl - Emit a local variable declaration. 1707 /// 1708 /// This function can be called with a null (unreachable) insert point. 1709 void EmitVarDecl(const VarDecl &D); 1710 1711 void EmitScalarInit(const Expr *init, const ValueDecl *D, 1712 LValue lvalue, bool capturedByInit); 1713 void EmitScalarInit(llvm::Value *init, LValue lvalue); 1714 1715 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 1716 llvm::Value *Address); 1717 1718 /// EmitAutoVarDecl - Emit an auto variable declaration. 1719 /// 1720 /// This function can be called with a null (unreachable) insert point. 1721 void EmitAutoVarDecl(const VarDecl &D); 1722 1723 class AutoVarEmission { 1724 friend class CodeGenFunction; 1725 1726 const VarDecl *Variable; 1727 1728 /// The alignment of the variable. 1729 CharUnits Alignment; 1730 1731 /// The address of the alloca. Null if the variable was emitted 1732 /// as a global constant. 1733 llvm::Value *Address; 1734 1735 llvm::Value *NRVOFlag; 1736 1737 /// True if the variable is a __block variable. 1738 bool IsByRef; 1739 1740 /// True if the variable is of aggregate type and has a constant 1741 /// initializer. 1742 bool IsConstantAggregate; 1743 1744 /// Non-null if we should use lifetime annotations. 1745 llvm::Value *SizeForLifetimeMarkers; 1746 1747 struct Invalid {}; 1748 AutoVarEmission(Invalid) : Variable(0) {} 1749 1750 AutoVarEmission(const VarDecl &variable) 1751 : Variable(&variable), Address(0), NRVOFlag(0), 1752 IsByRef(false), IsConstantAggregate(false), 1753 SizeForLifetimeMarkers(0) {} 1754 1755 bool wasEmittedAsGlobal() const { return Address == 0; } 1756 1757 public: 1758 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 1759 1760 bool useLifetimeMarkers() const { return SizeForLifetimeMarkers != 0; } 1761 llvm::Value *getSizeForLifetimeMarkers() const { 1762 assert(useLifetimeMarkers()); 1763 return SizeForLifetimeMarkers; 1764 } 1765 1766 /// Returns the raw, allocated address, which is not necessarily 1767 /// the address of the object itself. 1768 llvm::Value *getAllocatedAddress() const { 1769 return Address; 1770 } 1771 1772 /// Returns the address of the object within this declaration. 1773 /// Note that this does not chase the forwarding pointer for 1774 /// __block decls. 1775 llvm::Value *getObjectAddress(CodeGenFunction &CGF) const { 1776 if (!IsByRef) return Address; 1777 1778 return CGF.Builder.CreateStructGEP(Address, 1779 CGF.getByRefValueLLVMField(Variable), 1780 Variable->getNameAsString()); 1781 } 1782 }; 1783 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 1784 void EmitAutoVarInit(const AutoVarEmission &emission); 1785 void EmitAutoVarCleanups(const AutoVarEmission &emission); 1786 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 1787 QualType::DestructionKind dtorKind); 1788 1789 void EmitStaticVarDecl(const VarDecl &D, 1790 llvm::GlobalValue::LinkageTypes Linkage); 1791 1792 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 1793 void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer, 1794 unsigned ArgNo); 1795 1796 /// protectFromPeepholes - Protect a value that we're intending to 1797 /// store to the side, but which will probably be used later, from 1798 /// aggressive peepholing optimizations that might delete it. 1799 /// 1800 /// Pass the result to unprotectFromPeepholes to declare that 1801 /// protection is no longer required. 1802 /// 1803 /// There's no particular reason why this shouldn't apply to 1804 /// l-values, it's just that no existing peepholes work on pointers. 1805 PeepholeProtection protectFromPeepholes(RValue rvalue); 1806 void unprotectFromPeepholes(PeepholeProtection protection); 1807 1808 //===--------------------------------------------------------------------===// 1809 // Statement Emission 1810 //===--------------------------------------------------------------------===// 1811 1812 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 1813 void EmitStopPoint(const Stmt *S); 1814 1815 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 1816 /// this function even if there is no current insertion point. 1817 /// 1818 /// This function may clear the current insertion point; callers should use 1819 /// EnsureInsertPoint if they wish to subsequently generate code without first 1820 /// calling EmitBlock, EmitBranch, or EmitStmt. 1821 void EmitStmt(const Stmt *S); 1822 1823 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 1824 /// necessarily require an insertion point or debug information; typically 1825 /// because the statement amounts to a jump or a container of other 1826 /// statements. 1827 /// 1828 /// \return True if the statement was handled. 1829 bool EmitSimpleStmt(const Stmt *S); 1830 1831 llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 1832 AggValueSlot AVS = AggValueSlot::ignored()); 1833 llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S, 1834 bool GetLast = false, 1835 AggValueSlot AVS = 1836 AggValueSlot::ignored()); 1837 1838 /// EmitLabel - Emit the block for the given label. It is legal to call this 1839 /// function even if there is no current insertion point. 1840 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 1841 1842 void EmitLabelStmt(const LabelStmt &S); 1843 void EmitAttributedStmt(const AttributedStmt &S); 1844 void EmitGotoStmt(const GotoStmt &S); 1845 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 1846 void EmitIfStmt(const IfStmt &S); 1847 void EmitWhileStmt(const WhileStmt &S); 1848 void EmitDoStmt(const DoStmt &S); 1849 void EmitForStmt(const ForStmt &S); 1850 void EmitReturnStmt(const ReturnStmt &S); 1851 void EmitDeclStmt(const DeclStmt &S); 1852 void EmitBreakStmt(const BreakStmt &S); 1853 void EmitContinueStmt(const ContinueStmt &S); 1854 void EmitSwitchStmt(const SwitchStmt &S); 1855 void EmitDefaultStmt(const DefaultStmt &S); 1856 void EmitCaseStmt(const CaseStmt &S); 1857 void EmitCaseStmtRange(const CaseStmt &S); 1858 void EmitAsmStmt(const AsmStmt &S); 1859 1860 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 1861 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 1862 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 1863 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 1864 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 1865 1866 llvm::Constant *getUnwindResumeFn(); 1867 llvm::Constant *getUnwindResumeOrRethrowFn(); 1868 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1869 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 1870 1871 void EmitCXXTryStmt(const CXXTryStmt &S); 1872 void EmitSEHTryStmt(const SEHTryStmt &S); 1873 void EmitCXXForRangeStmt(const CXXForRangeStmt &S); 1874 1875 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 1876 llvm::Function *GenerateCapturedStmtFunction(const CapturedDecl *CD, 1877 const RecordDecl *RD, 1878 SourceLocation Loc); 1879 1880 //===--------------------------------------------------------------------===// 1881 // LValue Expression Emission 1882 //===--------------------------------------------------------------------===// 1883 1884 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 1885 RValue GetUndefRValue(QualType Ty); 1886 1887 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 1888 /// and issue an ErrorUnsupported style diagnostic (using the 1889 /// provided Name). 1890 RValue EmitUnsupportedRValue(const Expr *E, 1891 const char *Name); 1892 1893 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 1894 /// an ErrorUnsupported style diagnostic (using the provided Name). 1895 LValue EmitUnsupportedLValue(const Expr *E, 1896 const char *Name); 1897 1898 /// EmitLValue - Emit code to compute a designator that specifies the location 1899 /// of the expression. 1900 /// 1901 /// This can return one of two things: a simple address or a bitfield 1902 /// reference. In either case, the LLVM Value* in the LValue structure is 1903 /// guaranteed to be an LLVM pointer type. 1904 /// 1905 /// If this returns a bitfield reference, nothing about the pointee type of 1906 /// the LLVM value is known: For example, it may not be a pointer to an 1907 /// integer. 1908 /// 1909 /// If this returns a normal address, and if the lvalue's C type is fixed 1910 /// size, this method guarantees that the returned pointer type will point to 1911 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 1912 /// variable length type, this is not possible. 1913 /// 1914 LValue EmitLValue(const Expr *E); 1915 1916 /// \brief Same as EmitLValue but additionally we generate checking code to 1917 /// guard against undefined behavior. This is only suitable when we know 1918 /// that the address will be used to access the object. 1919 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 1920 1921 RValue convertTempToRValue(llvm::Value *addr, QualType type, 1922 SourceLocation Loc); 1923 1924 void EmitAtomicInit(Expr *E, LValue lvalue); 1925 1926 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 1927 AggValueSlot slot = AggValueSlot::ignored()); 1928 1929 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 1930 1931 /// EmitToMemory - Change a scalar value from its value 1932 /// representation to its in-memory representation. 1933 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 1934 1935 /// EmitFromMemory - Change a scalar value from its memory 1936 /// representation to its value representation. 1937 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 1938 1939 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1940 /// care to appropriately convert from the memory representation to 1941 /// the LLVM value representation. 1942 llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile, 1943 unsigned Alignment, QualType Ty, 1944 SourceLocation Loc, 1945 llvm::MDNode *TBAAInfo = 0, 1946 QualType TBAABaseTy = QualType(), 1947 uint64_t TBAAOffset = 0); 1948 1949 /// EmitLoadOfScalar - Load a scalar value from an address, taking 1950 /// care to appropriately convert from the memory representation to 1951 /// the LLVM value representation. The l-value must be a simple 1952 /// l-value. 1953 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 1954 1955 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1956 /// care to appropriately convert from the memory representation to 1957 /// the LLVM value representation. 1958 void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr, 1959 bool Volatile, unsigned Alignment, QualType Ty, 1960 llvm::MDNode *TBAAInfo = 0, bool isInit = false, 1961 QualType TBAABaseTy = QualType(), 1962 uint64_t TBAAOffset = 0); 1963 1964 /// EmitStoreOfScalar - Store a scalar value to an address, taking 1965 /// care to appropriately convert from the memory representation to 1966 /// the LLVM value representation. The l-value must be a simple 1967 /// l-value. The isInit flag indicates whether this is an initialization. 1968 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 1969 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 1970 1971 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 1972 /// this method emits the address of the lvalue, then loads the result as an 1973 /// rvalue, returning the rvalue. 1974 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 1975 RValue EmitLoadOfExtVectorElementLValue(LValue V); 1976 RValue EmitLoadOfBitfieldLValue(LValue LV); 1977 1978 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 1979 /// lvalue, where both are guaranteed to the have the same type, and that type 1980 /// is 'Ty'. 1981 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false); 1982 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 1983 1984 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 1985 /// as EmitStoreThroughLValue. 1986 /// 1987 /// \param Result [out] - If non-null, this will be set to a Value* for the 1988 /// bit-field contents after the store, appropriate for use as the result of 1989 /// an assignment to the bit-field. 1990 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 1991 llvm::Value **Result=0); 1992 1993 /// Emit an l-value for an assignment (simple or compound) of complex type. 1994 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 1995 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 1996 LValue EmitScalarCompooundAssignWithComplex(const CompoundAssignOperator *E, 1997 llvm::Value *&Result); 1998 1999 // Note: only available for agg return types 2000 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 2001 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 2002 // Note: only available for agg return types 2003 LValue EmitCallExprLValue(const CallExpr *E); 2004 // Note: only available for agg return types 2005 LValue EmitVAArgExprLValue(const VAArgExpr *E); 2006 LValue EmitDeclRefLValue(const DeclRefExpr *E); 2007 LValue EmitStringLiteralLValue(const StringLiteral *E); 2008 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 2009 LValue EmitPredefinedLValue(const PredefinedExpr *E); 2010 LValue EmitUnaryOpLValue(const UnaryOperator *E); 2011 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 2012 bool Accessed = false); 2013 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 2014 LValue EmitMemberExpr(const MemberExpr *E); 2015 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 2016 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 2017 LValue EmitInitListLValue(const InitListExpr *E); 2018 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 2019 LValue EmitCastLValue(const CastExpr *E); 2020 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 2021 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 2022 2023 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 2024 2025 class ConstantEmission { 2026 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 2027 ConstantEmission(llvm::Constant *C, bool isReference) 2028 : ValueAndIsReference(C, isReference) {} 2029 public: 2030 ConstantEmission() {} 2031 static ConstantEmission forReference(llvm::Constant *C) { 2032 return ConstantEmission(C, true); 2033 } 2034 static ConstantEmission forValue(llvm::Constant *C) { 2035 return ConstantEmission(C, false); 2036 } 2037 2038 LLVM_EXPLICIT operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; } 2039 2040 bool isReference() const { return ValueAndIsReference.getInt(); } 2041 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 2042 assert(isReference()); 2043 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 2044 refExpr->getType()); 2045 } 2046 2047 llvm::Constant *getValue() const { 2048 assert(!isReference()); 2049 return ValueAndIsReference.getPointer(); 2050 } 2051 }; 2052 2053 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 2054 2055 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 2056 AggValueSlot slot = AggValueSlot::ignored()); 2057 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 2058 2059 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 2060 const ObjCIvarDecl *Ivar); 2061 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 2062 LValue EmitLValueForLambdaField(const FieldDecl *Field); 2063 2064 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 2065 /// if the Field is a reference, this will return the address of the reference 2066 /// and not the address of the value stored in the reference. 2067 LValue EmitLValueForFieldInitialization(LValue Base, 2068 const FieldDecl* Field); 2069 2070 LValue EmitLValueForIvar(QualType ObjectTy, 2071 llvm::Value* Base, const ObjCIvarDecl *Ivar, 2072 unsigned CVRQualifiers); 2073 2074 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 2075 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 2076 LValue EmitLambdaLValue(const LambdaExpr *E); 2077 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 2078 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 2079 2080 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 2081 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 2082 LValue EmitStmtExprLValue(const StmtExpr *E); 2083 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 2084 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 2085 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init); 2086 2087 //===--------------------------------------------------------------------===// 2088 // Scalar Expression Emission 2089 //===--------------------------------------------------------------------===// 2090 2091 /// EmitCall - Generate a call of the given function, expecting the given 2092 /// result type, and using the given argument list which specifies both the 2093 /// LLVM arguments and the types they were derived from. 2094 /// 2095 /// \param TargetDecl - If given, the decl of the function in a direct call; 2096 /// used to set attributes on the call (noreturn, etc.). 2097 RValue EmitCall(const CGFunctionInfo &FnInfo, 2098 llvm::Value *Callee, 2099 ReturnValueSlot ReturnValue, 2100 const CallArgList &Args, 2101 const Decl *TargetDecl = 0, 2102 llvm::Instruction **callOrInvoke = 0); 2103 2104 RValue EmitCall(QualType FnType, llvm::Value *Callee, 2105 SourceLocation CallLoc, 2106 ReturnValueSlot ReturnValue, 2107 CallExpr::const_arg_iterator ArgBeg, 2108 CallExpr::const_arg_iterator ArgEnd, 2109 const Decl *TargetDecl = 0); 2110 RValue EmitCallExpr(const CallExpr *E, 2111 ReturnValueSlot ReturnValue = ReturnValueSlot()); 2112 2113 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2114 const Twine &name = ""); 2115 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 2116 ArrayRef<llvm::Value*> args, 2117 const Twine &name = ""); 2118 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2119 const Twine &name = ""); 2120 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 2121 ArrayRef<llvm::Value*> args, 2122 const Twine &name = ""); 2123 2124 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2125 ArrayRef<llvm::Value *> Args, 2126 const Twine &Name = ""); 2127 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 2128 const Twine &Name = ""); 2129 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2130 ArrayRef<llvm::Value*> args, 2131 const Twine &name = ""); 2132 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 2133 const Twine &name = ""); 2134 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 2135 ArrayRef<llvm::Value*> args); 2136 2137 llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 2138 NestedNameSpecifier *Qual, 2139 llvm::Type *Ty); 2140 2141 llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 2142 CXXDtorType Type, 2143 const CXXRecordDecl *RD); 2144 2145 RValue EmitCXXMemberCall(const CXXMethodDecl *MD, 2146 SourceLocation CallLoc, 2147 llvm::Value *Callee, 2148 ReturnValueSlot ReturnValue, 2149 llvm::Value *This, 2150 llvm::Value *ImplicitParam, 2151 QualType ImplicitParamTy, 2152 CallExpr::const_arg_iterator ArgBeg, 2153 CallExpr::const_arg_iterator ArgEnd); 2154 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 2155 ReturnValueSlot ReturnValue); 2156 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 2157 ReturnValueSlot ReturnValue); 2158 2159 llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 2160 const CXXMethodDecl *MD, 2161 llvm::Value *This); 2162 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 2163 const CXXMethodDecl *MD, 2164 ReturnValueSlot ReturnValue); 2165 2166 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 2167 ReturnValueSlot ReturnValue); 2168 2169 2170 RValue EmitBuiltinExpr(const FunctionDecl *FD, 2171 unsigned BuiltinID, const CallExpr *E); 2172 2173 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 2174 2175 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 2176 /// is unhandled by the current target. 2177 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2178 2179 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 2180 const llvm::CmpInst::Predicate Fp, 2181 const llvm::CmpInst::Predicate Ip, 2182 const llvm::Twine &Name = ""); 2183 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty); 2184 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2185 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2186 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 2187 SmallVectorImpl<llvm::Value *> &Ops, 2188 llvm::Value *Align = 0); 2189 llvm::Value *EmitNeonCall(llvm::Function *F, 2190 SmallVectorImpl<llvm::Value*> &O, 2191 const char *name, 2192 unsigned shift = 0, bool rightshift = false); 2193 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 2194 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 2195 bool negateForRightShift); 2196 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 2197 llvm::Type *Ty, bool usgn, const char *name); 2198 2199 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 2200 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2201 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 2202 2203 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 2204 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 2205 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 2206 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 2207 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 2208 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 2209 const ObjCMethodDecl *MethodWithObjects); 2210 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 2211 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 2212 ReturnValueSlot Return = ReturnValueSlot()); 2213 2214 /// Retrieves the default cleanup kind for an ARC cleanup. 2215 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 2216 CleanupKind getARCCleanupKind() { 2217 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 2218 ? NormalAndEHCleanup : NormalCleanup; 2219 } 2220 2221 // ARC primitives. 2222 void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr); 2223 void EmitARCDestroyWeak(llvm::Value *addr); 2224 llvm::Value *EmitARCLoadWeak(llvm::Value *addr); 2225 llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr); 2226 llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr, 2227 bool ignored); 2228 void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src); 2229 void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src); 2230 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 2231 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 2232 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 2233 bool resultIgnored); 2234 llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value, 2235 bool resultIgnored); 2236 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 2237 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 2238 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 2239 void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise); 2240 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 2241 llvm::Value *EmitARCAutorelease(llvm::Value *value); 2242 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 2243 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 2244 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 2245 2246 std::pair<LValue,llvm::Value*> 2247 EmitARCStoreAutoreleasing(const BinaryOperator *e); 2248 std::pair<LValue,llvm::Value*> 2249 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 2250 2251 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 2252 2253 llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr); 2254 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 2255 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 2256 2257 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 2258 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 2259 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 2260 2261 void EmitARCIntrinsicUse(llvm::ArrayRef<llvm::Value*> values); 2262 2263 static Destroyer destroyARCStrongImprecise; 2264 static Destroyer destroyARCStrongPrecise; 2265 static Destroyer destroyARCWeak; 2266 2267 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 2268 llvm::Value *EmitObjCAutoreleasePoolPush(); 2269 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 2270 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 2271 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 2272 2273 /// \brief Emits a reference binding to the passed in expression. 2274 RValue EmitReferenceBindingToExpr(const Expr *E); 2275 2276 //===--------------------------------------------------------------------===// 2277 // Expression Emission 2278 //===--------------------------------------------------------------------===// 2279 2280 // Expressions are broken into three classes: scalar, complex, aggregate. 2281 2282 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 2283 /// scalar type, returning the result. 2284 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 2285 2286 /// EmitScalarConversion - Emit a conversion from the specified type to the 2287 /// specified destination type, both of which are LLVM scalar types. 2288 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 2289 QualType DstTy); 2290 2291 /// EmitComplexToScalarConversion - Emit a conversion from the specified 2292 /// complex type to the specified destination type, where the destination type 2293 /// is an LLVM scalar type. 2294 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 2295 QualType DstTy); 2296 2297 2298 /// EmitAggExpr - Emit the computation of the specified expression 2299 /// of aggregate type. The result is computed into the given slot, 2300 /// which may be null to indicate that the value is not needed. 2301 void EmitAggExpr(const Expr *E, AggValueSlot AS); 2302 2303 /// EmitAggExprToLValue - Emit the computation of the specified expression of 2304 /// aggregate type into a temporary LValue. 2305 LValue EmitAggExprToLValue(const Expr *E); 2306 2307 /// EmitGCMemmoveCollectable - Emit special API for structs with object 2308 /// pointers. 2309 void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr, 2310 QualType Ty); 2311 2312 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 2313 /// make sure it survives garbage collection until this point. 2314 void EmitExtendGCLifetime(llvm::Value *object); 2315 2316 /// EmitComplexExpr - Emit the computation of the specified expression of 2317 /// complex type, returning the result. 2318 ComplexPairTy EmitComplexExpr(const Expr *E, 2319 bool IgnoreReal = false, 2320 bool IgnoreImag = false); 2321 2322 /// EmitComplexExprIntoLValue - Emit the given expression of complex 2323 /// type and place its result into the specified l-value. 2324 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 2325 2326 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 2327 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 2328 2329 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 2330 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 2331 2332 /// CreateStaticVarDecl - Create a zero-initialized LLVM global for 2333 /// a static local variable. 2334 llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D, 2335 const char *Separator, 2336 llvm::GlobalValue::LinkageTypes Linkage); 2337 2338 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 2339 /// global variable that has already been created for it. If the initializer 2340 /// has a different type than GV does, this may free GV and return a different 2341 /// one. Otherwise it just returns GV. 2342 llvm::GlobalVariable * 2343 AddInitializerToStaticVarDecl(const VarDecl &D, 2344 llvm::GlobalVariable *GV); 2345 2346 2347 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 2348 /// variable with global storage. 2349 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 2350 bool PerformInit); 2351 2352 /// Call atexit() with a function that passes the given argument to 2353 /// the given function. 2354 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 2355 llvm::Constant *addr); 2356 2357 /// Emit code in this function to perform a guarded variable 2358 /// initialization. Guarded initializations are used when it's not 2359 /// possible to prove that an initialization will be done exactly 2360 /// once, e.g. with a static local variable or a static data member 2361 /// of a class template. 2362 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 2363 bool PerformInit); 2364 2365 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 2366 /// variables. 2367 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 2368 ArrayRef<llvm::Constant *> Decls, 2369 llvm::GlobalVariable *Guard = 0); 2370 2371 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 2372 /// variables. 2373 void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 2374 const std::vector<std::pair<llvm::WeakVH, 2375 llvm::Constant*> > &DtorsAndObjects); 2376 2377 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 2378 const VarDecl *D, 2379 llvm::GlobalVariable *Addr, 2380 bool PerformInit); 2381 2382 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 2383 2384 void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src, 2385 const Expr *Exp); 2386 2387 void enterFullExpression(const ExprWithCleanups *E) { 2388 if (E->getNumObjects() == 0) return; 2389 enterNonTrivialFullExpression(E); 2390 } 2391 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 2392 2393 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 2394 2395 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 2396 2397 RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0); 2398 2399 //===--------------------------------------------------------------------===// 2400 // Annotations Emission 2401 //===--------------------------------------------------------------------===// 2402 2403 /// Emit an annotation call (intrinsic or builtin). 2404 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 2405 llvm::Value *AnnotatedVal, 2406 StringRef AnnotationStr, 2407 SourceLocation Location); 2408 2409 /// Emit local annotations for the local variable V, declared by D. 2410 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 2411 2412 /// Emit field annotations for the given field & value. Returns the 2413 /// annotation result. 2414 llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V); 2415 2416 //===--------------------------------------------------------------------===// 2417 // Internal Helpers 2418 //===--------------------------------------------------------------------===// 2419 2420 /// ContainsLabel - Return true if the statement contains a label in it. If 2421 /// this statement is not executed normally, it not containing a label means 2422 /// that we can just remove the code. 2423 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 2424 2425 /// containsBreak - Return true if the statement contains a break out of it. 2426 /// If the statement (recursively) contains a switch or loop with a break 2427 /// inside of it, this is fine. 2428 static bool containsBreak(const Stmt *S); 2429 2430 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2431 /// to a constant, or if it does but contains a label, return false. If it 2432 /// constant folds return true and set the boolean result in Result. 2433 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result); 2434 2435 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 2436 /// to a constant, or if it does but contains a label, return false. If it 2437 /// constant folds return true and set the folded value. 2438 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result); 2439 2440 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 2441 /// if statement) to the specified blocks. Based on the condition, this might 2442 /// try to simplify the codegen of the conditional based on the branch. 2443 /// TrueCount should be the number of times we expect the condition to 2444 /// evaluate to true based on PGO data. 2445 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 2446 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 2447 2448 /// \brief Emit a description of a type in a format suitable for passing to 2449 /// a runtime sanitizer handler. 2450 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 2451 2452 /// \brief Convert a value into a format suitable for passing to a runtime 2453 /// sanitizer handler. 2454 llvm::Value *EmitCheckValue(llvm::Value *V); 2455 2456 /// \brief Emit a description of a source location in a format suitable for 2457 /// passing to a runtime sanitizer handler. 2458 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 2459 2460 /// \brief Specify under what conditions this check can be recovered 2461 enum CheckRecoverableKind { 2462 /// Always terminate program execution if this check fails 2463 CRK_Unrecoverable, 2464 /// Check supports recovering, allows user to specify which 2465 CRK_Recoverable, 2466 /// Runtime conditionally aborts, always need to support recovery. 2467 CRK_AlwaysRecoverable 2468 }; 2469 2470 /// \brief Create a basic block that will call a handler function in a 2471 /// sanitizer runtime with the provided arguments, and create a conditional 2472 /// branch to it. 2473 void EmitCheck(llvm::Value *Checked, StringRef CheckName, 2474 ArrayRef<llvm::Constant *> StaticArgs, 2475 ArrayRef<llvm::Value *> DynamicArgs, 2476 CheckRecoverableKind Recoverable); 2477 2478 /// \brief Create a basic block that will call the trap intrinsic, and emit a 2479 /// conditional branch to it, for the -ftrapv checks. 2480 void EmitTrapCheck(llvm::Value *Checked); 2481 2482 /// EmitCallArg - Emit a single call argument. 2483 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 2484 2485 /// EmitDelegateCallArg - We are performing a delegate call; that 2486 /// is, the current function is delegating to another one. Produce 2487 /// a r-value suitable for passing the given parameter. 2488 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 2489 SourceLocation loc); 2490 2491 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 2492 /// point operation, expressed as the maximum relative error in ulp. 2493 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 2494 2495 private: 2496 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 2497 void EmitReturnOfRValue(RValue RV, QualType Ty); 2498 2499 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 2500 2501 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 2502 DeferredReplacements; 2503 2504 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 2505 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 2506 /// 2507 /// \param AI - The first function argument of the expansion. 2508 /// \return The argument following the last expanded function 2509 /// argument. 2510 llvm::Function::arg_iterator 2511 ExpandTypeFromArgs(QualType Ty, LValue Dst, 2512 llvm::Function::arg_iterator AI); 2513 2514 /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg 2515 /// Ty, into individual arguments on the provided vector \arg Args. See 2516 /// ABIArgInfo::Expand. 2517 void ExpandTypeToArgs(QualType Ty, RValue Src, 2518 SmallVectorImpl<llvm::Value *> &Args, 2519 llvm::FunctionType *IRFuncTy); 2520 2521 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 2522 const Expr *InputExpr, std::string &ConstraintStr); 2523 2524 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 2525 LValue InputValue, QualType InputType, 2526 std::string &ConstraintStr, 2527 SourceLocation Loc); 2528 2529 public: 2530 /// EmitCallArgs - Emit call arguments for a function. 2531 template <typename T> 2532 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 2533 CallExpr::const_arg_iterator ArgBeg, 2534 CallExpr::const_arg_iterator ArgEnd, 2535 bool ForceColumnInfo = false) { 2536 if (CallArgTypeInfo) { 2537 EmitCallArgs(Args, CallArgTypeInfo->isVariadic(), 2538 CallArgTypeInfo->param_type_begin(), 2539 CallArgTypeInfo->param_type_end(), ArgBeg, ArgEnd, 2540 ForceColumnInfo); 2541 } else { 2542 // T::param_type_iterator might not have a default ctor. 2543 const QualType *NoIter = 0; 2544 EmitCallArgs(Args, /*AllowExtraArguments=*/true, NoIter, NoIter, ArgBeg, 2545 ArgEnd, ForceColumnInfo); 2546 } 2547 } 2548 2549 template<typename ArgTypeIterator> 2550 void EmitCallArgs(CallArgList& Args, 2551 bool AllowExtraArguments, 2552 ArgTypeIterator ArgTypeBeg, 2553 ArgTypeIterator ArgTypeEnd, 2554 CallExpr::const_arg_iterator ArgBeg, 2555 CallExpr::const_arg_iterator ArgEnd, 2556 bool ForceColumnInfo = false) { 2557 SmallVector<QualType, 16> ArgTypes; 2558 CallExpr::const_arg_iterator Arg = ArgBeg; 2559 2560 // First, use the argument types that the type info knows about 2561 for (ArgTypeIterator I = ArgTypeBeg, E = ArgTypeEnd; I != E; ++I, ++Arg) { 2562 assert(Arg != ArgEnd && "Running over edge of argument list!"); 2563 #ifndef NDEBUG 2564 QualType ArgType = *I; 2565 QualType ActualArgType = Arg->getType(); 2566 if (ArgType->isPointerType() && ActualArgType->isPointerType()) { 2567 QualType ActualBaseType = 2568 ActualArgType->getAs<PointerType>()->getPointeeType(); 2569 QualType ArgBaseType = 2570 ArgType->getAs<PointerType>()->getPointeeType(); 2571 if (ArgBaseType->isVariableArrayType()) { 2572 if (const VariableArrayType *VAT = 2573 getContext().getAsVariableArrayType(ActualBaseType)) { 2574 if (!VAT->getSizeExpr()) 2575 ActualArgType = ArgType; 2576 } 2577 } 2578 } 2579 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()). 2580 getTypePtr() == 2581 getContext().getCanonicalType(ActualArgType).getTypePtr() && 2582 "type mismatch in call argument!"); 2583 #endif 2584 ArgTypes.push_back(*I); 2585 } 2586 2587 // Either we've emitted all the call args, or we have a call to variadic 2588 // function or some other call that allows extra arguments. 2589 assert((Arg == ArgEnd || AllowExtraArguments) && 2590 "Extra arguments in non-variadic function!"); 2591 2592 // If we still have any arguments, emit them using the type of the argument. 2593 for (; Arg != ArgEnd; ++Arg) 2594 ArgTypes.push_back(Arg->getType()); 2595 2596 EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, ForceColumnInfo); 2597 } 2598 2599 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 2600 CallExpr::const_arg_iterator ArgBeg, 2601 CallExpr::const_arg_iterator ArgEnd, bool ForceColumnInfo); 2602 2603 private: 2604 const TargetCodeGenInfo &getTargetHooks() const { 2605 return CGM.getTargetCodeGenInfo(); 2606 } 2607 2608 void EmitDeclMetadata(); 2609 2610 CodeGenModule::ByrefHelpers * 2611 buildByrefHelpers(llvm::StructType &byrefType, 2612 const AutoVarEmission &emission); 2613 2614 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 2615 2616 /// GetPointeeAlignment - Given an expression with a pointer type, emit the 2617 /// value and compute our best estimate of the alignment of the pointee. 2618 std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr); 2619 }; 2620 2621 /// Helper class with most of the code for saving a value for a 2622 /// conditional expression cleanup. 2623 struct DominatingLLVMValue { 2624 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 2625 2626 /// Answer whether the given value needs extra work to be saved. 2627 static bool needsSaving(llvm::Value *value) { 2628 // If it's not an instruction, we don't need to save. 2629 if (!isa<llvm::Instruction>(value)) return false; 2630 2631 // If it's an instruction in the entry block, we don't need to save. 2632 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 2633 return (block != &block->getParent()->getEntryBlock()); 2634 } 2635 2636 /// Try to save the given value. 2637 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 2638 if (!needsSaving(value)) return saved_type(value, false); 2639 2640 // Otherwise we need an alloca. 2641 llvm::Value *alloca = 2642 CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save"); 2643 CGF.Builder.CreateStore(value, alloca); 2644 2645 return saved_type(alloca, true); 2646 } 2647 2648 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 2649 if (!value.getInt()) return value.getPointer(); 2650 return CGF.Builder.CreateLoad(value.getPointer()); 2651 } 2652 }; 2653 2654 /// A partial specialization of DominatingValue for llvm::Values that 2655 /// might be llvm::Instructions. 2656 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 2657 typedef T *type; 2658 static type restore(CodeGenFunction &CGF, saved_type value) { 2659 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 2660 } 2661 }; 2662 2663 /// A specialization of DominatingValue for RValue. 2664 template <> struct DominatingValue<RValue> { 2665 typedef RValue type; 2666 class saved_type { 2667 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 2668 AggregateAddress, ComplexAddress }; 2669 2670 llvm::Value *Value; 2671 Kind K; 2672 saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {} 2673 2674 public: 2675 static bool needsSaving(RValue value); 2676 static saved_type save(CodeGenFunction &CGF, RValue value); 2677 RValue restore(CodeGenFunction &CGF); 2678 2679 // implementations in CGExprCXX.cpp 2680 }; 2681 2682 static bool needsSaving(type value) { 2683 return saved_type::needsSaving(value); 2684 } 2685 static saved_type save(CodeGenFunction &CGF, type value) { 2686 return saved_type::save(CGF, value); 2687 } 2688 static type restore(CodeGenFunction &CGF, saved_type value) { 2689 return value.restore(CGF); 2690 } 2691 }; 2692 2693 } // end namespace CodeGen 2694 } // end namespace clang 2695 2696 #endif 2697