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