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