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 const TargetCodeGenInfo &getTargetHooks() const { 1483 return CGM.getTargetCodeGenInfo(); 1484 } 1485 1486 //===--------------------------------------------------------------------===// 1487 // Cleanups 1488 //===--------------------------------------------------------------------===// 1489 1490 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 1491 1492 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1493 Address arrayEndPointer, 1494 QualType elementType, 1495 CharUnits elementAlignment, 1496 Destroyer *destroyer); 1497 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1498 llvm::Value *arrayEnd, 1499 QualType elementType, 1500 CharUnits elementAlignment, 1501 Destroyer *destroyer); 1502 1503 void pushDestroy(QualType::DestructionKind dtorKind, 1504 Address addr, QualType type); 1505 void pushEHDestroy(QualType::DestructionKind dtorKind, 1506 Address addr, QualType type); 1507 void pushDestroy(CleanupKind kind, Address addr, QualType type, 1508 Destroyer *destroyer, bool useEHCleanupForArray); 1509 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 1510 QualType type, Destroyer *destroyer, 1511 bool useEHCleanupForArray); 1512 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1513 llvm::Value *CompletePtr, 1514 QualType ElementType); 1515 void pushStackRestore(CleanupKind kind, Address SPMem); 1516 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 1517 bool useEHCleanupForArray); 1518 llvm::Function *generateDestroyHelper(Address addr, QualType type, 1519 Destroyer *destroyer, 1520 bool useEHCleanupForArray, 1521 const VarDecl *VD); 1522 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 1523 QualType elementType, CharUnits elementAlign, 1524 Destroyer *destroyer, 1525 bool checkZeroLength, bool useEHCleanup); 1526 1527 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 1528 1529 /// Determines whether an EH cleanup is required to destroy a type 1530 /// with the given destruction kind. 1531 bool needsEHCleanup(QualType::DestructionKind kind) { 1532 switch (kind) { 1533 case QualType::DK_none: 1534 return false; 1535 case QualType::DK_cxx_destructor: 1536 case QualType::DK_objc_weak_lifetime: 1537 return getLangOpts().Exceptions; 1538 case QualType::DK_objc_strong_lifetime: 1539 return getLangOpts().Exceptions && 1540 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 1541 } 1542 llvm_unreachable("bad destruction kind"); 1543 } 1544 1545 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 1546 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 1547 } 1548 1549 //===--------------------------------------------------------------------===// 1550 // Objective-C 1551 //===--------------------------------------------------------------------===// 1552 1553 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 1554 1555 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 1556 1557 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 1558 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 1559 const ObjCPropertyImplDecl *PID); 1560 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 1561 const ObjCPropertyImplDecl *propImpl, 1562 const ObjCMethodDecl *GetterMothodDecl, 1563 llvm::Constant *AtomicHelperFn); 1564 1565 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 1566 ObjCMethodDecl *MD, bool ctor); 1567 1568 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 1569 /// for the given property. 1570 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 1571 const ObjCPropertyImplDecl *PID); 1572 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 1573 const ObjCPropertyImplDecl *propImpl, 1574 llvm::Constant *AtomicHelperFn); 1575 1576 //===--------------------------------------------------------------------===// 1577 // Block Bits 1578 //===--------------------------------------------------------------------===// 1579 1580 llvm::Value *EmitBlockLiteral(const BlockExpr *); 1581 static void destroyBlockInfos(CGBlockInfo *info); 1582 1583 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 1584 const CGBlockInfo &Info, 1585 const DeclMapTy &ldm, 1586 bool IsLambdaConversionToBlock); 1587 1588 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 1589 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 1590 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 1591 const ObjCPropertyImplDecl *PID); 1592 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 1593 const ObjCPropertyImplDecl *PID); 1594 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 1595 1596 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags); 1597 1598 class AutoVarEmission; 1599 1600 void emitByrefStructureInit(const AutoVarEmission &emission); 1601 void enterByrefCleanup(const AutoVarEmission &emission); 1602 1603 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 1604 llvm::Value *ptr); 1605 1606 Address LoadBlockStruct(); 1607 Address GetAddrOfBlockDecl(const VarDecl *var, bool ByRef); 1608 1609 /// BuildBlockByrefAddress - Computes the location of the 1610 /// data in a variable which is declared as __block. 1611 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 1612 bool followForward = true); 1613 Address emitBlockByrefAddress(Address baseAddr, 1614 const BlockByrefInfo &info, 1615 bool followForward, 1616 const llvm::Twine &name); 1617 1618 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 1619 1620 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 1621 1622 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 1623 const CGFunctionInfo &FnInfo); 1624 /// \brief Emit code for the start of a function. 1625 /// \param Loc The location to be associated with the function. 1626 /// \param StartLoc The location of the function body. 1627 void StartFunction(GlobalDecl GD, 1628 QualType RetTy, 1629 llvm::Function *Fn, 1630 const CGFunctionInfo &FnInfo, 1631 const FunctionArgList &Args, 1632 SourceLocation Loc = SourceLocation(), 1633 SourceLocation StartLoc = SourceLocation()); 1634 1635 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor); 1636 1637 void EmitConstructorBody(FunctionArgList &Args); 1638 void EmitDestructorBody(FunctionArgList &Args); 1639 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 1640 void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body); 1641 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 1642 1643 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 1644 CallArgList &CallArgs); 1645 void EmitLambdaToBlockPointerBody(FunctionArgList &Args); 1646 void EmitLambdaBlockInvokeBody(); 1647 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 1648 void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD); 1649 void EmitAsanPrologueOrEpilogue(bool Prologue); 1650 1651 /// \brief Emit the unified return block, trying to avoid its emission when 1652 /// possible. 1653 /// \return The debug location of the user written return statement if the 1654 /// return block is is avoided. 1655 llvm::DebugLoc EmitReturnBlock(); 1656 1657 /// FinishFunction - Complete IR generation of the current function. It is 1658 /// legal to call this function even if there is no current insertion point. 1659 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 1660 1661 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 1662 const CGFunctionInfo &FnInfo); 1663 1664 void EmitCallAndReturnForThunk(llvm::Constant *Callee, 1665 const ThunkInfo *Thunk); 1666 1667 void FinishThunk(); 1668 1669 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 1670 void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr, 1671 llvm::Value *Callee); 1672 1673 /// Generate a thunk for the given method. 1674 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 1675 GlobalDecl GD, const ThunkInfo &Thunk); 1676 1677 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 1678 const CGFunctionInfo &FnInfo, 1679 GlobalDecl GD, const ThunkInfo &Thunk); 1680 1681 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 1682 FunctionArgList &Args); 1683 1684 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init); 1685 1686 /// Struct with all informations about dynamic [sub]class needed to set vptr. 1687 struct VPtr { 1688 BaseSubobject Base; 1689 const CXXRecordDecl *NearestVBase; 1690 CharUnits OffsetFromNearestVBase; 1691 const CXXRecordDecl *VTableClass; 1692 }; 1693 1694 /// Initialize the vtable pointer of the given subobject. 1695 void InitializeVTablePointer(const VPtr &vptr); 1696 1697 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 1698 1699 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 1700 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 1701 1702 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 1703 CharUnits OffsetFromNearestVBase, 1704 bool BaseIsNonVirtualPrimaryBase, 1705 const CXXRecordDecl *VTableClass, 1706 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 1707 1708 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 1709 1710 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 1711 /// to by This. 1712 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 1713 const CXXRecordDecl *VTableClass); 1714 1715 enum CFITypeCheckKind { 1716 CFITCK_VCall, 1717 CFITCK_NVCall, 1718 CFITCK_DerivedCast, 1719 CFITCK_UnrelatedCast, 1720 CFITCK_ICall, 1721 }; 1722 1723 /// \brief Derived is the presumed address of an object of type T after a 1724 /// cast. If T is a polymorphic class type, emit a check that the virtual 1725 /// table for Derived belongs to a class derived from T. 1726 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 1727 bool MayBeNull, CFITypeCheckKind TCK, 1728 SourceLocation Loc); 1729 1730 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 1731 /// If vptr CFI is enabled, emit a check that VTable is valid. 1732 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 1733 CFITypeCheckKind TCK, SourceLocation Loc); 1734 1735 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 1736 /// RD using llvm.type.test. 1737 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 1738 CFITypeCheckKind TCK, SourceLocation Loc); 1739 1740 /// If whole-program virtual table optimization is enabled, emit an assumption 1741 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 1742 /// enabled, emit a check that VTable is a member of RD's type identifier. 1743 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 1744 llvm::Value *VTable, SourceLocation Loc); 1745 1746 /// Returns whether we should perform a type checked load when loading a 1747 /// virtual function for virtual calls to members of RD. This is generally 1748 /// true when both vcall CFI and whole-program-vtables are enabled. 1749 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 1750 1751 /// Emit a type checked load from the given vtable. 1752 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 1753 uint64_t VTableByteOffset); 1754 1755 /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 1756 /// expr can be devirtualized. 1757 bool CanDevirtualizeMemberFunctionCall(const Expr *Base, 1758 const CXXMethodDecl *MD); 1759 1760 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 1761 /// given phase of destruction for a destructor. The end result 1762 /// should call destructors on members and base classes in reverse 1763 /// order of their construction. 1764 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 1765 1766 /// ShouldInstrumentFunction - Return true if the current function should be 1767 /// instrumented with __cyg_profile_func_* calls 1768 bool ShouldInstrumentFunction(); 1769 1770 /// ShouldXRayInstrument - Return true if the current function should be 1771 /// instrumented with XRay nop sleds. 1772 bool ShouldXRayInstrumentFunction() const; 1773 1774 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 1775 /// instrumentation function with the current function and the call site, if 1776 /// function instrumentation is enabled. 1777 void EmitFunctionInstrumentation(const char *Fn); 1778 1779 /// EmitMCountInstrumentation - Emit call to .mcount. 1780 void EmitMCountInstrumentation(); 1781 1782 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 1783 /// arguments for the given function. This is also responsible for naming the 1784 /// LLVM function arguments. 1785 void EmitFunctionProlog(const CGFunctionInfo &FI, 1786 llvm::Function *Fn, 1787 const FunctionArgList &Args); 1788 1789 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 1790 /// given temporary. 1791 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 1792 SourceLocation EndLoc); 1793 1794 /// Emit a test that checks if the return value \p RV is nonnull. 1795 void EmitReturnValueCheck(llvm::Value *RV); 1796 1797 /// EmitStartEHSpec - Emit the start of the exception spec. 1798 void EmitStartEHSpec(const Decl *D); 1799 1800 /// EmitEndEHSpec - Emit the end of the exception spec. 1801 void EmitEndEHSpec(const Decl *D); 1802 1803 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 1804 llvm::BasicBlock *getTerminateLandingPad(); 1805 1806 /// getTerminateHandler - Return a handler (not a landing pad, just 1807 /// a catch handler) that just calls terminate. This is used when 1808 /// a terminate scope encloses a try. 1809 llvm::BasicBlock *getTerminateHandler(); 1810 1811 llvm::Type *ConvertTypeForMem(QualType T); 1812 llvm::Type *ConvertType(QualType T); 1813 llvm::Type *ConvertType(const TypeDecl *T) { 1814 return ConvertType(getContext().getTypeDeclType(T)); 1815 } 1816 1817 /// LoadObjCSelf - Load the value of self. This function is only valid while 1818 /// generating code for an Objective-C method. 1819 llvm::Value *LoadObjCSelf(); 1820 1821 /// TypeOfSelfObject - Return type of object that this self represents. 1822 QualType TypeOfSelfObject(); 1823 1824 /// hasAggregateLLVMType - Return true if the specified AST type will map into 1825 /// an aggregate LLVM type or is void. 1826 static TypeEvaluationKind getEvaluationKind(QualType T); 1827 1828 static bool hasScalarEvaluationKind(QualType T) { 1829 return getEvaluationKind(T) == TEK_Scalar; 1830 } 1831 1832 static bool hasAggregateEvaluationKind(QualType T) { 1833 return getEvaluationKind(T) == TEK_Aggregate; 1834 } 1835 1836 /// createBasicBlock - Create an LLVM basic block. 1837 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 1838 llvm::Function *parent = nullptr, 1839 llvm::BasicBlock *before = nullptr) { 1840 #ifdef NDEBUG 1841 return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before); 1842 #else 1843 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 1844 #endif 1845 } 1846 1847 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 1848 /// label maps to. 1849 JumpDest getJumpDestForLabel(const LabelDecl *S); 1850 1851 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 1852 /// another basic block, simplify it. This assumes that no other code could 1853 /// potentially reference the basic block. 1854 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 1855 1856 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 1857 /// adding a fall-through branch from the current insert block if 1858 /// necessary. It is legal to call this function even if there is no current 1859 /// insertion point. 1860 /// 1861 /// IsFinished - If true, indicates that the caller has finished emitting 1862 /// branches to the given block and does not expect to emit code into it. This 1863 /// means the block can be ignored if it is unreachable. 1864 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 1865 1866 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 1867 /// near its uses, and leave the insertion point in it. 1868 void EmitBlockAfterUses(llvm::BasicBlock *BB); 1869 1870 /// EmitBranch - Emit a branch to the specified basic block from the current 1871 /// insert block, taking care to avoid creation of branches from dummy 1872 /// blocks. It is legal to call this function even if there is no current 1873 /// insertion point. 1874 /// 1875 /// This function clears the current insertion point. The caller should follow 1876 /// calls to this function with calls to Emit*Block prior to generation new 1877 /// code. 1878 void EmitBranch(llvm::BasicBlock *Block); 1879 1880 /// HaveInsertPoint - True if an insertion point is defined. If not, this 1881 /// indicates that the current code being emitted is unreachable. 1882 bool HaveInsertPoint() const { 1883 return Builder.GetInsertBlock() != nullptr; 1884 } 1885 1886 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 1887 /// emitted IR has a place to go. Note that by definition, if this function 1888 /// creates a block then that block is unreachable; callers may do better to 1889 /// detect when no insertion point is defined and simply skip IR generation. 1890 void EnsureInsertPoint() { 1891 if (!HaveInsertPoint()) 1892 EmitBlock(createBasicBlock()); 1893 } 1894 1895 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1896 /// specified stmt yet. 1897 void ErrorUnsupported(const Stmt *S, const char *Type); 1898 1899 //===--------------------------------------------------------------------===// 1900 // Helpers 1901 //===--------------------------------------------------------------------===// 1902 1903 LValue MakeAddrLValue(Address Addr, QualType T, 1904 LValueBaseInfo BaseInfo = 1905 LValueBaseInfo(AlignmentSource::Type)) { 1906 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, 1907 CGM.getTBAAInfo(T)); 1908 } 1909 1910 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 1911 LValueBaseInfo BaseInfo = 1912 LValueBaseInfo(AlignmentSource::Type)) { 1913 return LValue::MakeAddr(Address(V, Alignment), T, getContext(), 1914 BaseInfo, CGM.getTBAAInfo(T)); 1915 } 1916 1917 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 1918 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 1919 CharUnits getNaturalTypeAlignment(QualType T, 1920 LValueBaseInfo *BaseInfo = nullptr, 1921 bool forPointeeType = false); 1922 CharUnits getNaturalPointeeTypeAlignment(QualType T, 1923 LValueBaseInfo *BaseInfo = nullptr); 1924 1925 Address EmitLoadOfReference(Address Ref, const ReferenceType *RefTy, 1926 LValueBaseInfo *BaseInfo = nullptr); 1927 LValue EmitLoadOfReferenceLValue(Address Ref, const ReferenceType *RefTy); 1928 1929 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 1930 LValueBaseInfo *BaseInfo = nullptr); 1931 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 1932 1933 /// CreateTempAlloca - This creates an alloca and inserts it into the entry 1934 /// block if \p ArraySize is nullptr, otherwise inserts it at the current 1935 /// insertion point of the builder. The caller is responsible for setting an 1936 /// appropriate alignment on 1937 /// the alloca. 1938 /// 1939 /// \p ArraySize is the number of array elements to be allocated if it 1940 /// is not nullptr. 1941 /// 1942 /// LangAS::Default is the address space of pointers to local variables and 1943 /// temporaries, as exposed in the source language. In certain 1944 /// configurations, this is not the same as the alloca address space, and a 1945 /// cast is needed to lift the pointer from the alloca AS into 1946 /// LangAS::Default. This can happen when the target uses a restricted 1947 /// address space for the stack but the source language requires 1948 /// LangAS::Default to be a generic address space. The latter condition is 1949 /// common for most programming languages; OpenCL is an exception in that 1950 /// LangAS::Default is the private address space, which naturally maps 1951 /// to the stack. 1952 /// 1953 /// Because the address of a temporary is often exposed to the program in 1954 /// various ways, this function will perform the cast by default. The cast 1955 /// may be avoided by passing false as \p CastToDefaultAddrSpace; this is 1956 /// more efficient if the caller knows that the address will not be exposed. 1957 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp", 1958 llvm::Value *ArraySize = nullptr); 1959 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 1960 const Twine &Name = "tmp", 1961 llvm::Value *ArraySize = nullptr, 1962 bool CastToDefaultAddrSpace = true); 1963 1964 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 1965 /// default ABI alignment of the given LLVM type. 1966 /// 1967 /// IMPORTANT NOTE: This is *not* generally the right alignment for 1968 /// any given AST type that happens to have been lowered to the 1969 /// given IR type. This should only ever be used for function-local, 1970 /// IR-driven manipulations like saving and restoring a value. Do 1971 /// not hand this address off to arbitrary IRGen routines, and especially 1972 /// do not pass it as an argument to a function that might expect a 1973 /// properly ABI-aligned value. 1974 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 1975 const Twine &Name = "tmp"); 1976 1977 /// InitTempAlloca - Provide an initial value for the given alloca which 1978 /// will be observable at all locations in the function. 1979 /// 1980 /// The address should be something that was returned from one of 1981 /// the CreateTempAlloca or CreateMemTemp routines, and the 1982 /// initializer must be valid in the entry block (i.e. it must 1983 /// either be a constant or an argument value). 1984 void InitTempAlloca(Address Alloca, llvm::Value *Value); 1985 1986 /// CreateIRTemp - Create a temporary IR object of the given type, with 1987 /// appropriate alignment. This routine should only be used when an temporary 1988 /// value needs to be stored into an alloca (for example, to avoid explicit 1989 /// PHI construction), but the type is the IR type, not the type appropriate 1990 /// for storing in memory. 1991 /// 1992 /// That is, this is exactly equivalent to CreateMemTemp, but calling 1993 /// ConvertType instead of ConvertTypeForMem. 1994 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 1995 1996 /// CreateMemTemp - Create a temporary memory object of the given type, with 1997 /// appropriate alignment. Cast it to the default address space if 1998 /// \p CastToDefaultAddrSpace is true. 1999 Address CreateMemTemp(QualType T, const Twine &Name = "tmp", 2000 bool CastToDefaultAddrSpace = true); 2001 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp", 2002 bool CastToDefaultAddrSpace = true); 2003 2004 /// CreateAggTemp - Create a temporary memory object for the given 2005 /// aggregate type. 2006 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") { 2007 return AggValueSlot::forAddr(CreateMemTemp(T, Name), 2008 T.getQualifiers(), 2009 AggValueSlot::IsNotDestructed, 2010 AggValueSlot::DoesNotNeedGCBarriers, 2011 AggValueSlot::IsNotAliased); 2012 } 2013 2014 /// Emit a cast to void* in the appropriate address space. 2015 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 2016 2017 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 2018 /// expression and compare the result against zero, returning an Int1Ty value. 2019 llvm::Value *EvaluateExprAsBool(const Expr *E); 2020 2021 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 2022 void EmitIgnoredExpr(const Expr *E); 2023 2024 /// EmitAnyExpr - Emit code to compute the specified expression which can have 2025 /// any type. The result is returned as an RValue struct. If this is an 2026 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 2027 /// the result should be returned. 2028 /// 2029 /// \param ignoreResult True if the resulting value isn't used. 2030 RValue EmitAnyExpr(const Expr *E, 2031 AggValueSlot aggSlot = AggValueSlot::ignored(), 2032 bool ignoreResult = false); 2033 2034 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 2035 // or the value of the expression, depending on how va_list is defined. 2036 Address EmitVAListRef(const Expr *E); 2037 2038 /// Emit a "reference" to a __builtin_ms_va_list; this is 2039 /// always the value of the expression, because a __builtin_ms_va_list is a 2040 /// pointer to a char. 2041 Address EmitMSVAListRef(const Expr *E); 2042 2043 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will 2044 /// always be accessible even if no aggregate location is provided. 2045 RValue EmitAnyExprToTemp(const Expr *E); 2046 2047 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 2048 /// arbitrary expression into the given memory location. 2049 void EmitAnyExprToMem(const Expr *E, Address Location, 2050 Qualifiers Quals, bool IsInitializer); 2051 2052 void EmitAnyExprToExn(const Expr *E, Address Addr); 2053 2054 /// EmitExprAsInit - Emits the code necessary to initialize a 2055 /// location in memory with the given initializer. 2056 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2057 bool capturedByInit); 2058 2059 /// hasVolatileMember - returns true if aggregate type has a volatile 2060 /// member. 2061 bool hasVolatileMember(QualType T) { 2062 if (const RecordType *RT = T->getAs<RecordType>()) { 2063 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2064 return RD->hasVolatileMember(); 2065 } 2066 return false; 2067 } 2068 /// EmitAggregateCopy - Emit an aggregate assignment. 2069 /// 2070 /// The difference to EmitAggregateCopy is that tail padding is not copied. 2071 /// This is required for correctness when assigning non-POD structures in C++. 2072 void EmitAggregateAssign(Address DestPtr, Address SrcPtr, 2073 QualType EltTy) { 2074 bool IsVolatile = hasVolatileMember(EltTy); 2075 EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, true); 2076 } 2077 2078 void EmitAggregateCopyCtor(Address DestPtr, Address SrcPtr, 2079 QualType DestTy, QualType SrcTy) { 2080 EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false, 2081 /*IsAssignment=*/false); 2082 } 2083 2084 /// EmitAggregateCopy - Emit an aggregate copy. 2085 /// 2086 /// \param isVolatile - True iff either the source or the destination is 2087 /// volatile. 2088 /// \param isAssignment - If false, allow padding to be copied. This often 2089 /// yields more efficient. 2090 void EmitAggregateCopy(Address DestPtr, Address SrcPtr, 2091 QualType EltTy, bool isVolatile=false, 2092 bool isAssignment = false); 2093 2094 /// GetAddrOfLocalVar - Return the address of a local variable. 2095 Address GetAddrOfLocalVar(const VarDecl *VD) { 2096 auto it = LocalDeclMap.find(VD); 2097 assert(it != LocalDeclMap.end() && 2098 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 2099 return it->second; 2100 } 2101 2102 /// getOpaqueLValueMapping - Given an opaque value expression (which 2103 /// must be mapped to an l-value), return its mapping. 2104 const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) { 2105 assert(OpaqueValueMapping::shouldBindAsLValue(e)); 2106 2107 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator 2108 it = OpaqueLValues.find(e); 2109 assert(it != OpaqueLValues.end() && "no mapping for opaque value!"); 2110 return it->second; 2111 } 2112 2113 /// getOpaqueRValueMapping - Given an opaque value expression (which 2114 /// must be mapped to an r-value), return its mapping. 2115 const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) { 2116 assert(!OpaqueValueMapping::shouldBindAsLValue(e)); 2117 2118 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator 2119 it = OpaqueRValues.find(e); 2120 assert(it != OpaqueRValues.end() && "no mapping for opaque value!"); 2121 return it->second; 2122 } 2123 2124 /// Get the index of the current ArrayInitLoopExpr, if any. 2125 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; } 2126 2127 /// getAccessedFieldNo - Given an encoded value and a result number, return 2128 /// the input field number being accessed. 2129 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 2130 2131 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 2132 llvm::BasicBlock *GetIndirectGotoBlock(); 2133 2134 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts. 2135 static bool IsWrappedCXXThis(const Expr *E); 2136 2137 /// EmitNullInitialization - Generate code to set a value of the given type to 2138 /// null, If the type contains data member pointers, they will be initialized 2139 /// to -1 in accordance with the Itanium C++ ABI. 2140 void EmitNullInitialization(Address DestPtr, QualType Ty); 2141 2142 /// Emits a call to an LLVM variable-argument intrinsic, either 2143 /// \c llvm.va_start or \c llvm.va_end. 2144 /// \param ArgValue A reference to the \c va_list as emitted by either 2145 /// \c EmitVAListRef or \c EmitMSVAListRef. 2146 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 2147 /// calls \c llvm.va_end. 2148 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 2149 2150 /// Generate code to get an argument from the passed in pointer 2151 /// and update it accordingly. 2152 /// \param VE The \c VAArgExpr for which to generate code. 2153 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 2154 /// either \c EmitVAListRef or \c EmitMSVAListRef. 2155 /// \returns A pointer to the argument. 2156 // FIXME: We should be able to get rid of this method and use the va_arg 2157 // instruction in LLVM instead once it works well enough. 2158 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 2159 2160 /// emitArrayLength - Compute the length of an array, even if it's a 2161 /// VLA, and drill down to the base element type. 2162 llvm::Value *emitArrayLength(const ArrayType *arrayType, 2163 QualType &baseType, 2164 Address &addr); 2165 2166 /// EmitVLASize - Capture all the sizes for the VLA expressions in 2167 /// the given variably-modified type and store them in the VLASizeMap. 2168 /// 2169 /// This function can be called with a null (unreachable) insert point. 2170 void EmitVariablyModifiedType(QualType Ty); 2171 2172 /// getVLASize - Returns an LLVM value that corresponds to the size, 2173 /// in non-variably-sized elements, of a variable length array type, 2174 /// plus that largest non-variably-sized element type. Assumes that 2175 /// the type has already been emitted with EmitVariablyModifiedType. 2176 std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla); 2177 std::pair<llvm::Value*,QualType> getVLASize(QualType vla); 2178 2179 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2180 /// generating code for an C++ member function. 2181 llvm::Value *LoadCXXThis() { 2182 assert(CXXThisValue && "no 'this' value for this function"); 2183 return CXXThisValue; 2184 } 2185 Address LoadCXXThisAddress(); 2186 2187 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2188 /// virtual bases. 2189 // FIXME: Every place that calls LoadCXXVTT is something 2190 // that needs to be abstracted properly. 2191 llvm::Value *LoadCXXVTT() { 2192 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2193 return CXXStructorImplicitParamValue; 2194 } 2195 2196 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2197 /// complete class to the given direct base. 2198 Address 2199 GetAddressOfDirectBaseInCompleteClass(Address Value, 2200 const CXXRecordDecl *Derived, 2201 const CXXRecordDecl *Base, 2202 bool BaseIsVirtual); 2203 2204 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2205 2206 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2207 /// load of 'this' and returns address of the base class. 2208 Address GetAddressOfBaseClass(Address Value, 2209 const CXXRecordDecl *Derived, 2210 CastExpr::path_const_iterator PathBegin, 2211 CastExpr::path_const_iterator PathEnd, 2212 bool NullCheckValue, SourceLocation Loc); 2213 2214 Address GetAddressOfDerivedClass(Address Value, 2215 const CXXRecordDecl *Derived, 2216 CastExpr::path_const_iterator PathBegin, 2217 CastExpr::path_const_iterator PathEnd, 2218 bool NullCheckValue); 2219 2220 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2221 /// base constructor/destructor with virtual bases. 2222 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2223 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2224 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2225 bool Delegating); 2226 2227 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2228 CXXCtorType CtorType, 2229 const FunctionArgList &Args, 2230 SourceLocation Loc); 2231 // It's important not to confuse this and the previous function. Delegating 2232 // constructors are the C++0x feature. The constructor delegate optimization 2233 // is used to reduce duplication in the base and complete consturctors where 2234 // they are substantially the same. 2235 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2236 const FunctionArgList &Args); 2237 2238 /// Emit a call to an inheriting constructor (that is, one that invokes a 2239 /// constructor inherited from a base class) by inlining its definition. This 2240 /// is necessary if the ABI does not support forwarding the arguments to the 2241 /// base class constructor (because they're variadic or similar). 2242 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2243 CXXCtorType CtorType, 2244 bool ForVirtualBase, 2245 bool Delegating, 2246 CallArgList &Args); 2247 2248 /// Emit a call to a constructor inherited from a base class, passing the 2249 /// current constructor's arguments along unmodified (without even making 2250 /// a copy). 2251 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2252 bool ForVirtualBase, Address This, 2253 bool InheritedFromVBase, 2254 const CXXInheritedCtorInitExpr *E); 2255 2256 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2257 bool ForVirtualBase, bool Delegating, 2258 Address This, const CXXConstructExpr *E); 2259 2260 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2261 bool ForVirtualBase, bool Delegating, 2262 Address This, CallArgList &Args); 2263 2264 /// Emit assumption load for all bases. Requires to be be called only on 2265 /// most-derived class and not under construction of the object. 2266 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2267 2268 /// Emit assumption that vptr load == global vtable. 2269 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2270 2271 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2272 Address This, Address Src, 2273 const CXXConstructExpr *E); 2274 2275 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2276 const ArrayType *ArrayTy, 2277 Address ArrayPtr, 2278 const CXXConstructExpr *E, 2279 bool ZeroInitialization = false); 2280 2281 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2282 llvm::Value *NumElements, 2283 Address ArrayPtr, 2284 const CXXConstructExpr *E, 2285 bool ZeroInitialization = false); 2286 2287 static Destroyer destroyCXXObject; 2288 2289 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2290 bool ForVirtualBase, bool Delegating, 2291 Address This); 2292 2293 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2294 llvm::Type *ElementTy, Address NewPtr, 2295 llvm::Value *NumElements, 2296 llvm::Value *AllocSizeWithoutCookie); 2297 2298 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2299 Address Ptr); 2300 2301 llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr); 2302 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2303 2304 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2305 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2306 2307 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2308 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2309 CharUnits CookieSize = CharUnits()); 2310 2311 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2312 const Expr *Arg, bool IsDelete); 2313 2314 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2315 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2316 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2317 2318 /// \brief Situations in which we might emit a check for the suitability of a 2319 /// pointer or glvalue. 2320 enum TypeCheckKind { 2321 /// Checking the operand of a load. Must be suitably sized and aligned. 2322 TCK_Load, 2323 /// Checking the destination of a store. Must be suitably sized and aligned. 2324 TCK_Store, 2325 /// Checking the bound value in a reference binding. Must be suitably sized 2326 /// and aligned, but is not required to refer to an object (until the 2327 /// reference is used), per core issue 453. 2328 TCK_ReferenceBinding, 2329 /// Checking the object expression in a non-static data member access. Must 2330 /// be an object within its lifetime. 2331 TCK_MemberAccess, 2332 /// Checking the 'this' pointer for a call to a non-static member function. 2333 /// Must be an object within its lifetime. 2334 TCK_MemberCall, 2335 /// Checking the 'this' pointer for a constructor call. 2336 TCK_ConstructorCall, 2337 /// Checking the operand of a static_cast to a derived pointer type. Must be 2338 /// null or an object within its lifetime. 2339 TCK_DowncastPointer, 2340 /// Checking the operand of a static_cast to a derived reference type. Must 2341 /// be an object within its lifetime. 2342 TCK_DowncastReference, 2343 /// Checking the operand of a cast to a base object. Must be suitably sized 2344 /// and aligned. 2345 TCK_Upcast, 2346 /// Checking the operand of a cast to a virtual base object. Must be an 2347 /// object within its lifetime. 2348 TCK_UpcastToVirtualBase, 2349 /// Checking the value assigned to a _Nonnull pointer. Must not be null. 2350 TCK_NonnullAssign 2351 }; 2352 2353 /// \brief Whether any type-checking sanitizers are enabled. If \c false, 2354 /// calls to EmitTypeCheck can be skipped. 2355 bool sanitizePerformTypeCheck() const; 2356 2357 /// \brief Emit a check that \p V is the address of storage of the 2358 /// appropriate size and alignment for an object of type \p Type. 2359 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2360 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2361 SanitizerSet SkippedChecks = SanitizerSet()); 2362 2363 /// \brief Emit a check that \p Base points into an array object, which 2364 /// we can access at index \p Index. \p Accessed should be \c false if we 2365 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 2366 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 2367 QualType IndexType, bool Accessed); 2368 2369 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 2370 bool isInc, bool isPre); 2371 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 2372 bool isInc, bool isPre); 2373 2374 void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment, 2375 llvm::Value *OffsetValue = nullptr) { 2376 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment, 2377 OffsetValue); 2378 } 2379 2380 /// Converts Location to a DebugLoc, if debug information is enabled. 2381 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 2382 2383 2384 //===--------------------------------------------------------------------===// 2385 // Declaration Emission 2386 //===--------------------------------------------------------------------===// 2387 2388 /// EmitDecl - Emit a declaration. 2389 /// 2390 /// This function can be called with a null (unreachable) insert point. 2391 void EmitDecl(const Decl &D); 2392 2393 /// EmitVarDecl - Emit a local variable declaration. 2394 /// 2395 /// This function can be called with a null (unreachable) insert point. 2396 void EmitVarDecl(const VarDecl &D); 2397 2398 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2399 bool capturedByInit); 2400 2401 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 2402 llvm::Value *Address); 2403 2404 /// \brief Determine whether the given initializer is trivial in the sense 2405 /// that it requires no code to be generated. 2406 bool isTrivialInitializer(const Expr *Init); 2407 2408 /// EmitAutoVarDecl - Emit an auto variable declaration. 2409 /// 2410 /// This function can be called with a null (unreachable) insert point. 2411 void EmitAutoVarDecl(const VarDecl &D); 2412 2413 class AutoVarEmission { 2414 friend class CodeGenFunction; 2415 2416 const VarDecl *Variable; 2417 2418 /// The address of the alloca. Invalid if the variable was emitted 2419 /// as a global constant. 2420 Address Addr; 2421 2422 llvm::Value *NRVOFlag; 2423 2424 /// True if the variable is a __block variable. 2425 bool IsByRef; 2426 2427 /// True if the variable is of aggregate type and has a constant 2428 /// initializer. 2429 bool IsConstantAggregate; 2430 2431 /// Non-null if we should use lifetime annotations. 2432 llvm::Value *SizeForLifetimeMarkers; 2433 2434 struct Invalid {}; 2435 AutoVarEmission(Invalid) : Variable(nullptr), Addr(Address::invalid()) {} 2436 2437 AutoVarEmission(const VarDecl &variable) 2438 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 2439 IsByRef(false), IsConstantAggregate(false), 2440 SizeForLifetimeMarkers(nullptr) {} 2441 2442 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 2443 2444 public: 2445 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 2446 2447 bool useLifetimeMarkers() const { 2448 return SizeForLifetimeMarkers != nullptr; 2449 } 2450 llvm::Value *getSizeForLifetimeMarkers() const { 2451 assert(useLifetimeMarkers()); 2452 return SizeForLifetimeMarkers; 2453 } 2454 2455 /// Returns the raw, allocated address, which is not necessarily 2456 /// the address of the object itself. 2457 Address getAllocatedAddress() const { 2458 return Addr; 2459 } 2460 2461 /// Returns the address of the object within this declaration. 2462 /// Note that this does not chase the forwarding pointer for 2463 /// __block decls. 2464 Address getObjectAddress(CodeGenFunction &CGF) const { 2465 if (!IsByRef) return Addr; 2466 2467 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 2468 } 2469 }; 2470 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 2471 void EmitAutoVarInit(const AutoVarEmission &emission); 2472 void EmitAutoVarCleanups(const AutoVarEmission &emission); 2473 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 2474 QualType::DestructionKind dtorKind); 2475 2476 void EmitStaticVarDecl(const VarDecl &D, 2477 llvm::GlobalValue::LinkageTypes Linkage); 2478 2479 class ParamValue { 2480 llvm::Value *Value; 2481 unsigned Alignment; 2482 ParamValue(llvm::Value *V, unsigned A) : Value(V), Alignment(A) {} 2483 public: 2484 static ParamValue forDirect(llvm::Value *value) { 2485 return ParamValue(value, 0); 2486 } 2487 static ParamValue forIndirect(Address addr) { 2488 assert(!addr.getAlignment().isZero()); 2489 return ParamValue(addr.getPointer(), addr.getAlignment().getQuantity()); 2490 } 2491 2492 bool isIndirect() const { return Alignment != 0; } 2493 llvm::Value *getAnyValue() const { return Value; } 2494 2495 llvm::Value *getDirectValue() const { 2496 assert(!isIndirect()); 2497 return Value; 2498 } 2499 2500 Address getIndirectAddress() const { 2501 assert(isIndirect()); 2502 return Address(Value, CharUnits::fromQuantity(Alignment)); 2503 } 2504 }; 2505 2506 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 2507 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 2508 2509 /// protectFromPeepholes - Protect a value that we're intending to 2510 /// store to the side, but which will probably be used later, from 2511 /// aggressive peepholing optimizations that might delete it. 2512 /// 2513 /// Pass the result to unprotectFromPeepholes to declare that 2514 /// protection is no longer required. 2515 /// 2516 /// There's no particular reason why this shouldn't apply to 2517 /// l-values, it's just that no existing peepholes work on pointers. 2518 PeepholeProtection protectFromPeepholes(RValue rvalue); 2519 void unprotectFromPeepholes(PeepholeProtection protection); 2520 2521 void EmitAlignmentAssumption(llvm::Value *PtrValue, llvm::Value *Alignment, 2522 llvm::Value *OffsetValue = nullptr) { 2523 Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment, 2524 OffsetValue); 2525 } 2526 2527 //===--------------------------------------------------------------------===// 2528 // Statement Emission 2529 //===--------------------------------------------------------------------===// 2530 2531 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 2532 void EmitStopPoint(const Stmt *S); 2533 2534 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 2535 /// this function even if there is no current insertion point. 2536 /// 2537 /// This function may clear the current insertion point; callers should use 2538 /// EnsureInsertPoint if they wish to subsequently generate code without first 2539 /// calling EmitBlock, EmitBranch, or EmitStmt. 2540 void EmitStmt(const Stmt *S); 2541 2542 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 2543 /// necessarily require an insertion point or debug information; typically 2544 /// because the statement amounts to a jump or a container of other 2545 /// statements. 2546 /// 2547 /// \return True if the statement was handled. 2548 bool EmitSimpleStmt(const Stmt *S); 2549 2550 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 2551 AggValueSlot AVS = AggValueSlot::ignored()); 2552 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 2553 bool GetLast = false, 2554 AggValueSlot AVS = 2555 AggValueSlot::ignored()); 2556 2557 /// EmitLabel - Emit the block for the given label. It is legal to call this 2558 /// function even if there is no current insertion point. 2559 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 2560 2561 void EmitLabelStmt(const LabelStmt &S); 2562 void EmitAttributedStmt(const AttributedStmt &S); 2563 void EmitGotoStmt(const GotoStmt &S); 2564 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 2565 void EmitIfStmt(const IfStmt &S); 2566 2567 void EmitWhileStmt(const WhileStmt &S, 2568 ArrayRef<const Attr *> Attrs = None); 2569 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 2570 void EmitForStmt(const ForStmt &S, 2571 ArrayRef<const Attr *> Attrs = None); 2572 void EmitReturnStmt(const ReturnStmt &S); 2573 void EmitDeclStmt(const DeclStmt &S); 2574 void EmitBreakStmt(const BreakStmt &S); 2575 void EmitContinueStmt(const ContinueStmt &S); 2576 void EmitSwitchStmt(const SwitchStmt &S); 2577 void EmitDefaultStmt(const DefaultStmt &S); 2578 void EmitCaseStmt(const CaseStmt &S); 2579 void EmitCaseStmtRange(const CaseStmt &S); 2580 void EmitAsmStmt(const AsmStmt &S); 2581 2582 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 2583 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 2584 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 2585 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 2586 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 2587 2588 void EmitCoroutineBody(const CoroutineBodyStmt &S); 2589 void EmitCoreturnStmt(const CoreturnStmt &S); 2590 RValue EmitCoawaitExpr(const CoawaitExpr &E, 2591 AggValueSlot aggSlot = AggValueSlot::ignored(), 2592 bool ignoreResult = false); 2593 LValue EmitCoawaitLValue(const CoawaitExpr *E); 2594 RValue EmitCoyieldExpr(const CoyieldExpr &E, 2595 AggValueSlot aggSlot = AggValueSlot::ignored(), 2596 bool ignoreResult = false); 2597 LValue EmitCoyieldLValue(const CoyieldExpr *E); 2598 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 2599 2600 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2601 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 2602 2603 void EmitCXXTryStmt(const CXXTryStmt &S); 2604 void EmitSEHTryStmt(const SEHTryStmt &S); 2605 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 2606 void EnterSEHTryStmt(const SEHTryStmt &S); 2607 void ExitSEHTryStmt(const SEHTryStmt &S); 2608 2609 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 2610 const Stmt *OutlinedStmt); 2611 2612 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 2613 const SEHExceptStmt &Except); 2614 2615 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 2616 const SEHFinallyStmt &Finally); 2617 2618 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 2619 llvm::Value *ParentFP, 2620 llvm::Value *EntryEBP); 2621 llvm::Value *EmitSEHExceptionCode(); 2622 llvm::Value *EmitSEHExceptionInfo(); 2623 llvm::Value *EmitSEHAbnormalTermination(); 2624 2625 /// Scan the outlined statement for captures from the parent function. For 2626 /// each capture, mark the capture as escaped and emit a call to 2627 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 2628 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 2629 bool IsFilter); 2630 2631 /// Recovers the address of a local in a parent function. ParentVar is the 2632 /// address of the variable used in the immediate parent function. It can 2633 /// either be an alloca or a call to llvm.localrecover if there are nested 2634 /// outlined functions. ParentFP is the frame pointer of the outermost parent 2635 /// frame. 2636 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 2637 Address ParentVar, 2638 llvm::Value *ParentFP); 2639 2640 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 2641 ArrayRef<const Attr *> Attrs = None); 2642 2643 /// Returns calculated size of the specified type. 2644 llvm::Value *getTypeSize(QualType Ty); 2645 LValue InitCapturedStruct(const CapturedStmt &S); 2646 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 2647 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 2648 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 2649 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S); 2650 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 2651 SmallVectorImpl<llvm::Value *> &CapturedVars); 2652 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 2653 SourceLocation Loc); 2654 /// \brief Perform element by element copying of arrays with type \a 2655 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 2656 /// generated by \a CopyGen. 2657 /// 2658 /// \param DestAddr Address of the destination array. 2659 /// \param SrcAddr Address of the source array. 2660 /// \param OriginalType Type of destination and source arrays. 2661 /// \param CopyGen Copying procedure that copies value of single array element 2662 /// to another single array element. 2663 void EmitOMPAggregateAssign( 2664 Address DestAddr, Address SrcAddr, QualType OriginalType, 2665 const llvm::function_ref<void(Address, Address)> &CopyGen); 2666 /// \brief Emit proper copying of data from one variable to another. 2667 /// 2668 /// \param OriginalType Original type of the copied variables. 2669 /// \param DestAddr Destination address. 2670 /// \param SrcAddr Source address. 2671 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 2672 /// type of the base array element). 2673 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 2674 /// the base array element). 2675 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 2676 /// DestVD. 2677 void EmitOMPCopy(QualType OriginalType, 2678 Address DestAddr, Address SrcAddr, 2679 const VarDecl *DestVD, const VarDecl *SrcVD, 2680 const Expr *Copy); 2681 /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or 2682 /// \a X = \a E \a BO \a E. 2683 /// 2684 /// \param X Value to be updated. 2685 /// \param E Update value. 2686 /// \param BO Binary operation for update operation. 2687 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 2688 /// expression, false otherwise. 2689 /// \param AO Atomic ordering of the generated atomic instructions. 2690 /// \param CommonGen Code generator for complex expressions that cannot be 2691 /// expressed through atomicrmw instruction. 2692 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 2693 /// generated, <false, RValue::get(nullptr)> otherwise. 2694 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 2695 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 2696 llvm::AtomicOrdering AO, SourceLocation Loc, 2697 const llvm::function_ref<RValue(RValue)> &CommonGen); 2698 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 2699 OMPPrivateScope &PrivateScope); 2700 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 2701 OMPPrivateScope &PrivateScope); 2702 void EmitOMPUseDevicePtrClause( 2703 const OMPClause &C, OMPPrivateScope &PrivateScope, 2704 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 2705 /// \brief Emit code for copyin clause in \a D directive. The next code is 2706 /// generated at the start of outlined functions for directives: 2707 /// \code 2708 /// threadprivate_var1 = master_threadprivate_var1; 2709 /// operator=(threadprivate_var2, master_threadprivate_var2); 2710 /// ... 2711 /// __kmpc_barrier(&loc, global_tid); 2712 /// \endcode 2713 /// 2714 /// \param D OpenMP directive possibly with 'copyin' clause(s). 2715 /// \returns true if at least one copyin variable is found, false otherwise. 2716 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 2717 /// \brief Emit initial code for lastprivate variables. If some variable is 2718 /// not also firstprivate, then the default initialization is used. Otherwise 2719 /// initialization of this variable is performed by EmitOMPFirstprivateClause 2720 /// method. 2721 /// 2722 /// \param D Directive that may have 'lastprivate' directives. 2723 /// \param PrivateScope Private scope for capturing lastprivate variables for 2724 /// proper codegen in internal captured statement. 2725 /// 2726 /// \returns true if there is at least one lastprivate variable, false 2727 /// otherwise. 2728 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 2729 OMPPrivateScope &PrivateScope); 2730 /// \brief Emit final copying of lastprivate values to original variables at 2731 /// the end of the worksharing or simd directive. 2732 /// 2733 /// \param D Directive that has at least one 'lastprivate' directives. 2734 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 2735 /// it is the last iteration of the loop code in associated directive, or to 2736 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 2737 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 2738 bool NoFinals, 2739 llvm::Value *IsLastIterCond = nullptr); 2740 /// Emit initial code for linear clauses. 2741 void EmitOMPLinearClause(const OMPLoopDirective &D, 2742 CodeGenFunction::OMPPrivateScope &PrivateScope); 2743 /// Emit final code for linear clauses. 2744 /// \param CondGen Optional conditional code for final part of codegen for 2745 /// linear clause. 2746 void EmitOMPLinearClauseFinal( 2747 const OMPLoopDirective &D, 2748 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen); 2749 /// \brief Emit initial code for reduction variables. Creates reduction copies 2750 /// and initializes them with the values according to OpenMP standard. 2751 /// 2752 /// \param D Directive (possibly) with the 'reduction' clause. 2753 /// \param PrivateScope Private scope for capturing reduction variables for 2754 /// proper codegen in internal captured statement. 2755 /// 2756 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 2757 OMPPrivateScope &PrivateScope); 2758 /// \brief Emit final update of reduction values to original variables at 2759 /// the end of the directive. 2760 /// 2761 /// \param D Directive that has at least one 'reduction' directives. 2762 /// \param ReductionKind The kind of reduction to perform. 2763 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, 2764 const OpenMPDirectiveKind ReductionKind); 2765 /// \brief Emit initial code for linear variables. Creates private copies 2766 /// and initializes them with the values according to OpenMP standard. 2767 /// 2768 /// \param D Directive (possibly) with the 'linear' clause. 2769 void EmitOMPLinearClauseInit(const OMPLoopDirective &D); 2770 2771 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 2772 llvm::Value * /*OutlinedFn*/, 2773 const OMPTaskDataTy & /*Data*/)> 2774 TaskGenTy; 2775 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 2776 const RegionCodeGenTy &BodyGen, 2777 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 2778 2779 void EmitOMPParallelDirective(const OMPParallelDirective &S); 2780 void EmitOMPSimdDirective(const OMPSimdDirective &S); 2781 void EmitOMPForDirective(const OMPForDirective &S); 2782 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 2783 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 2784 void EmitOMPSectionDirective(const OMPSectionDirective &S); 2785 void EmitOMPSingleDirective(const OMPSingleDirective &S); 2786 void EmitOMPMasterDirective(const OMPMasterDirective &S); 2787 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 2788 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 2789 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 2790 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 2791 void EmitOMPTaskDirective(const OMPTaskDirective &S); 2792 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 2793 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 2794 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 2795 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 2796 void EmitOMPFlushDirective(const OMPFlushDirective &S); 2797 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 2798 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 2799 void EmitOMPTargetDirective(const OMPTargetDirective &S); 2800 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 2801 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 2802 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 2803 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 2804 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 2805 void 2806 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 2807 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 2808 void 2809 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 2810 void EmitOMPCancelDirective(const OMPCancelDirective &S); 2811 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 2812 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 2813 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 2814 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 2815 void EmitOMPDistributeParallelForDirective( 2816 const OMPDistributeParallelForDirective &S); 2817 void EmitOMPDistributeParallelForSimdDirective( 2818 const OMPDistributeParallelForSimdDirective &S); 2819 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 2820 void EmitOMPTargetParallelForSimdDirective( 2821 const OMPTargetParallelForSimdDirective &S); 2822 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 2823 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 2824 void 2825 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 2826 void EmitOMPTeamsDistributeParallelForSimdDirective( 2827 const OMPTeamsDistributeParallelForSimdDirective &S); 2828 void EmitOMPTeamsDistributeParallelForDirective( 2829 const OMPTeamsDistributeParallelForDirective &S); 2830 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S); 2831 void EmitOMPTargetTeamsDistributeDirective( 2832 const OMPTargetTeamsDistributeDirective &S); 2833 void EmitOMPTargetTeamsDistributeParallelForDirective( 2834 const OMPTargetTeamsDistributeParallelForDirective &S); 2835 void EmitOMPTargetTeamsDistributeParallelForSimdDirective( 2836 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 2837 void EmitOMPTargetTeamsDistributeSimdDirective( 2838 const OMPTargetTeamsDistributeSimdDirective &S); 2839 2840 /// Emit device code for the target directive. 2841 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 2842 StringRef ParentName, 2843 const OMPTargetDirective &S); 2844 static void 2845 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 2846 const OMPTargetParallelDirective &S); 2847 static void 2848 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 2849 const OMPTargetTeamsDirective &S); 2850 /// \brief Emit inner loop of the worksharing/simd construct. 2851 /// 2852 /// \param S Directive, for which the inner loop must be emitted. 2853 /// \param RequiresCleanup true, if directive has some associated private 2854 /// variables. 2855 /// \param LoopCond Bollean condition for loop continuation. 2856 /// \param IncExpr Increment expression for loop control variable. 2857 /// \param BodyGen Generator for the inner body of the inner loop. 2858 /// \param PostIncGen Genrator for post-increment code (required for ordered 2859 /// loop directvies). 2860 void EmitOMPInnerLoop( 2861 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 2862 const Expr *IncExpr, 2863 const llvm::function_ref<void(CodeGenFunction &)> &BodyGen, 2864 const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen); 2865 2866 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind); 2867 /// Emit initial code for loop counters of loop-based directives. 2868 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, 2869 OMPPrivateScope &LoopScope); 2870 2871 /// Helper for the OpenMP loop directives. 2872 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit); 2873 2874 /// \brief Emit code for the worksharing loop-based directive. 2875 /// \return true, if this construct has any lastprivate clause, false - 2876 /// otherwise. 2877 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB, 2878 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 2879 const CodeGenDispatchBoundsTy &CGDispatchBounds); 2880 2881 private: 2882 /// Helpers for blocks 2883 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 2884 2885 /// Helpers for the OpenMP loop directives. 2886 void EmitOMPSimdInit(const OMPLoopDirective &D, bool IsMonotonic = false); 2887 void EmitOMPSimdFinal( 2888 const OMPLoopDirective &D, 2889 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> &CondGen); 2890 2891 void EmitOMPDistributeLoop(const OMPLoopDirective &S, 2892 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr); 2893 2894 /// struct with the values to be passed to the OpenMP loop-related functions 2895 struct OMPLoopArguments { 2896 /// loop lower bound 2897 Address LB = Address::invalid(); 2898 /// loop upper bound 2899 Address UB = Address::invalid(); 2900 /// loop stride 2901 Address ST = Address::invalid(); 2902 /// isLastIteration argument for runtime functions 2903 Address IL = Address::invalid(); 2904 /// Chunk value generated by sema 2905 llvm::Value *Chunk = nullptr; 2906 /// EnsureUpperBound 2907 Expr *EUB = nullptr; 2908 /// IncrementExpression 2909 Expr *IncExpr = nullptr; 2910 /// Loop initialization 2911 Expr *Init = nullptr; 2912 /// Loop exit condition 2913 Expr *Cond = nullptr; 2914 /// Update of LB after a whole chunk has been executed 2915 Expr *NextLB = nullptr; 2916 /// Update of UB after a whole chunk has been executed 2917 Expr *NextUB = nullptr; 2918 OMPLoopArguments() = default; 2919 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL, 2920 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr, 2921 Expr *IncExpr = nullptr, Expr *Init = nullptr, 2922 Expr *Cond = nullptr, Expr *NextLB = nullptr, 2923 Expr *NextUB = nullptr) 2924 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB), 2925 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB), 2926 NextUB(NextUB) {} 2927 }; 2928 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic, 2929 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, 2930 const OMPLoopArguments &LoopArgs, 2931 const CodeGenLoopTy &CodeGenLoop, 2932 const CodeGenOrderedTy &CodeGenOrdered); 2933 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind, 2934 bool IsMonotonic, const OMPLoopDirective &S, 2935 OMPPrivateScope &LoopScope, bool Ordered, 2936 const OMPLoopArguments &LoopArgs, 2937 const CodeGenDispatchBoundsTy &CGDispatchBounds); 2938 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind, 2939 const OMPLoopDirective &S, 2940 OMPPrivateScope &LoopScope, 2941 const OMPLoopArguments &LoopArgs, 2942 const CodeGenLoopTy &CodeGenLoopContent); 2943 /// \brief Emit code for sections directive. 2944 void EmitSections(const OMPExecutableDirective &S); 2945 2946 public: 2947 2948 //===--------------------------------------------------------------------===// 2949 // LValue Expression Emission 2950 //===--------------------------------------------------------------------===// 2951 2952 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 2953 RValue GetUndefRValue(QualType Ty); 2954 2955 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 2956 /// and issue an ErrorUnsupported style diagnostic (using the 2957 /// provided Name). 2958 RValue EmitUnsupportedRValue(const Expr *E, 2959 const char *Name); 2960 2961 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 2962 /// an ErrorUnsupported style diagnostic (using the provided Name). 2963 LValue EmitUnsupportedLValue(const Expr *E, 2964 const char *Name); 2965 2966 /// EmitLValue - Emit code to compute a designator that specifies the location 2967 /// of the expression. 2968 /// 2969 /// This can return one of two things: a simple address or a bitfield 2970 /// reference. In either case, the LLVM Value* in the LValue structure is 2971 /// guaranteed to be an LLVM pointer type. 2972 /// 2973 /// If this returns a bitfield reference, nothing about the pointee type of 2974 /// the LLVM value is known: For example, it may not be a pointer to an 2975 /// integer. 2976 /// 2977 /// If this returns a normal address, and if the lvalue's C type is fixed 2978 /// size, this method guarantees that the returned pointer type will point to 2979 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 2980 /// variable length type, this is not possible. 2981 /// 2982 LValue EmitLValue(const Expr *E); 2983 2984 /// \brief Same as EmitLValue but additionally we generate checking code to 2985 /// guard against undefined behavior. This is only suitable when we know 2986 /// that the address will be used to access the object. 2987 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 2988 2989 RValue convertTempToRValue(Address addr, QualType type, 2990 SourceLocation Loc); 2991 2992 void EmitAtomicInit(Expr *E, LValue lvalue); 2993 2994 bool LValueIsSuitableForInlineAtomic(LValue Src); 2995 2996 RValue EmitAtomicLoad(LValue LV, SourceLocation SL, 2997 AggValueSlot Slot = AggValueSlot::ignored()); 2998 2999 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 3000 llvm::AtomicOrdering AO, bool IsVolatile = false, 3001 AggValueSlot slot = AggValueSlot::ignored()); 3002 3003 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 3004 3005 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO, 3006 bool IsVolatile, bool isInit); 3007 3008 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange( 3009 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, 3010 llvm::AtomicOrdering Success = 3011 llvm::AtomicOrdering::SequentiallyConsistent, 3012 llvm::AtomicOrdering Failure = 3013 llvm::AtomicOrdering::SequentiallyConsistent, 3014 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored()); 3015 3016 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, 3017 const llvm::function_ref<RValue(RValue)> &UpdateOp, 3018 bool IsVolatile); 3019 3020 /// EmitToMemory - Change a scalar value from its value 3021 /// representation to its in-memory representation. 3022 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 3023 3024 /// EmitFromMemory - Change a scalar value from its memory 3025 /// representation to its value representation. 3026 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 3027 3028 /// Check if the scalar \p Value is within the valid range for the given 3029 /// type \p Ty. 3030 /// 3031 /// Returns true if a check is needed (even if the range is unknown). 3032 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 3033 SourceLocation Loc); 3034 3035 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3036 /// care to appropriately convert from the memory representation to 3037 /// the LLVM value representation. 3038 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3039 SourceLocation Loc, 3040 LValueBaseInfo BaseInfo = 3041 LValueBaseInfo(AlignmentSource::Type), 3042 llvm::MDNode *TBAAInfo = nullptr, 3043 QualType TBAABaseTy = QualType(), 3044 uint64_t TBAAOffset = 0, 3045 bool isNontemporal = false); 3046 3047 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3048 /// care to appropriately convert from the memory representation to 3049 /// the LLVM value representation. The l-value must be a simple 3050 /// l-value. 3051 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 3052 3053 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3054 /// care to appropriately convert from the memory representation to 3055 /// the LLVM value representation. 3056 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3057 bool Volatile, QualType Ty, 3058 LValueBaseInfo BaseInfo = 3059 LValueBaseInfo(AlignmentSource::Type), 3060 llvm::MDNode *TBAAInfo = nullptr, bool isInit = false, 3061 QualType TBAABaseTy = QualType(), 3062 uint64_t TBAAOffset = 0, bool isNontemporal = false); 3063 3064 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3065 /// care to appropriately convert from the memory representation to 3066 /// the LLVM value representation. The l-value must be a simple 3067 /// l-value. The isInit flag indicates whether this is an initialization. 3068 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 3069 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 3070 3071 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 3072 /// this method emits the address of the lvalue, then loads the result as an 3073 /// rvalue, returning the rvalue. 3074 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 3075 RValue EmitLoadOfExtVectorElementLValue(LValue V); 3076 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc); 3077 RValue EmitLoadOfGlobalRegLValue(LValue LV); 3078 3079 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 3080 /// lvalue, where both are guaranteed to the have the same type, and that type 3081 /// is 'Ty'. 3082 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false); 3083 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 3084 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 3085 3086 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 3087 /// as EmitStoreThroughLValue. 3088 /// 3089 /// \param Result [out] - If non-null, this will be set to a Value* for the 3090 /// bit-field contents after the store, appropriate for use as the result of 3091 /// an assignment to the bit-field. 3092 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 3093 llvm::Value **Result=nullptr); 3094 3095 /// Emit an l-value for an assignment (simple or compound) of complex type. 3096 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 3097 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 3098 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, 3099 llvm::Value *&Result); 3100 3101 // Note: only available for agg return types 3102 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 3103 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 3104 // Note: only available for agg return types 3105 LValue EmitCallExprLValue(const CallExpr *E); 3106 // Note: only available for agg return types 3107 LValue EmitVAArgExprLValue(const VAArgExpr *E); 3108 LValue EmitDeclRefLValue(const DeclRefExpr *E); 3109 LValue EmitStringLiteralLValue(const StringLiteral *E); 3110 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 3111 LValue EmitPredefinedLValue(const PredefinedExpr *E); 3112 LValue EmitUnaryOpLValue(const UnaryOperator *E); 3113 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3114 bool Accessed = false); 3115 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3116 bool IsLowerBound = true); 3117 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 3118 LValue EmitMemberExpr(const MemberExpr *E); 3119 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 3120 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 3121 LValue EmitInitListLValue(const InitListExpr *E); 3122 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 3123 LValue EmitCastLValue(const CastExpr *E); 3124 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 3125 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 3126 3127 Address EmitExtVectorElementLValue(LValue V); 3128 3129 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 3130 3131 Address EmitArrayToPointerDecay(const Expr *Array, 3132 LValueBaseInfo *BaseInfo = nullptr); 3133 3134 class ConstantEmission { 3135 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 3136 ConstantEmission(llvm::Constant *C, bool isReference) 3137 : ValueAndIsReference(C, isReference) {} 3138 public: 3139 ConstantEmission() {} 3140 static ConstantEmission forReference(llvm::Constant *C) { 3141 return ConstantEmission(C, true); 3142 } 3143 static ConstantEmission forValue(llvm::Constant *C) { 3144 return ConstantEmission(C, false); 3145 } 3146 3147 explicit operator bool() const { 3148 return ValueAndIsReference.getOpaqueValue() != nullptr; 3149 } 3150 3151 bool isReference() const { return ValueAndIsReference.getInt(); } 3152 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 3153 assert(isReference()); 3154 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 3155 refExpr->getType()); 3156 } 3157 3158 llvm::Constant *getValue() const { 3159 assert(!isReference()); 3160 return ValueAndIsReference.getPointer(); 3161 } 3162 }; 3163 3164 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 3165 3166 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 3167 AggValueSlot slot = AggValueSlot::ignored()); 3168 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 3169 3170 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 3171 const ObjCIvarDecl *Ivar); 3172 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 3173 LValue EmitLValueForLambdaField(const FieldDecl *Field); 3174 3175 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 3176 /// if the Field is a reference, this will return the address of the reference 3177 /// and not the address of the value stored in the reference. 3178 LValue EmitLValueForFieldInitialization(LValue Base, 3179 const FieldDecl* Field); 3180 3181 LValue EmitLValueForIvar(QualType ObjectTy, 3182 llvm::Value* Base, const ObjCIvarDecl *Ivar, 3183 unsigned CVRQualifiers); 3184 3185 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 3186 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 3187 LValue EmitLambdaLValue(const LambdaExpr *E); 3188 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 3189 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 3190 3191 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 3192 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 3193 LValue EmitStmtExprLValue(const StmtExpr *E); 3194 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 3195 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 3196 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init); 3197 3198 //===--------------------------------------------------------------------===// 3199 // Scalar Expression Emission 3200 //===--------------------------------------------------------------------===// 3201 3202 /// EmitCall - Generate a call of the given function, expecting the given 3203 /// result type, and using the given argument list which specifies both the 3204 /// LLVM arguments and the types they were derived from. 3205 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 3206 ReturnValueSlot ReturnValue, const CallArgList &Args, 3207 llvm::Instruction **callOrInvoke = nullptr); 3208 3209 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E, 3210 ReturnValueSlot ReturnValue, 3211 llvm::Value *Chain = nullptr); 3212 RValue EmitCallExpr(const CallExpr *E, 3213 ReturnValueSlot ReturnValue = ReturnValueSlot()); 3214 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3215 CGCallee EmitCallee(const Expr *E); 3216 3217 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl); 3218 3219 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 3220 const Twine &name = ""); 3221 llvm::CallInst *EmitRuntimeCall(llvm::Value *callee, 3222 ArrayRef<llvm::Value*> args, 3223 const Twine &name = ""); 3224 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 3225 const Twine &name = ""); 3226 llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee, 3227 ArrayRef<llvm::Value*> args, 3228 const Twine &name = ""); 3229 3230 llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee, 3231 ArrayRef<llvm::Value *> Args, 3232 const Twine &Name = ""); 3233 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 3234 ArrayRef<llvm::Value*> args, 3235 const Twine &name = ""); 3236 llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, 3237 const Twine &name = ""); 3238 void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 3239 ArrayRef<llvm::Value*> args); 3240 3241 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 3242 NestedNameSpecifier *Qual, 3243 llvm::Type *Ty); 3244 3245 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 3246 CXXDtorType Type, 3247 const CXXRecordDecl *RD); 3248 3249 RValue 3250 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, 3251 const CGCallee &Callee, 3252 ReturnValueSlot ReturnValue, llvm::Value *This, 3253 llvm::Value *ImplicitParam, 3254 QualType ImplicitParamTy, const CallExpr *E, 3255 CallArgList *RtlArgs); 3256 RValue EmitCXXDestructorCall(const CXXDestructorDecl *DD, 3257 const CGCallee &Callee, 3258 llvm::Value *This, llvm::Value *ImplicitParam, 3259 QualType ImplicitParamTy, const CallExpr *E, 3260 StructorType Type); 3261 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 3262 ReturnValueSlot ReturnValue); 3263 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, 3264 const CXXMethodDecl *MD, 3265 ReturnValueSlot ReturnValue, 3266 bool HasQualifier, 3267 NestedNameSpecifier *Qualifier, 3268 bool IsArrow, const Expr *Base); 3269 // Compute the object pointer. 3270 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 3271 llvm::Value *memberPtr, 3272 const MemberPointerType *memberPtrType, 3273 LValueBaseInfo *BaseInfo = nullptr); 3274 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 3275 ReturnValueSlot ReturnValue); 3276 3277 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 3278 const CXXMethodDecl *MD, 3279 ReturnValueSlot ReturnValue); 3280 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 3281 3282 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 3283 ReturnValueSlot ReturnValue); 3284 3285 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E, 3286 ReturnValueSlot ReturnValue); 3287 3288 RValue EmitBuiltinExpr(const FunctionDecl *FD, 3289 unsigned BuiltinID, const CallExpr *E, 3290 ReturnValueSlot ReturnValue); 3291 3292 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 3293 3294 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 3295 /// is unhandled by the current target. 3296 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3297 3298 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 3299 const llvm::CmpInst::Predicate Fp, 3300 const llvm::CmpInst::Predicate Ip, 3301 const llvm::Twine &Name = ""); 3302 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3303 3304 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 3305 unsigned LLVMIntrinsic, 3306 unsigned AltLLVMIntrinsic, 3307 const char *NameHint, 3308 unsigned Modifier, 3309 const CallExpr *E, 3310 SmallVectorImpl<llvm::Value *> &Ops, 3311 Address PtrOp0, Address PtrOp1); 3312 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 3313 unsigned Modifier, llvm::Type *ArgTy, 3314 const CallExpr *E); 3315 llvm::Value *EmitNeonCall(llvm::Function *F, 3316 SmallVectorImpl<llvm::Value*> &O, 3317 const char *name, 3318 unsigned shift = 0, bool rightshift = false); 3319 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 3320 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 3321 bool negateForRightShift); 3322 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 3323 llvm::Type *Ty, bool usgn, const char *name); 3324 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 3325 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3326 3327 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 3328 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3329 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3330 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3331 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3332 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 3333 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, 3334 const CallExpr *E); 3335 3336 private: 3337 enum class MSVCIntrin; 3338 3339 public: 3340 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E); 3341 3342 llvm::Value *EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args); 3343 3344 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 3345 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 3346 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 3347 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 3348 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 3349 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 3350 const ObjCMethodDecl *MethodWithObjects); 3351 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 3352 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 3353 ReturnValueSlot Return = ReturnValueSlot()); 3354 3355 /// Retrieves the default cleanup kind for an ARC cleanup. 3356 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 3357 CleanupKind getARCCleanupKind() { 3358 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 3359 ? NormalAndEHCleanup : NormalCleanup; 3360 } 3361 3362 // ARC primitives. 3363 void EmitARCInitWeak(Address addr, llvm::Value *value); 3364 void EmitARCDestroyWeak(Address addr); 3365 llvm::Value *EmitARCLoadWeak(Address addr); 3366 llvm::Value *EmitARCLoadWeakRetained(Address addr); 3367 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored); 3368 void EmitARCCopyWeak(Address dst, Address src); 3369 void EmitARCMoveWeak(Address dst, Address src); 3370 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 3371 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 3372 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 3373 bool resultIgnored); 3374 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value, 3375 bool resultIgnored); 3376 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 3377 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 3378 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 3379 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise); 3380 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 3381 llvm::Value *EmitARCAutorelease(llvm::Value *value); 3382 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 3383 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 3384 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 3385 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value); 3386 3387 std::pair<LValue,llvm::Value*> 3388 EmitARCStoreAutoreleasing(const BinaryOperator *e); 3389 std::pair<LValue,llvm::Value*> 3390 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 3391 std::pair<LValue,llvm::Value*> 3392 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored); 3393 3394 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 3395 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 3396 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 3397 3398 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 3399 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e, 3400 bool allowUnsafeClaim); 3401 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 3402 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 3403 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr); 3404 3405 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 3406 3407 static Destroyer destroyARCStrongImprecise; 3408 static Destroyer destroyARCStrongPrecise; 3409 static Destroyer destroyARCWeak; 3410 static Destroyer emitARCIntrinsicUse; 3411 3412 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 3413 llvm::Value *EmitObjCAutoreleasePoolPush(); 3414 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 3415 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 3416 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 3417 3418 /// \brief Emits a reference binding to the passed in expression. 3419 RValue EmitReferenceBindingToExpr(const Expr *E); 3420 3421 //===--------------------------------------------------------------------===// 3422 // Expression Emission 3423 //===--------------------------------------------------------------------===// 3424 3425 // Expressions are broken into three classes: scalar, complex, aggregate. 3426 3427 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 3428 /// scalar type, returning the result. 3429 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 3430 3431 /// Emit a conversion from the specified type to the specified destination 3432 /// type, both of which are LLVM scalar types. 3433 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 3434 QualType DstTy, SourceLocation Loc); 3435 3436 /// Emit a conversion from the specified complex type to the specified 3437 /// destination type, where the destination type is an LLVM scalar type. 3438 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 3439 QualType DstTy, 3440 SourceLocation Loc); 3441 3442 /// EmitAggExpr - Emit the computation of the specified expression 3443 /// of aggregate type. The result is computed into the given slot, 3444 /// which may be null to indicate that the value is not needed. 3445 void EmitAggExpr(const Expr *E, AggValueSlot AS); 3446 3447 /// EmitAggExprToLValue - Emit the computation of the specified expression of 3448 /// aggregate type into a temporary LValue. 3449 LValue EmitAggExprToLValue(const Expr *E); 3450 3451 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 3452 /// make sure it survives garbage collection until this point. 3453 void EmitExtendGCLifetime(llvm::Value *object); 3454 3455 /// EmitComplexExpr - Emit the computation of the specified expression of 3456 /// complex type, returning the result. 3457 ComplexPairTy EmitComplexExpr(const Expr *E, 3458 bool IgnoreReal = false, 3459 bool IgnoreImag = false); 3460 3461 /// EmitComplexExprIntoLValue - Emit the given expression of complex 3462 /// type and place its result into the specified l-value. 3463 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 3464 3465 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 3466 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 3467 3468 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 3469 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 3470 3471 Address emitAddrOfRealComponent(Address complex, QualType complexType); 3472 Address emitAddrOfImagComponent(Address complex, QualType complexType); 3473 3474 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 3475 /// global variable that has already been created for it. If the initializer 3476 /// has a different type than GV does, this may free GV and return a different 3477 /// one. Otherwise it just returns GV. 3478 llvm::GlobalVariable * 3479 AddInitializerToStaticVarDecl(const VarDecl &D, 3480 llvm::GlobalVariable *GV); 3481 3482 3483 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 3484 /// variable with global storage. 3485 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr, 3486 bool PerformInit); 3487 3488 llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor, 3489 llvm::Constant *Addr); 3490 3491 /// Call atexit() with a function that passes the given argument to 3492 /// the given function. 3493 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn, 3494 llvm::Constant *addr); 3495 3496 /// Emit code in this function to perform a guarded variable 3497 /// initialization. Guarded initializations are used when it's not 3498 /// possible to prove that an initialization will be done exactly 3499 /// once, e.g. with a static local variable or a static data member 3500 /// of a class template. 3501 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 3502 bool PerformInit); 3503 3504 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 3505 /// variables. 3506 void GenerateCXXGlobalInitFunc(llvm::Function *Fn, 3507 ArrayRef<llvm::Function *> CXXThreadLocals, 3508 Address Guard = Address::invalid()); 3509 3510 /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global 3511 /// variables. 3512 void GenerateCXXGlobalDtorsFunc( 3513 llvm::Function *Fn, 3514 const std::vector<std::pair<llvm::WeakTrackingVH, llvm::Constant *>> 3515 &DtorsAndObjects); 3516 3517 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 3518 const VarDecl *D, 3519 llvm::GlobalVariable *Addr, 3520 bool PerformInit); 3521 3522 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 3523 3524 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp); 3525 3526 void enterFullExpression(const ExprWithCleanups *E) { 3527 if (E->getNumObjects() == 0) return; 3528 enterNonTrivialFullExpression(E); 3529 } 3530 void enterNonTrivialFullExpression(const ExprWithCleanups *E); 3531 3532 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 3533 3534 void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest); 3535 3536 RValue EmitAtomicExpr(AtomicExpr *E); 3537 3538 //===--------------------------------------------------------------------===// 3539 // Annotations Emission 3540 //===--------------------------------------------------------------------===// 3541 3542 /// Emit an annotation call (intrinsic or builtin). 3543 llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn, 3544 llvm::Value *AnnotatedVal, 3545 StringRef AnnotationStr, 3546 SourceLocation Location); 3547 3548 /// Emit local annotations for the local variable V, declared by D. 3549 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 3550 3551 /// Emit field annotations for the given field & value. Returns the 3552 /// annotation result. 3553 Address EmitFieldAnnotations(const FieldDecl *D, Address V); 3554 3555 //===--------------------------------------------------------------------===// 3556 // Internal Helpers 3557 //===--------------------------------------------------------------------===// 3558 3559 /// ContainsLabel - Return true if the statement contains a label in it. If 3560 /// this statement is not executed normally, it not containing a label means 3561 /// that we can just remove the code. 3562 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 3563 3564 /// containsBreak - Return true if the statement contains a break out of it. 3565 /// If the statement (recursively) contains a switch or loop with a break 3566 /// inside of it, this is fine. 3567 static bool containsBreak(const Stmt *S); 3568 3569 /// Determine if the given statement might introduce a declaration into the 3570 /// current scope, by being a (possibly-labelled) DeclStmt. 3571 static bool mightAddDeclToScope(const Stmt *S); 3572 3573 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 3574 /// to a constant, or if it does but contains a label, return false. If it 3575 /// constant folds return true and set the boolean result in Result. 3576 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, 3577 bool AllowLabels = false); 3578 3579 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 3580 /// to a constant, or if it does but contains a label, return false. If it 3581 /// constant folds return true and set the folded value. 3582 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result, 3583 bool AllowLabels = false); 3584 3585 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 3586 /// if statement) to the specified blocks. Based on the condition, this might 3587 /// try to simplify the codegen of the conditional based on the branch. 3588 /// TrueCount should be the number of times we expect the condition to 3589 /// evaluate to true based on PGO data. 3590 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 3591 llvm::BasicBlock *FalseBlock, uint64_t TrueCount); 3592 3593 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is 3594 /// nonnull, if \p LHS is marked _Nonnull. 3595 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc); 3596 3597 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to 3598 /// detect undefined behavior when the pointer overflow sanitizer is enabled. 3599 /// \p SignedIndices indicates whether any of the GEP indices are signed. 3600 llvm::Value *EmitCheckedInBoundsGEP(llvm::Value *Ptr, 3601 ArrayRef<llvm::Value *> IdxList, 3602 bool SignedIndices, 3603 SourceLocation Loc, 3604 const Twine &Name = ""); 3605 3606 /// \brief Emit a description of a type in a format suitable for passing to 3607 /// a runtime sanitizer handler. 3608 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 3609 3610 /// \brief Convert a value into a format suitable for passing to a runtime 3611 /// sanitizer handler. 3612 llvm::Value *EmitCheckValue(llvm::Value *V); 3613 3614 /// \brief Emit a description of a source location in a format suitable for 3615 /// passing to a runtime sanitizer handler. 3616 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 3617 3618 /// \brief Create a basic block that will call a handler function in a 3619 /// sanitizer runtime with the provided arguments, and create a conditional 3620 /// branch to it. 3621 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 3622 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs, 3623 ArrayRef<llvm::Value *> DynamicArgs); 3624 3625 /// \brief Emit a slow path cross-DSO CFI check which calls __cfi_slowpath 3626 /// if Cond if false. 3627 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, 3628 llvm::ConstantInt *TypeId, llvm::Value *Ptr, 3629 ArrayRef<llvm::Constant *> StaticArgs); 3630 3631 /// \brief Create a basic block that will call the trap intrinsic, and emit a 3632 /// conditional branch to it, for the -ftrapv checks. 3633 void EmitTrapCheck(llvm::Value *Checked); 3634 3635 /// \brief Emit a call to trap or debugtrap and attach function attribute 3636 /// "trap-func-name" if specified. 3637 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID); 3638 3639 /// \brief Emit a stub for the cross-DSO CFI check function. 3640 void EmitCfiCheckStub(); 3641 3642 /// \brief Emit a cross-DSO CFI failure handling function. 3643 void EmitCfiCheckFail(); 3644 3645 /// \brief Create a check for a function parameter that may potentially be 3646 /// declared as non-null. 3647 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, 3648 AbstractCallee AC, unsigned ParmNum); 3649 3650 /// EmitCallArg - Emit a single call argument. 3651 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 3652 3653 /// EmitDelegateCallArg - We are performing a delegate call; that 3654 /// is, the current function is delegating to another one. Produce 3655 /// a r-value suitable for passing the given parameter. 3656 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 3657 SourceLocation loc); 3658 3659 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 3660 /// point operation, expressed as the maximum relative error in ulp. 3661 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 3662 3663 private: 3664 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 3665 void EmitReturnOfRValue(RValue RV, QualType Ty); 3666 3667 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 3668 3669 llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4> 3670 DeferredReplacements; 3671 3672 /// Set the address of a local variable. 3673 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 3674 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 3675 LocalDeclMap.insert({VD, Addr}); 3676 } 3677 3678 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 3679 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 3680 /// 3681 /// \param AI - The first function argument of the expansion. 3682 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 3683 SmallVectorImpl<llvm::Value *>::iterator &AI); 3684 3685 /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg 3686 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 3687 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 3688 void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 3689 SmallVectorImpl<llvm::Value *> &IRCallArgs, 3690 unsigned &IRCallArgPos); 3691 3692 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 3693 const Expr *InputExpr, std::string &ConstraintStr); 3694 3695 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 3696 LValue InputValue, QualType InputType, 3697 std::string &ConstraintStr, 3698 SourceLocation Loc); 3699 3700 /// \brief Attempts to statically evaluate the object size of E. If that 3701 /// fails, emits code to figure the size of E out for us. This is 3702 /// pass_object_size aware. 3703 /// 3704 /// If EmittedExpr is non-null, this will use that instead of re-emitting E. 3705 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 3706 llvm::IntegerType *ResType, 3707 llvm::Value *EmittedE); 3708 3709 /// \brief Emits the size of E, as required by __builtin_object_size. This 3710 /// function is aware of pass_object_size parameters, and will act accordingly 3711 /// if E is a parameter with the pass_object_size attribute. 3712 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 3713 llvm::IntegerType *ResType, 3714 llvm::Value *EmittedE); 3715 3716 public: 3717 #ifndef NDEBUG 3718 // Determine whether the given argument is an Objective-C method 3719 // that may have type parameters in its signature. 3720 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) { 3721 const DeclContext *dc = method->getDeclContext(); 3722 if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) { 3723 return classDecl->getTypeParamListAsWritten(); 3724 } 3725 3726 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) { 3727 return catDecl->getTypeParamList(); 3728 } 3729 3730 return false; 3731 } 3732 3733 template<typename T> 3734 static bool isObjCMethodWithTypeParams(const T *) { return false; } 3735 #endif 3736 3737 enum class EvaluationOrder { 3738 ///! No language constraints on evaluation order. 3739 Default, 3740 ///! Language semantics require left-to-right evaluation. 3741 ForceLeftToRight, 3742 ///! Language semantics require right-to-left evaluation. 3743 ForceRightToLeft 3744 }; 3745 3746 /// EmitCallArgs - Emit call arguments for a function. 3747 template <typename T> 3748 void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo, 3749 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3750 AbstractCallee AC = AbstractCallee(), 3751 unsigned ParamsToSkip = 0, 3752 EvaluationOrder Order = EvaluationOrder::Default) { 3753 SmallVector<QualType, 16> ArgTypes; 3754 CallExpr::const_arg_iterator Arg = ArgRange.begin(); 3755 3756 assert((ParamsToSkip == 0 || CallArgTypeInfo) && 3757 "Can't skip parameters if type info is not provided"); 3758 if (CallArgTypeInfo) { 3759 #ifndef NDEBUG 3760 bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo); 3761 #endif 3762 3763 // First, use the argument types that the type info knows about 3764 for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip, 3765 E = CallArgTypeInfo->param_type_end(); 3766 I != E; ++I, ++Arg) { 3767 assert(Arg != ArgRange.end() && "Running over edge of argument list!"); 3768 assert((isGenericMethod || 3769 ((*I)->isVariablyModifiedType() || 3770 (*I).getNonReferenceType()->isObjCRetainableType() || 3771 getContext() 3772 .getCanonicalType((*I).getNonReferenceType()) 3773 .getTypePtr() == 3774 getContext() 3775 .getCanonicalType((*Arg)->getType()) 3776 .getTypePtr())) && 3777 "type mismatch in call argument!"); 3778 ArgTypes.push_back(*I); 3779 } 3780 } 3781 3782 // Either we've emitted all the call args, or we have a call to variadic 3783 // function. 3784 assert((Arg == ArgRange.end() || !CallArgTypeInfo || 3785 CallArgTypeInfo->isVariadic()) && 3786 "Extra arguments in non-variadic function!"); 3787 3788 // If we still have any arguments, emit them using the type of the argument. 3789 for (auto *A : llvm::make_range(Arg, ArgRange.end())) 3790 ArgTypes.push_back(CallArgTypeInfo ? getVarArgType(A) : A->getType()); 3791 3792 EmitCallArgs(Args, ArgTypes, ArgRange, AC, ParamsToSkip, Order); 3793 } 3794 3795 void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes, 3796 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3797 AbstractCallee AC = AbstractCallee(), 3798 unsigned ParamsToSkip = 0, 3799 EvaluationOrder Order = EvaluationOrder::Default); 3800 3801 /// EmitPointerWithAlignment - Given an expression with a pointer type, 3802 /// emit the value and compute our best estimate of the alignment of the 3803 /// pointee. 3804 /// 3805 /// \param BaseInfo - If non-null, this will be initialized with 3806 /// information about the source of the alignment and the may-alias 3807 /// attribute. Note that this function will conservatively fall back on 3808 /// the type when it doesn't recognize the expression and may-alias will 3809 /// be set to false. 3810 /// 3811 /// One reasonable way to use this information is when there's a language 3812 /// guarantee that the pointer must be aligned to some stricter value, and 3813 /// we're simply trying to ensure that sufficiently obvious uses of under- 3814 /// aligned objects don't get miscompiled; for example, a placement new 3815 /// into the address of a local variable. In such a case, it's quite 3816 /// reasonable to just ignore the returned alignment when it isn't from an 3817 /// explicit source. 3818 Address EmitPointerWithAlignment(const Expr *Addr, 3819 LValueBaseInfo *BaseInfo = nullptr); 3820 3821 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 3822 3823 private: 3824 QualType getVarArgType(const Expr *Arg); 3825 3826 void EmitDeclMetadata(); 3827 3828 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 3829 const AutoVarEmission &emission); 3830 3831 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 3832 3833 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 3834 }; 3835 3836 /// Helper class with most of the code for saving a value for a 3837 /// conditional expression cleanup. 3838 struct DominatingLLVMValue { 3839 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 3840 3841 /// Answer whether the given value needs extra work to be saved. 3842 static bool needsSaving(llvm::Value *value) { 3843 // If it's not an instruction, we don't need to save. 3844 if (!isa<llvm::Instruction>(value)) return false; 3845 3846 // If it's an instruction in the entry block, we don't need to save. 3847 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 3848 return (block != &block->getParent()->getEntryBlock()); 3849 } 3850 3851 /// Try to save the given value. 3852 static saved_type save(CodeGenFunction &CGF, llvm::Value *value) { 3853 if (!needsSaving(value)) return saved_type(value, false); 3854 3855 // Otherwise, we need an alloca. 3856 auto align = CharUnits::fromQuantity( 3857 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 3858 Address alloca = 3859 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 3860 CGF.Builder.CreateStore(value, alloca); 3861 3862 return saved_type(alloca.getPointer(), true); 3863 } 3864 3865 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) { 3866 // If the value says it wasn't saved, trust that it's still dominating. 3867 if (!value.getInt()) return value.getPointer(); 3868 3869 // Otherwise, it should be an alloca instruction, as set up in save(). 3870 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 3871 return CGF.Builder.CreateAlignedLoad(alloca, alloca->getAlignment()); 3872 } 3873 }; 3874 3875 /// A partial specialization of DominatingValue for llvm::Values that 3876 /// might be llvm::Instructions. 3877 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 3878 typedef T *type; 3879 static type restore(CodeGenFunction &CGF, saved_type value) { 3880 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 3881 } 3882 }; 3883 3884 /// A specialization of DominatingValue for Address. 3885 template <> struct DominatingValue<Address> { 3886 typedef Address type; 3887 3888 struct saved_type { 3889 DominatingLLVMValue::saved_type SavedValue; 3890 CharUnits Alignment; 3891 }; 3892 3893 static bool needsSaving(type value) { 3894 return DominatingLLVMValue::needsSaving(value.getPointer()); 3895 } 3896 static saved_type save(CodeGenFunction &CGF, type value) { 3897 return { DominatingLLVMValue::save(CGF, value.getPointer()), 3898 value.getAlignment() }; 3899 } 3900 static type restore(CodeGenFunction &CGF, saved_type value) { 3901 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue), 3902 value.Alignment); 3903 } 3904 }; 3905 3906 /// A specialization of DominatingValue for RValue. 3907 template <> struct DominatingValue<RValue> { 3908 typedef RValue type; 3909 class saved_type { 3910 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 3911 AggregateAddress, ComplexAddress }; 3912 3913 llvm::Value *Value; 3914 unsigned K : 3; 3915 unsigned Align : 29; 3916 saved_type(llvm::Value *v, Kind k, unsigned a = 0) 3917 : Value(v), K(k), Align(a) {} 3918 3919 public: 3920 static bool needsSaving(RValue value); 3921 static saved_type save(CodeGenFunction &CGF, RValue value); 3922 RValue restore(CodeGenFunction &CGF); 3923 3924 // implementations in CGCleanup.cpp 3925 }; 3926 3927 static bool needsSaving(type value) { 3928 return saved_type::needsSaving(value); 3929 } 3930 static saved_type save(CodeGenFunction &CGF, type value) { 3931 return saved_type::save(CGF, value); 3932 } 3933 static type restore(CodeGenFunction &CGF, saved_type value) { 3934 return value.restore(CGF); 3935 } 3936 }; 3937 3938 } // end namespace CodeGen 3939 } // end namespace clang 3940 3941 #endif 3942