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