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