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