1 //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is the internal per-function state used for llvm translation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 14 #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H 15 16 #include "CGBuilder.h" 17 #include "CGDebugInfo.h" 18 #include "CGLoopInfo.h" 19 #include "CGValue.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "EHScopeStack.h" 23 #include "VarBypassDetector.h" 24 #include "clang/AST/CharUnits.h" 25 #include "clang/AST/CurrentSourceLocExprScope.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/StmtOpenMP.h" 30 #include "clang/AST/Type.h" 31 #include "clang/Basic/ABI.h" 32 #include "clang/Basic/CapturedStmt.h" 33 #include "clang/Basic/CodeGenOptions.h" 34 #include "clang/Basic/OpenMPKinds.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "llvm/ADT/ArrayRef.h" 37 #include "llvm/ADT/DenseMap.h" 38 #include "llvm/ADT/MapVector.h" 39 #include "llvm/ADT/SmallVector.h" 40 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 41 #include "llvm/IR/ValueHandle.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Transforms/Utils/SanitizerStats.h" 44 45 namespace llvm { 46 class BasicBlock; 47 class LLVMContext; 48 class MDNode; 49 class Module; 50 class SwitchInst; 51 class Twine; 52 class Value; 53 class CanonicalLoopInfo; 54 } 55 56 namespace clang { 57 class ASTContext; 58 class BlockDecl; 59 class CXXDestructorDecl; 60 class CXXForRangeStmt; 61 class CXXTryStmt; 62 class Decl; 63 class LabelDecl; 64 class EnumConstantDecl; 65 class FunctionDecl; 66 class FunctionProtoType; 67 class LabelStmt; 68 class ObjCContainerDecl; 69 class ObjCInterfaceDecl; 70 class ObjCIvarDecl; 71 class ObjCMethodDecl; 72 class ObjCImplementationDecl; 73 class ObjCPropertyImplDecl; 74 class TargetInfo; 75 class VarDecl; 76 class ObjCForCollectionStmt; 77 class ObjCAtTryStmt; 78 class ObjCAtThrowStmt; 79 class ObjCAtSynchronizedStmt; 80 class ObjCAutoreleasePoolStmt; 81 class OMPUseDevicePtrClause; 82 class OMPUseDeviceAddrClause; 83 class ReturnsNonNullAttr; 84 class SVETypeFlags; 85 class OMPExecutableDirective; 86 87 namespace analyze_os_log { 88 class OSLogBufferLayout; 89 } 90 91 namespace CodeGen { 92 class CodeGenTypes; 93 class CGCallee; 94 class CGFunctionInfo; 95 class CGRecordLayout; 96 class CGBlockInfo; 97 class CGCXXABI; 98 class BlockByrefHelpers; 99 class BlockByrefInfo; 100 class BlockFlags; 101 class BlockFieldFlags; 102 class RegionCodeGenTy; 103 class TargetCodeGenInfo; 104 struct OMPTaskDataTy; 105 struct CGCoroData; 106 107 /// The kind of evaluation to perform on values of a particular 108 /// type. Basically, is the code in CGExprScalar, CGExprComplex, or 109 /// CGExprAgg? 110 /// 111 /// TODO: should vectors maybe be split out into their own thing? 112 enum TypeEvaluationKind { 113 TEK_Scalar, 114 TEK_Complex, 115 TEK_Aggregate 116 }; 117 118 #define LIST_SANITIZER_CHECKS \ 119 SANITIZER_CHECK(AddOverflow, add_overflow, 0) \ 120 SANITIZER_CHECK(BuiltinUnreachable, builtin_unreachable, 0) \ 121 SANITIZER_CHECK(CFICheckFail, cfi_check_fail, 0) \ 122 SANITIZER_CHECK(DivremOverflow, divrem_overflow, 0) \ 123 SANITIZER_CHECK(DynamicTypeCacheMiss, dynamic_type_cache_miss, 0) \ 124 SANITIZER_CHECK(FloatCastOverflow, float_cast_overflow, 0) \ 125 SANITIZER_CHECK(FunctionTypeMismatch, function_type_mismatch, 1) \ 126 SANITIZER_CHECK(ImplicitConversion, implicit_conversion, 0) \ 127 SANITIZER_CHECK(InvalidBuiltin, invalid_builtin, 0) \ 128 SANITIZER_CHECK(InvalidObjCCast, invalid_objc_cast, 0) \ 129 SANITIZER_CHECK(LoadInvalidValue, load_invalid_value, 0) \ 130 SANITIZER_CHECK(MissingReturn, missing_return, 0) \ 131 SANITIZER_CHECK(MulOverflow, mul_overflow, 0) \ 132 SANITIZER_CHECK(NegateOverflow, negate_overflow, 0) \ 133 SANITIZER_CHECK(NullabilityArg, nullability_arg, 0) \ 134 SANITIZER_CHECK(NullabilityReturn, nullability_return, 1) \ 135 SANITIZER_CHECK(NonnullArg, nonnull_arg, 0) \ 136 SANITIZER_CHECK(NonnullReturn, nonnull_return, 1) \ 137 SANITIZER_CHECK(OutOfBounds, out_of_bounds, 0) \ 138 SANITIZER_CHECK(PointerOverflow, pointer_overflow, 0) \ 139 SANITIZER_CHECK(ShiftOutOfBounds, shift_out_of_bounds, 0) \ 140 SANITIZER_CHECK(SubOverflow, sub_overflow, 0) \ 141 SANITIZER_CHECK(TypeMismatch, type_mismatch, 1) \ 142 SANITIZER_CHECK(AlignmentAssumption, alignment_assumption, 0) \ 143 SANITIZER_CHECK(VLABoundNotPositive, vla_bound_not_positive, 0) 144 145 enum SanitizerHandler { 146 #define SANITIZER_CHECK(Enum, Name, Version) Enum, 147 LIST_SANITIZER_CHECKS 148 #undef SANITIZER_CHECK 149 }; 150 151 /// Helper class with most of the code for saving a value for a 152 /// conditional expression cleanup. 153 struct DominatingLLVMValue { 154 typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type; 155 156 /// Answer whether the given value needs extra work to be saved. 157 static bool needsSaving(llvm::Value *value) { 158 // If it's not an instruction, we don't need to save. 159 if (!isa<llvm::Instruction>(value)) return false; 160 161 // If it's an instruction in the entry block, we don't need to save. 162 llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent(); 163 return (block != &block->getParent()->getEntryBlock()); 164 } 165 166 static saved_type save(CodeGenFunction &CGF, llvm::Value *value); 167 static llvm::Value *restore(CodeGenFunction &CGF, saved_type value); 168 }; 169 170 /// A partial specialization of DominatingValue for llvm::Values that 171 /// might be llvm::Instructions. 172 template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue { 173 typedef T *type; 174 static type restore(CodeGenFunction &CGF, saved_type value) { 175 return static_cast<T*>(DominatingLLVMValue::restore(CGF, value)); 176 } 177 }; 178 179 /// A specialization of DominatingValue for Address. 180 template <> struct DominatingValue<Address> { 181 typedef Address type; 182 183 struct saved_type { 184 DominatingLLVMValue::saved_type SavedValue; 185 CharUnits Alignment; 186 }; 187 188 static bool needsSaving(type value) { 189 return DominatingLLVMValue::needsSaving(value.getPointer()); 190 } 191 static saved_type save(CodeGenFunction &CGF, type value) { 192 return { DominatingLLVMValue::save(CGF, value.getPointer()), 193 value.getAlignment() }; 194 } 195 static type restore(CodeGenFunction &CGF, saved_type value) { 196 return Address(DominatingLLVMValue::restore(CGF, value.SavedValue), 197 value.Alignment); 198 } 199 }; 200 201 /// A specialization of DominatingValue for RValue. 202 template <> struct DominatingValue<RValue> { 203 typedef RValue type; 204 class saved_type { 205 enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral, 206 AggregateAddress, ComplexAddress }; 207 208 llvm::Value *Value; 209 unsigned K : 3; 210 unsigned Align : 29; 211 saved_type(llvm::Value *v, Kind k, unsigned a = 0) 212 : Value(v), K(k), Align(a) {} 213 214 public: 215 static bool needsSaving(RValue value); 216 static saved_type save(CodeGenFunction &CGF, RValue value); 217 RValue restore(CodeGenFunction &CGF); 218 219 // implementations in CGCleanup.cpp 220 }; 221 222 static bool needsSaving(type value) { 223 return saved_type::needsSaving(value); 224 } 225 static saved_type save(CodeGenFunction &CGF, type value) { 226 return saved_type::save(CGF, value); 227 } 228 static type restore(CodeGenFunction &CGF, saved_type value) { 229 return value.restore(CGF); 230 } 231 }; 232 233 /// CodeGenFunction - This class organizes the per-function state that is used 234 /// while generating LLVM code. 235 class CodeGenFunction : public CodeGenTypeCache { 236 CodeGenFunction(const CodeGenFunction &) = delete; 237 void operator=(const CodeGenFunction &) = delete; 238 239 friend class CGCXXABI; 240 public: 241 /// A jump destination is an abstract label, branching to which may 242 /// require a jump out through normal cleanups. 243 struct JumpDest { 244 JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {} 245 JumpDest(llvm::BasicBlock *Block, 246 EHScopeStack::stable_iterator Depth, 247 unsigned Index) 248 : Block(Block), ScopeDepth(Depth), Index(Index) {} 249 250 bool isValid() const { return Block != nullptr; } 251 llvm::BasicBlock *getBlock() const { return Block; } 252 EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; } 253 unsigned getDestIndex() const { return Index; } 254 255 // This should be used cautiously. 256 void setScopeDepth(EHScopeStack::stable_iterator depth) { 257 ScopeDepth = depth; 258 } 259 260 private: 261 llvm::BasicBlock *Block; 262 EHScopeStack::stable_iterator ScopeDepth; 263 unsigned Index; 264 }; 265 266 CodeGenModule &CGM; // Per-module state. 267 const TargetInfo &Target; 268 269 // For EH/SEH outlined funclets, this field points to parent's CGF 270 CodeGenFunction *ParentCGF = nullptr; 271 272 typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy; 273 LoopInfoStack LoopStack; 274 CGBuilderTy Builder; 275 276 // Stores variables for which we can't generate correct lifetime markers 277 // because of jumps. 278 VarBypassDetector Bypasses; 279 280 /// List of recently emitted OMPCanonicalLoops. 281 /// 282 /// Since OMPCanonicalLoops are nested inside other statements (in particular 283 /// CapturedStmt generated by OMPExecutableDirective and non-perfectly nested 284 /// loops), we cannot directly call OMPEmitOMPCanonicalLoop and receive its 285 /// llvm::CanonicalLoopInfo. Instead, we call EmitStmt and any 286 /// OMPEmitOMPCanonicalLoop called by it will add its CanonicalLoopInfo to 287 /// this stack when done. Entering a new loop requires clearing this list; it 288 /// either means we start parsing a new loop nest (in which case the previous 289 /// loop nest goes out of scope) or a second loop in the same level in which 290 /// case it would be ambiguous into which of the two (or more) loops the loop 291 /// nest would extend. 292 SmallVector<llvm::CanonicalLoopInfo *, 4> OMPLoopNestStack; 293 294 /// Number of nested loop to be consumed by the last surrounding 295 /// loop-associated directive. 296 int ExpectedOMPLoopDepth = 0; 297 298 // CodeGen lambda for loops and support for ordered clause 299 typedef llvm::function_ref<void(CodeGenFunction &, const OMPLoopDirective &, 300 JumpDest)> 301 CodeGenLoopTy; 302 typedef llvm::function_ref<void(CodeGenFunction &, SourceLocation, 303 const unsigned, const bool)> 304 CodeGenOrderedTy; 305 306 // Codegen lambda for loop bounds in worksharing loop constructs 307 typedef llvm::function_ref<std::pair<LValue, LValue>( 308 CodeGenFunction &, const OMPExecutableDirective &S)> 309 CodeGenLoopBoundsTy; 310 311 // Codegen lambda for loop bounds in dispatch-based loop implementation 312 typedef llvm::function_ref<std::pair<llvm::Value *, llvm::Value *>( 313 CodeGenFunction &, const OMPExecutableDirective &S, Address LB, 314 Address UB)> 315 CodeGenDispatchBoundsTy; 316 317 /// CGBuilder insert helper. This function is called after an 318 /// instruction is created using Builder. 319 void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, 320 llvm::BasicBlock *BB, 321 llvm::BasicBlock::iterator InsertPt) const; 322 323 /// CurFuncDecl - Holds the Decl for the current outermost 324 /// non-closure context. 325 const Decl *CurFuncDecl; 326 /// CurCodeDecl - This is the inner-most code context, which includes blocks. 327 const Decl *CurCodeDecl; 328 const CGFunctionInfo *CurFnInfo; 329 QualType FnRetTy; 330 llvm::Function *CurFn = nullptr; 331 332 /// Save Parameter Decl for coroutine. 333 llvm::SmallVector<const ParmVarDecl *, 4> FnArgs; 334 335 // Holds coroutine data if the current function is a coroutine. We use a 336 // wrapper to manage its lifetime, so that we don't have to define CGCoroData 337 // in this header. 338 struct CGCoroInfo { 339 std::unique_ptr<CGCoroData> Data; 340 CGCoroInfo(); 341 ~CGCoroInfo(); 342 }; 343 CGCoroInfo CurCoro; 344 345 bool isCoroutine() const { 346 return CurCoro.Data != nullptr; 347 } 348 349 /// CurGD - The GlobalDecl for the current function being compiled. 350 GlobalDecl CurGD; 351 352 /// PrologueCleanupDepth - The cleanup depth enclosing all the 353 /// cleanups associated with the parameters. 354 EHScopeStack::stable_iterator PrologueCleanupDepth; 355 356 /// ReturnBlock - Unified return block. 357 JumpDest ReturnBlock; 358 359 /// ReturnValue - The temporary alloca to hold the return 360 /// value. This is invalid iff the function has no return value. 361 Address ReturnValue = Address::invalid(); 362 363 /// ReturnValuePointer - The temporary alloca to hold a pointer to sret. 364 /// This is invalid if sret is not in use. 365 Address ReturnValuePointer = Address::invalid(); 366 367 /// If a return statement is being visited, this holds the return statment's 368 /// result expression. 369 const Expr *RetExpr = nullptr; 370 371 /// Return true if a label was seen in the current scope. 372 bool hasLabelBeenSeenInCurrentScope() const { 373 if (CurLexicalScope) 374 return CurLexicalScope->hasLabels(); 375 return !LabelMap.empty(); 376 } 377 378 /// AllocaInsertPoint - This is an instruction in the entry block before which 379 /// we prefer to insert allocas. 380 llvm::AssertingVH<llvm::Instruction> AllocaInsertPt; 381 382 private: 383 /// PostAllocaInsertPt - This is a place in the prologue where code can be 384 /// inserted that will be dominated by all the static allocas. This helps 385 /// achieve two things: 386 /// 1. Contiguity of all static allocas (within the prologue) is maintained. 387 /// 2. All other prologue code (which are dominated by static allocas) do 388 /// appear in the source order immediately after all static allocas. 389 /// 390 /// PostAllocaInsertPt will be lazily created when it is *really* required. 391 llvm::AssertingVH<llvm::Instruction> PostAllocaInsertPt = nullptr; 392 393 public: 394 /// Return PostAllocaInsertPt. If it is not yet created, then insert it 395 /// immediately after AllocaInsertPt. 396 llvm::Instruction *getPostAllocaInsertPoint() { 397 if (!PostAllocaInsertPt) { 398 assert(AllocaInsertPt && 399 "Expected static alloca insertion point at function prologue"); 400 assert(AllocaInsertPt->getParent()->isEntryBlock() && 401 "EBB should be entry block of the current code gen function"); 402 PostAllocaInsertPt = AllocaInsertPt->clone(); 403 PostAllocaInsertPt->setName("postallocapt"); 404 PostAllocaInsertPt->insertAfter(AllocaInsertPt); 405 } 406 407 return PostAllocaInsertPt; 408 } 409 410 /// API for captured statement code generation. 411 class CGCapturedStmtInfo { 412 public: 413 explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default) 414 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {} 415 explicit CGCapturedStmtInfo(const CapturedStmt &S, 416 CapturedRegionKind K = CR_Default) 417 : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) { 418 419 RecordDecl::field_iterator Field = 420 S.getCapturedRecordDecl()->field_begin(); 421 for (CapturedStmt::const_capture_iterator I = S.capture_begin(), 422 E = S.capture_end(); 423 I != E; ++I, ++Field) { 424 if (I->capturesThis()) 425 CXXThisFieldDecl = *Field; 426 else if (I->capturesVariable()) 427 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field; 428 else if (I->capturesVariableByCopy()) 429 CaptureFields[I->getCapturedVar()->getCanonicalDecl()] = *Field; 430 } 431 } 432 433 virtual ~CGCapturedStmtInfo(); 434 435 CapturedRegionKind getKind() const { return Kind; } 436 437 virtual void setContextValue(llvm::Value *V) { ThisValue = V; } 438 // Retrieve the value of the context parameter. 439 virtual llvm::Value *getContextValue() const { return ThisValue; } 440 441 /// Lookup the captured field decl for a variable. 442 virtual const FieldDecl *lookup(const VarDecl *VD) const { 443 return CaptureFields.lookup(VD->getCanonicalDecl()); 444 } 445 446 bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; } 447 virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; } 448 449 static bool classof(const CGCapturedStmtInfo *) { 450 return true; 451 } 452 453 /// Emit the captured statement body. 454 virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) { 455 CGF.incrementProfileCounter(S); 456 CGF.EmitStmt(S); 457 } 458 459 /// Get the name of the capture helper. 460 virtual StringRef getHelperName() const { return "__captured_stmt"; } 461 462 /// Get the CaptureFields 463 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> getCaptureFields() { 464 return CaptureFields; 465 } 466 467 private: 468 /// The kind of captured statement being generated. 469 CapturedRegionKind Kind; 470 471 /// Keep the map between VarDecl and FieldDecl. 472 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields; 473 474 /// The base address of the captured record, passed in as the first 475 /// argument of the parallel region function. 476 llvm::Value *ThisValue; 477 478 /// Captured 'this' type. 479 FieldDecl *CXXThisFieldDecl; 480 }; 481 CGCapturedStmtInfo *CapturedStmtInfo = nullptr; 482 483 /// RAII for correct setting/restoring of CapturedStmtInfo. 484 class CGCapturedStmtRAII { 485 private: 486 CodeGenFunction &CGF; 487 CGCapturedStmtInfo *PrevCapturedStmtInfo; 488 public: 489 CGCapturedStmtRAII(CodeGenFunction &CGF, 490 CGCapturedStmtInfo *NewCapturedStmtInfo) 491 : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) { 492 CGF.CapturedStmtInfo = NewCapturedStmtInfo; 493 } 494 ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; } 495 }; 496 497 /// An abstract representation of regular/ObjC call/message targets. 498 class AbstractCallee { 499 /// The function declaration of the callee. 500 const Decl *CalleeDecl; 501 502 public: 503 AbstractCallee() : CalleeDecl(nullptr) {} 504 AbstractCallee(const FunctionDecl *FD) : CalleeDecl(FD) {} 505 AbstractCallee(const ObjCMethodDecl *OMD) : CalleeDecl(OMD) {} 506 bool hasFunctionDecl() const { 507 return isa_and_nonnull<FunctionDecl>(CalleeDecl); 508 } 509 const Decl *getDecl() const { return CalleeDecl; } 510 unsigned getNumParams() const { 511 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) 512 return FD->getNumParams(); 513 return cast<ObjCMethodDecl>(CalleeDecl)->param_size(); 514 } 515 const ParmVarDecl *getParamDecl(unsigned I) const { 516 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) 517 return FD->getParamDecl(I); 518 return *(cast<ObjCMethodDecl>(CalleeDecl)->param_begin() + I); 519 } 520 }; 521 522 /// Sanitizers enabled for this function. 523 SanitizerSet SanOpts; 524 525 /// True if CodeGen currently emits code implementing sanitizer checks. 526 bool IsSanitizerScope = false; 527 528 /// RAII object to set/unset CodeGenFunction::IsSanitizerScope. 529 class SanitizerScope { 530 CodeGenFunction *CGF; 531 public: 532 SanitizerScope(CodeGenFunction *CGF); 533 ~SanitizerScope(); 534 }; 535 536 /// In C++, whether we are code generating a thunk. This controls whether we 537 /// should emit cleanups. 538 bool CurFuncIsThunk = false; 539 540 /// In ARC, whether we should autorelease the return value. 541 bool AutoreleaseResult = false; 542 543 /// Whether we processed a Microsoft-style asm block during CodeGen. These can 544 /// potentially set the return value. 545 bool SawAsmBlock = false; 546 547 const NamedDecl *CurSEHParent = nullptr; 548 549 /// True if the current function is an outlined SEH helper. This can be a 550 /// finally block or filter expression. 551 bool IsOutlinedSEHHelper = false; 552 553 /// True if CodeGen currently emits code inside presereved access index 554 /// region. 555 bool IsInPreservedAIRegion = false; 556 557 /// True if the current statement has nomerge attribute. 558 bool InNoMergeAttributedStmt = false; 559 560 // The CallExpr within the current statement that the musttail attribute 561 // applies to. nullptr if there is no 'musttail' on the current statement. 562 const CallExpr *MustTailCall = nullptr; 563 564 /// Returns true if a function must make progress, which means the 565 /// mustprogress attribute can be added. 566 bool checkIfFunctionMustProgress() { 567 if (CGM.getCodeGenOpts().getFiniteLoops() == 568 CodeGenOptions::FiniteLoopsKind::Never) 569 return false; 570 571 // C++11 and later guarantees that a thread eventually will do one of the 572 // following (6.9.2.3.1 in C++11): 573 // - terminate, 574 // - make a call to a library I/O function, 575 // - perform an access through a volatile glvalue, or 576 // - perform a synchronization operation or an atomic operation. 577 // 578 // Hence each function is 'mustprogress' in C++11 or later. 579 return getLangOpts().CPlusPlus11; 580 } 581 582 /// Returns true if a loop must make progress, which means the mustprogress 583 /// attribute can be added. \p HasConstantCond indicates whether the branch 584 /// condition is a known constant. 585 bool checkIfLoopMustProgress(bool HasConstantCond) { 586 if (CGM.getCodeGenOpts().getFiniteLoops() == 587 CodeGenOptions::FiniteLoopsKind::Always) 588 return true; 589 if (CGM.getCodeGenOpts().getFiniteLoops() == 590 CodeGenOptions::FiniteLoopsKind::Never) 591 return false; 592 593 // If the containing function must make progress, loops also must make 594 // progress (as in C++11 and later). 595 if (checkIfFunctionMustProgress()) 596 return true; 597 598 // Now apply rules for plain C (see 6.8.5.6 in C11). 599 // Loops with constant conditions do not have to make progress in any C 600 // version. 601 if (HasConstantCond) 602 return false; 603 604 // Loops with non-constant conditions must make progress in C11 and later. 605 return getLangOpts().C11; 606 } 607 608 const CodeGen::CGBlockInfo *BlockInfo = nullptr; 609 llvm::Value *BlockPointer = nullptr; 610 611 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 612 FieldDecl *LambdaThisCaptureField = nullptr; 613 614 /// A mapping from NRVO variables to the flags used to indicate 615 /// when the NRVO has been applied to this variable. 616 llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags; 617 618 EHScopeStack EHStack; 619 llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack; 620 llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack; 621 622 llvm::Instruction *CurrentFuncletPad = nullptr; 623 624 class CallLifetimeEnd final : public EHScopeStack::Cleanup { 625 bool isRedundantBeforeReturn() override { return true; } 626 627 llvm::Value *Addr; 628 llvm::Value *Size; 629 630 public: 631 CallLifetimeEnd(Address addr, llvm::Value *size) 632 : Addr(addr.getPointer()), Size(size) {} 633 634 void Emit(CodeGenFunction &CGF, Flags flags) override { 635 CGF.EmitLifetimeEnd(Size, Addr); 636 } 637 }; 638 639 /// Header for data within LifetimeExtendedCleanupStack. 640 struct LifetimeExtendedCleanupHeader { 641 /// The size of the following cleanup object. 642 unsigned Size; 643 /// The kind of cleanup to push: a value from the CleanupKind enumeration. 644 unsigned Kind : 31; 645 /// Whether this is a conditional cleanup. 646 unsigned IsConditional : 1; 647 648 size_t getSize() const { return Size; } 649 CleanupKind getKind() const { return (CleanupKind)Kind; } 650 bool isConditional() const { return IsConditional; } 651 }; 652 653 /// i32s containing the indexes of the cleanup destinations. 654 Address NormalCleanupDest = Address::invalid(); 655 656 unsigned NextCleanupDestIndex = 1; 657 658 /// EHResumeBlock - Unified block containing a call to llvm.eh.resume. 659 llvm::BasicBlock *EHResumeBlock = nullptr; 660 661 /// The exception slot. All landing pads write the current exception pointer 662 /// into this alloca. 663 llvm::Value *ExceptionSlot = nullptr; 664 665 /// The selector slot. Under the MandatoryCleanup model, all landing pads 666 /// write the current selector value into this alloca. 667 llvm::AllocaInst *EHSelectorSlot = nullptr; 668 669 /// A stack of exception code slots. Entering an __except block pushes a slot 670 /// on the stack and leaving pops one. The __exception_code() intrinsic loads 671 /// a value from the top of the stack. 672 SmallVector<Address, 1> SEHCodeSlotStack; 673 674 /// Value returned by __exception_info intrinsic. 675 llvm::Value *SEHInfo = nullptr; 676 677 /// Emits a landing pad for the current EH stack. 678 llvm::BasicBlock *EmitLandingPad(); 679 680 llvm::BasicBlock *getInvokeDestImpl(); 681 682 /// Parent loop-based directive for scan directive. 683 const OMPExecutableDirective *OMPParentLoopDirectiveForScan = nullptr; 684 llvm::BasicBlock *OMPBeforeScanBlock = nullptr; 685 llvm::BasicBlock *OMPAfterScanBlock = nullptr; 686 llvm::BasicBlock *OMPScanExitBlock = nullptr; 687 llvm::BasicBlock *OMPScanDispatch = nullptr; 688 bool OMPFirstScanLoop = false; 689 690 /// Manages parent directive for scan directives. 691 class ParentLoopDirectiveForScanRegion { 692 CodeGenFunction &CGF; 693 const OMPExecutableDirective *ParentLoopDirectiveForScan; 694 695 public: 696 ParentLoopDirectiveForScanRegion( 697 CodeGenFunction &CGF, 698 const OMPExecutableDirective &ParentLoopDirectiveForScan) 699 : CGF(CGF), 700 ParentLoopDirectiveForScan(CGF.OMPParentLoopDirectiveForScan) { 701 CGF.OMPParentLoopDirectiveForScan = &ParentLoopDirectiveForScan; 702 } 703 ~ParentLoopDirectiveForScanRegion() { 704 CGF.OMPParentLoopDirectiveForScan = ParentLoopDirectiveForScan; 705 } 706 }; 707 708 template <class T> 709 typename DominatingValue<T>::saved_type saveValueInCond(T value) { 710 return DominatingValue<T>::save(*this, value); 711 } 712 713 class CGFPOptionsRAII { 714 public: 715 CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures); 716 CGFPOptionsRAII(CodeGenFunction &CGF, const Expr *E); 717 ~CGFPOptionsRAII(); 718 719 private: 720 void ConstructorHelper(FPOptions FPFeatures); 721 CodeGenFunction &CGF; 722 FPOptions OldFPFeatures; 723 llvm::fp::ExceptionBehavior OldExcept; 724 llvm::RoundingMode OldRounding; 725 Optional<CGBuilderTy::FastMathFlagGuard> FMFGuard; 726 }; 727 FPOptions CurFPFeatures; 728 729 public: 730 /// ObjCEHValueStack - Stack of Objective-C exception values, used for 731 /// rethrows. 732 SmallVector<llvm::Value*, 8> ObjCEHValueStack; 733 734 /// A class controlling the emission of a finally block. 735 class FinallyInfo { 736 /// Where the catchall's edge through the cleanup should go. 737 JumpDest RethrowDest; 738 739 /// A function to call to enter the catch. 740 llvm::FunctionCallee BeginCatchFn; 741 742 /// An i1 variable indicating whether or not the @finally is 743 /// running for an exception. 744 llvm::AllocaInst *ForEHVar; 745 746 /// An i8* variable into which the exception pointer to rethrow 747 /// has been saved. 748 llvm::AllocaInst *SavedExnVar; 749 750 public: 751 void enter(CodeGenFunction &CGF, const Stmt *Finally, 752 llvm::FunctionCallee beginCatchFn, 753 llvm::FunctionCallee endCatchFn, llvm::FunctionCallee rethrowFn); 754 void exit(CodeGenFunction &CGF); 755 }; 756 757 /// Returns true inside SEH __try blocks. 758 bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); } 759 760 /// Returns true while emitting a cleanuppad. 761 bool isCleanupPadScope() const { 762 return CurrentFuncletPad && isa<llvm::CleanupPadInst>(CurrentFuncletPad); 763 } 764 765 /// pushFullExprCleanup - Push a cleanup to be run at the end of the 766 /// current full-expression. Safe against the possibility that 767 /// we're currently inside a conditionally-evaluated expression. 768 template <class T, class... As> 769 void pushFullExprCleanup(CleanupKind kind, As... A) { 770 // If we're not in a conditional branch, or if none of the 771 // arguments requires saving, then use the unconditional cleanup. 772 if (!isInConditionalBranch()) 773 return EHStack.pushCleanup<T>(kind, A...); 774 775 // Stash values in a tuple so we can guarantee the order of saves. 776 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 777 SavedTuple Saved{saveValueInCond(A)...}; 778 779 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 780 EHStack.pushCleanupTuple<CleanupType>(kind, Saved); 781 initFullExprCleanup(); 782 } 783 784 /// Queue a cleanup to be pushed after finishing the current full-expression, 785 /// potentially with an active flag. 786 template <class T, class... As> 787 void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) { 788 if (!isInConditionalBranch()) 789 return pushCleanupAfterFullExprWithActiveFlag<T>(Kind, Address::invalid(), 790 A...); 791 792 Address ActiveFlag = createCleanupActiveFlag(); 793 assert(!DominatingValue<Address>::needsSaving(ActiveFlag) && 794 "cleanup active flag should never need saving"); 795 796 typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple; 797 SavedTuple Saved{saveValueInCond(A)...}; 798 799 typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType; 800 pushCleanupAfterFullExprWithActiveFlag<CleanupType>(Kind, ActiveFlag, Saved); 801 } 802 803 template <class T, class... As> 804 void pushCleanupAfterFullExprWithActiveFlag(CleanupKind Kind, 805 Address ActiveFlag, As... A) { 806 LifetimeExtendedCleanupHeader Header = {sizeof(T), Kind, 807 ActiveFlag.isValid()}; 808 809 size_t OldSize = LifetimeExtendedCleanupStack.size(); 810 LifetimeExtendedCleanupStack.resize( 811 LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size + 812 (Header.IsConditional ? sizeof(ActiveFlag) : 0)); 813 814 static_assert(sizeof(Header) % alignof(T) == 0, 815 "Cleanup will be allocated on misaligned address"); 816 char *Buffer = &LifetimeExtendedCleanupStack[OldSize]; 817 new (Buffer) LifetimeExtendedCleanupHeader(Header); 818 new (Buffer + sizeof(Header)) T(A...); 819 if (Header.IsConditional) 820 new (Buffer + sizeof(Header) + sizeof(T)) Address(ActiveFlag); 821 } 822 823 /// Set up the last cleanup that was pushed as a conditional 824 /// full-expression cleanup. 825 void initFullExprCleanup() { 826 initFullExprCleanupWithFlag(createCleanupActiveFlag()); 827 } 828 829 void initFullExprCleanupWithFlag(Address ActiveFlag); 830 Address createCleanupActiveFlag(); 831 832 /// PushDestructorCleanup - Push a cleanup to call the 833 /// complete-object destructor of an object of the given type at the 834 /// given address. Does nothing if T is not a C++ class type with a 835 /// non-trivial destructor. 836 void PushDestructorCleanup(QualType T, Address Addr); 837 838 /// PushDestructorCleanup - Push a cleanup to call the 839 /// complete-object variant of the given destructor on the object at 840 /// the given address. 841 void PushDestructorCleanup(const CXXDestructorDecl *Dtor, QualType T, 842 Address Addr); 843 844 /// PopCleanupBlock - Will pop the cleanup entry on the stack and 845 /// process all branch fixups. 846 void PopCleanupBlock(bool FallThroughIsBranchThrough = false); 847 848 /// DeactivateCleanupBlock - Deactivates the given cleanup block. 849 /// The block cannot be reactivated. Pops it if it's the top of the 850 /// stack. 851 /// 852 /// \param DominatingIP - An instruction which is known to 853 /// dominate the current IP (if set) and which lies along 854 /// all paths of execution between the current IP and the 855 /// the point at which the cleanup comes into scope. 856 void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 857 llvm::Instruction *DominatingIP); 858 859 /// ActivateCleanupBlock - Activates an initially-inactive cleanup. 860 /// Cannot be used to resurrect a deactivated cleanup. 861 /// 862 /// \param DominatingIP - An instruction which is known to 863 /// dominate the current IP (if set) and which lies along 864 /// all paths of execution between the current IP and the 865 /// the point at which the cleanup comes into scope. 866 void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, 867 llvm::Instruction *DominatingIP); 868 869 /// Enters a new scope for capturing cleanups, all of which 870 /// will be executed once the scope is exited. 871 class RunCleanupsScope { 872 EHScopeStack::stable_iterator CleanupStackDepth, OldCleanupScopeDepth; 873 size_t LifetimeExtendedCleanupStackSize; 874 bool OldDidCallStackSave; 875 protected: 876 bool PerformCleanup; 877 private: 878 879 RunCleanupsScope(const RunCleanupsScope &) = delete; 880 void operator=(const RunCleanupsScope &) = delete; 881 882 protected: 883 CodeGenFunction& CGF; 884 885 public: 886 /// Enter a new cleanup scope. 887 explicit RunCleanupsScope(CodeGenFunction &CGF) 888 : PerformCleanup(true), CGF(CGF) 889 { 890 CleanupStackDepth = CGF.EHStack.stable_begin(); 891 LifetimeExtendedCleanupStackSize = 892 CGF.LifetimeExtendedCleanupStack.size(); 893 OldDidCallStackSave = CGF.DidCallStackSave; 894 CGF.DidCallStackSave = false; 895 OldCleanupScopeDepth = CGF.CurrentCleanupScopeDepth; 896 CGF.CurrentCleanupScopeDepth = CleanupStackDepth; 897 } 898 899 /// Exit this cleanup scope, emitting any accumulated cleanups. 900 ~RunCleanupsScope() { 901 if (PerformCleanup) 902 ForceCleanup(); 903 } 904 905 /// Determine whether this scope requires any cleanups. 906 bool requiresCleanups() const { 907 return CGF.EHStack.stable_begin() != CleanupStackDepth; 908 } 909 910 /// Force the emission of cleanups now, instead of waiting 911 /// until this object is destroyed. 912 /// \param ValuesToReload - A list of values that need to be available at 913 /// the insertion point after cleanup emission. If cleanup emission created 914 /// a shared cleanup block, these value pointers will be rewritten. 915 /// Otherwise, they not will be modified. 916 void ForceCleanup(std::initializer_list<llvm::Value**> ValuesToReload = {}) { 917 assert(PerformCleanup && "Already forced cleanup"); 918 CGF.DidCallStackSave = OldDidCallStackSave; 919 CGF.PopCleanupBlocks(CleanupStackDepth, LifetimeExtendedCleanupStackSize, 920 ValuesToReload); 921 PerformCleanup = false; 922 CGF.CurrentCleanupScopeDepth = OldCleanupScopeDepth; 923 } 924 }; 925 926 // Cleanup stack depth of the RunCleanupsScope that was pushed most recently. 927 EHScopeStack::stable_iterator CurrentCleanupScopeDepth = 928 EHScopeStack::stable_end(); 929 930 class LexicalScope : public RunCleanupsScope { 931 SourceRange Range; 932 SmallVector<const LabelDecl*, 4> Labels; 933 LexicalScope *ParentScope; 934 935 LexicalScope(const LexicalScope &) = delete; 936 void operator=(const LexicalScope &) = delete; 937 938 public: 939 /// Enter a new cleanup scope. 940 explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range) 941 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) { 942 CGF.CurLexicalScope = this; 943 if (CGDebugInfo *DI = CGF.getDebugInfo()) 944 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin()); 945 } 946 947 void addLabel(const LabelDecl *label) { 948 assert(PerformCleanup && "adding label to dead scope?"); 949 Labels.push_back(label); 950 } 951 952 /// Exit this cleanup scope, emitting any accumulated 953 /// cleanups. 954 ~LexicalScope() { 955 if (CGDebugInfo *DI = CGF.getDebugInfo()) 956 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd()); 957 958 // If we should perform a cleanup, force them now. Note that 959 // this ends the cleanup scope before rescoping any labels. 960 if (PerformCleanup) { 961 ApplyDebugLocation DL(CGF, Range.getEnd()); 962 ForceCleanup(); 963 } 964 } 965 966 /// Force the emission of cleanups now, instead of waiting 967 /// until this object is destroyed. 968 void ForceCleanup() { 969 CGF.CurLexicalScope = ParentScope; 970 RunCleanupsScope::ForceCleanup(); 971 972 if (!Labels.empty()) 973 rescopeLabels(); 974 } 975 976 bool hasLabels() const { 977 return !Labels.empty(); 978 } 979 980 void rescopeLabels(); 981 }; 982 983 typedef llvm::DenseMap<const Decl *, Address> DeclMapTy; 984 985 /// The class used to assign some variables some temporarily addresses. 986 class OMPMapVars { 987 DeclMapTy SavedLocals; 988 DeclMapTy SavedTempAddresses; 989 OMPMapVars(const OMPMapVars &) = delete; 990 void operator=(const OMPMapVars &) = delete; 991 992 public: 993 explicit OMPMapVars() = default; 994 ~OMPMapVars() { 995 assert(SavedLocals.empty() && "Did not restored original addresses."); 996 }; 997 998 /// Sets the address of the variable \p LocalVD to be \p TempAddr in 999 /// function \p CGF. 1000 /// \return true if at least one variable was set already, false otherwise. 1001 bool setVarAddr(CodeGenFunction &CGF, const VarDecl *LocalVD, 1002 Address TempAddr) { 1003 LocalVD = LocalVD->getCanonicalDecl(); 1004 // Only save it once. 1005 if (SavedLocals.count(LocalVD)) return false; 1006 1007 // Copy the existing local entry to SavedLocals. 1008 auto it = CGF.LocalDeclMap.find(LocalVD); 1009 if (it != CGF.LocalDeclMap.end()) 1010 SavedLocals.try_emplace(LocalVD, it->second); 1011 else 1012 SavedLocals.try_emplace(LocalVD, Address::invalid()); 1013 1014 // Generate the private entry. 1015 QualType VarTy = LocalVD->getType(); 1016 if (VarTy->isReferenceType()) { 1017 Address Temp = CGF.CreateMemTemp(VarTy); 1018 CGF.Builder.CreateStore(TempAddr.getPointer(), Temp); 1019 TempAddr = Temp; 1020 } 1021 SavedTempAddresses.try_emplace(LocalVD, TempAddr); 1022 1023 return true; 1024 } 1025 1026 /// Applies new addresses to the list of the variables. 1027 /// \return true if at least one variable is using new address, false 1028 /// otherwise. 1029 bool apply(CodeGenFunction &CGF) { 1030 copyInto(SavedTempAddresses, CGF.LocalDeclMap); 1031 SavedTempAddresses.clear(); 1032 return !SavedLocals.empty(); 1033 } 1034 1035 /// Restores original addresses of the variables. 1036 void restore(CodeGenFunction &CGF) { 1037 if (!SavedLocals.empty()) { 1038 copyInto(SavedLocals, CGF.LocalDeclMap); 1039 SavedLocals.clear(); 1040 } 1041 } 1042 1043 private: 1044 /// Copy all the entries in the source map over the corresponding 1045 /// entries in the destination, which must exist. 1046 static void copyInto(const DeclMapTy &Src, DeclMapTy &Dest) { 1047 for (auto &Pair : Src) { 1048 if (!Pair.second.isValid()) { 1049 Dest.erase(Pair.first); 1050 continue; 1051 } 1052 1053 auto I = Dest.find(Pair.first); 1054 if (I != Dest.end()) 1055 I->second = Pair.second; 1056 else 1057 Dest.insert(Pair); 1058 } 1059 } 1060 }; 1061 1062 /// The scope used to remap some variables as private in the OpenMP loop body 1063 /// (or other captured region emitted without outlining), and to restore old 1064 /// vars back on exit. 1065 class OMPPrivateScope : public RunCleanupsScope { 1066 OMPMapVars MappedVars; 1067 OMPPrivateScope(const OMPPrivateScope &) = delete; 1068 void operator=(const OMPPrivateScope &) = delete; 1069 1070 public: 1071 /// Enter a new OpenMP private scope. 1072 explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {} 1073 1074 /// Registers \p LocalVD variable as a private and apply \p PrivateGen 1075 /// function for it to generate corresponding private variable. \p 1076 /// PrivateGen returns an address of the generated private variable. 1077 /// \return true if the variable is registered as private, false if it has 1078 /// been privatized already. 1079 bool addPrivate(const VarDecl *LocalVD, 1080 const llvm::function_ref<Address()> PrivateGen) { 1081 assert(PerformCleanup && "adding private to dead scope"); 1082 return MappedVars.setVarAddr(CGF, LocalVD, PrivateGen()); 1083 } 1084 1085 /// Privatizes local variables previously registered as private. 1086 /// Registration is separate from the actual privatization to allow 1087 /// initializers use values of the original variables, not the private one. 1088 /// This is important, for example, if the private variable is a class 1089 /// variable initialized by a constructor that references other private 1090 /// variables. But at initialization original variables must be used, not 1091 /// private copies. 1092 /// \return true if at least one variable was privatized, false otherwise. 1093 bool Privatize() { return MappedVars.apply(CGF); } 1094 1095 void ForceCleanup() { 1096 RunCleanupsScope::ForceCleanup(); 1097 MappedVars.restore(CGF); 1098 } 1099 1100 /// Exit scope - all the mapped variables are restored. 1101 ~OMPPrivateScope() { 1102 if (PerformCleanup) 1103 ForceCleanup(); 1104 } 1105 1106 /// Checks if the global variable is captured in current function. 1107 bool isGlobalVarCaptured(const VarDecl *VD) const { 1108 VD = VD->getCanonicalDecl(); 1109 return !VD->isLocalVarDeclOrParm() && CGF.LocalDeclMap.count(VD) > 0; 1110 } 1111 }; 1112 1113 /// Save/restore original map of previously emitted local vars in case when we 1114 /// need to duplicate emission of the same code several times in the same 1115 /// function for OpenMP code. 1116 class OMPLocalDeclMapRAII { 1117 CodeGenFunction &CGF; 1118 DeclMapTy SavedMap; 1119 1120 public: 1121 OMPLocalDeclMapRAII(CodeGenFunction &CGF) 1122 : CGF(CGF), SavedMap(CGF.LocalDeclMap) {} 1123 ~OMPLocalDeclMapRAII() { SavedMap.swap(CGF.LocalDeclMap); } 1124 }; 1125 1126 /// Takes the old cleanup stack size and emits the cleanup blocks 1127 /// that have been added. 1128 void 1129 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 1130 std::initializer_list<llvm::Value **> ValuesToReload = {}); 1131 1132 /// Takes the old cleanup stack size and emits the cleanup blocks 1133 /// that have been added, then adds all lifetime-extended cleanups from 1134 /// the given position to the stack. 1135 void 1136 PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, 1137 size_t OldLifetimeExtendedStackSize, 1138 std::initializer_list<llvm::Value **> ValuesToReload = {}); 1139 1140 void ResolveBranchFixups(llvm::BasicBlock *Target); 1141 1142 /// The given basic block lies in the current EH scope, but may be a 1143 /// target of a potentially scope-crossing jump; get a stable handle 1144 /// to which we can perform this jump later. 1145 JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) { 1146 return JumpDest(Target, 1147 EHStack.getInnermostNormalCleanup(), 1148 NextCleanupDestIndex++); 1149 } 1150 1151 /// The given basic block lies in the current EH scope, but may be a 1152 /// target of a potentially scope-crossing jump; get a stable handle 1153 /// to which we can perform this jump later. 1154 JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) { 1155 return getJumpDestInCurrentScope(createBasicBlock(Name)); 1156 } 1157 1158 /// EmitBranchThroughCleanup - Emit a branch from the current insert 1159 /// block through the normal cleanup handling code (if any) and then 1160 /// on to \arg Dest. 1161 void EmitBranchThroughCleanup(JumpDest Dest); 1162 1163 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the 1164 /// specified destination obviously has no cleanups to run. 'false' is always 1165 /// a conservatively correct answer for this method. 1166 bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const; 1167 1168 /// popCatchScope - Pops the catch scope at the top of the EHScope 1169 /// stack, emitting any required code (other than the catch handlers 1170 /// themselves). 1171 void popCatchScope(); 1172 1173 llvm::BasicBlock *getEHResumeBlock(bool isCleanup); 1174 llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope); 1175 llvm::BasicBlock * 1176 getFuncletEHDispatchBlock(EHScopeStack::stable_iterator scope); 1177 1178 /// An object to manage conditionally-evaluated expressions. 1179 class ConditionalEvaluation { 1180 llvm::BasicBlock *StartBB; 1181 1182 public: 1183 ConditionalEvaluation(CodeGenFunction &CGF) 1184 : StartBB(CGF.Builder.GetInsertBlock()) {} 1185 1186 void begin(CodeGenFunction &CGF) { 1187 assert(CGF.OutermostConditional != this); 1188 if (!CGF.OutermostConditional) 1189 CGF.OutermostConditional = this; 1190 } 1191 1192 void end(CodeGenFunction &CGF) { 1193 assert(CGF.OutermostConditional != nullptr); 1194 if (CGF.OutermostConditional == this) 1195 CGF.OutermostConditional = nullptr; 1196 } 1197 1198 /// Returns a block which will be executed prior to each 1199 /// evaluation of the conditional code. 1200 llvm::BasicBlock *getStartingBlock() const { 1201 return StartBB; 1202 } 1203 }; 1204 1205 /// isInConditionalBranch - Return true if we're currently emitting 1206 /// one branch or the other of a conditional expression. 1207 bool isInConditionalBranch() const { return OutermostConditional != nullptr; } 1208 1209 void setBeforeOutermostConditional(llvm::Value *value, Address addr) { 1210 assert(isInConditionalBranch()); 1211 llvm::BasicBlock *block = OutermostConditional->getStartingBlock(); 1212 auto store = new llvm::StoreInst(value, addr.getPointer(), &block->back()); 1213 store->setAlignment(addr.getAlignment().getAsAlign()); 1214 } 1215 1216 /// An RAII object to record that we're evaluating a statement 1217 /// expression. 1218 class StmtExprEvaluation { 1219 CodeGenFunction &CGF; 1220 1221 /// We have to save the outermost conditional: cleanups in a 1222 /// statement expression aren't conditional just because the 1223 /// StmtExpr is. 1224 ConditionalEvaluation *SavedOutermostConditional; 1225 1226 public: 1227 StmtExprEvaluation(CodeGenFunction &CGF) 1228 : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) { 1229 CGF.OutermostConditional = nullptr; 1230 } 1231 1232 ~StmtExprEvaluation() { 1233 CGF.OutermostConditional = SavedOutermostConditional; 1234 CGF.EnsureInsertPoint(); 1235 } 1236 }; 1237 1238 /// An object which temporarily prevents a value from being 1239 /// destroyed by aggressive peephole optimizations that assume that 1240 /// all uses of a value have been realized in the IR. 1241 class PeepholeProtection { 1242 llvm::Instruction *Inst; 1243 friend class CodeGenFunction; 1244 1245 public: 1246 PeepholeProtection() : Inst(nullptr) {} 1247 }; 1248 1249 /// A non-RAII class containing all the information about a bound 1250 /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for 1251 /// this which makes individual mappings very simple; using this 1252 /// class directly is useful when you have a variable number of 1253 /// opaque values or don't want the RAII functionality for some 1254 /// reason. 1255 class OpaqueValueMappingData { 1256 const OpaqueValueExpr *OpaqueValue; 1257 bool BoundLValue; 1258 CodeGenFunction::PeepholeProtection Protection; 1259 1260 OpaqueValueMappingData(const OpaqueValueExpr *ov, 1261 bool boundLValue) 1262 : OpaqueValue(ov), BoundLValue(boundLValue) {} 1263 public: 1264 OpaqueValueMappingData() : OpaqueValue(nullptr) {} 1265 1266 static bool shouldBindAsLValue(const Expr *expr) { 1267 // gl-values should be bound as l-values for obvious reasons. 1268 // Records should be bound as l-values because IR generation 1269 // always keeps them in memory. Expressions of function type 1270 // act exactly like l-values but are formally required to be 1271 // r-values in C. 1272 return expr->isGLValue() || 1273 expr->getType()->isFunctionType() || 1274 hasAggregateEvaluationKind(expr->getType()); 1275 } 1276 1277 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1278 const OpaqueValueExpr *ov, 1279 const Expr *e) { 1280 if (shouldBindAsLValue(ov)) 1281 return bind(CGF, ov, CGF.EmitLValue(e)); 1282 return bind(CGF, ov, CGF.EmitAnyExpr(e)); 1283 } 1284 1285 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1286 const OpaqueValueExpr *ov, 1287 const LValue &lv) { 1288 assert(shouldBindAsLValue(ov)); 1289 CGF.OpaqueLValues.insert(std::make_pair(ov, lv)); 1290 return OpaqueValueMappingData(ov, true); 1291 } 1292 1293 static OpaqueValueMappingData bind(CodeGenFunction &CGF, 1294 const OpaqueValueExpr *ov, 1295 const RValue &rv) { 1296 assert(!shouldBindAsLValue(ov)); 1297 CGF.OpaqueRValues.insert(std::make_pair(ov, rv)); 1298 1299 OpaqueValueMappingData data(ov, false); 1300 1301 // Work around an extremely aggressive peephole optimization in 1302 // EmitScalarConversion which assumes that all other uses of a 1303 // value are extant. 1304 data.Protection = CGF.protectFromPeepholes(rv); 1305 1306 return data; 1307 } 1308 1309 bool isValid() const { return OpaqueValue != nullptr; } 1310 void clear() { OpaqueValue = nullptr; } 1311 1312 void unbind(CodeGenFunction &CGF) { 1313 assert(OpaqueValue && "no data to unbind!"); 1314 1315 if (BoundLValue) { 1316 CGF.OpaqueLValues.erase(OpaqueValue); 1317 } else { 1318 CGF.OpaqueRValues.erase(OpaqueValue); 1319 CGF.unprotectFromPeepholes(Protection); 1320 } 1321 } 1322 }; 1323 1324 /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr. 1325 class OpaqueValueMapping { 1326 CodeGenFunction &CGF; 1327 OpaqueValueMappingData Data; 1328 1329 public: 1330 static bool shouldBindAsLValue(const Expr *expr) { 1331 return OpaqueValueMappingData::shouldBindAsLValue(expr); 1332 } 1333 1334 /// Build the opaque value mapping for the given conditional 1335 /// operator if it's the GNU ?: extension. This is a common 1336 /// enough pattern that the convenience operator is really 1337 /// helpful. 1338 /// 1339 OpaqueValueMapping(CodeGenFunction &CGF, 1340 const AbstractConditionalOperator *op) : CGF(CGF) { 1341 if (isa<ConditionalOperator>(op)) 1342 // Leave Data empty. 1343 return; 1344 1345 const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op); 1346 Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(), 1347 e->getCommon()); 1348 } 1349 1350 /// Build the opaque value mapping for an OpaqueValueExpr whose source 1351 /// expression is set to the expression the OVE represents. 1352 OpaqueValueMapping(CodeGenFunction &CGF, const OpaqueValueExpr *OV) 1353 : CGF(CGF) { 1354 if (OV) { 1355 assert(OV->getSourceExpr() && "wrong form of OpaqueValueMapping used " 1356 "for OVE with no source expression"); 1357 Data = OpaqueValueMappingData::bind(CGF, OV, OV->getSourceExpr()); 1358 } 1359 } 1360 1361 OpaqueValueMapping(CodeGenFunction &CGF, 1362 const OpaqueValueExpr *opaqueValue, 1363 LValue lvalue) 1364 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) { 1365 } 1366 1367 OpaqueValueMapping(CodeGenFunction &CGF, 1368 const OpaqueValueExpr *opaqueValue, 1369 RValue rvalue) 1370 : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) { 1371 } 1372 1373 void pop() { 1374 Data.unbind(CGF); 1375 Data.clear(); 1376 } 1377 1378 ~OpaqueValueMapping() { 1379 if (Data.isValid()) Data.unbind(CGF); 1380 } 1381 }; 1382 1383 private: 1384 CGDebugInfo *DebugInfo; 1385 /// Used to create unique names for artificial VLA size debug info variables. 1386 unsigned VLAExprCounter = 0; 1387 bool DisableDebugInfo = false; 1388 1389 /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid 1390 /// calling llvm.stacksave for multiple VLAs in the same scope. 1391 bool DidCallStackSave = false; 1392 1393 /// IndirectBranch - The first time an indirect goto is seen we create a block 1394 /// with an indirect branch. Every time we see the address of a label taken, 1395 /// we add the label to the indirect goto. Every subsequent indirect goto is 1396 /// codegen'd as a jump to the IndirectBranch's basic block. 1397 llvm::IndirectBrInst *IndirectBranch = nullptr; 1398 1399 /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C 1400 /// decls. 1401 DeclMapTy LocalDeclMap; 1402 1403 // Keep track of the cleanups for callee-destructed parameters pushed to the 1404 // cleanup stack so that they can be deactivated later. 1405 llvm::DenseMap<const ParmVarDecl *, EHScopeStack::stable_iterator> 1406 CalleeDestructedParamCleanups; 1407 1408 /// SizeArguments - If a ParmVarDecl had the pass_object_size attribute, this 1409 /// will contain a mapping from said ParmVarDecl to its implicit "object_size" 1410 /// parameter. 1411 llvm::SmallDenseMap<const ParmVarDecl *, const ImplicitParamDecl *, 2> 1412 SizeArguments; 1413 1414 /// Track escaped local variables with auto storage. Used during SEH 1415 /// outlining to produce a call to llvm.localescape. 1416 llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals; 1417 1418 /// LabelMap - This keeps track of the LLVM basic block for each C label. 1419 llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap; 1420 1421 // BreakContinueStack - This keeps track of where break and continue 1422 // statements should jump to. 1423 struct BreakContinue { 1424 BreakContinue(JumpDest Break, JumpDest Continue) 1425 : BreakBlock(Break), ContinueBlock(Continue) {} 1426 1427 JumpDest BreakBlock; 1428 JumpDest ContinueBlock; 1429 }; 1430 SmallVector<BreakContinue, 8> BreakContinueStack; 1431 1432 /// Handles cancellation exit points in OpenMP-related constructs. 1433 class OpenMPCancelExitStack { 1434 /// Tracks cancellation exit point and join point for cancel-related exit 1435 /// and normal exit. 1436 struct CancelExit { 1437 CancelExit() = default; 1438 CancelExit(OpenMPDirectiveKind Kind, JumpDest ExitBlock, 1439 JumpDest ContBlock) 1440 : Kind(Kind), ExitBlock(ExitBlock), ContBlock(ContBlock) {} 1441 OpenMPDirectiveKind Kind = llvm::omp::OMPD_unknown; 1442 /// true if the exit block has been emitted already by the special 1443 /// emitExit() call, false if the default codegen is used. 1444 bool HasBeenEmitted = false; 1445 JumpDest ExitBlock; 1446 JumpDest ContBlock; 1447 }; 1448 1449 SmallVector<CancelExit, 8> Stack; 1450 1451 public: 1452 OpenMPCancelExitStack() : Stack(1) {} 1453 ~OpenMPCancelExitStack() = default; 1454 /// Fetches the exit block for the current OpenMP construct. 1455 JumpDest getExitBlock() const { return Stack.back().ExitBlock; } 1456 /// Emits exit block with special codegen procedure specific for the related 1457 /// OpenMP construct + emits code for normal construct cleanup. 1458 void emitExit(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 1459 const llvm::function_ref<void(CodeGenFunction &)> CodeGen) { 1460 if (Stack.back().Kind == Kind && getExitBlock().isValid()) { 1461 assert(CGF.getOMPCancelDestination(Kind).isValid()); 1462 assert(CGF.HaveInsertPoint()); 1463 assert(!Stack.back().HasBeenEmitted); 1464 auto IP = CGF.Builder.saveAndClearIP(); 1465 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1466 CodeGen(CGF); 1467 CGF.EmitBranch(Stack.back().ContBlock.getBlock()); 1468 CGF.Builder.restoreIP(IP); 1469 Stack.back().HasBeenEmitted = true; 1470 } 1471 CodeGen(CGF); 1472 } 1473 /// Enter the cancel supporting \a Kind construct. 1474 /// \param Kind OpenMP directive that supports cancel constructs. 1475 /// \param HasCancel true, if the construct has inner cancel directive, 1476 /// false otherwise. 1477 void enter(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, bool HasCancel) { 1478 Stack.push_back({Kind, 1479 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.exit") 1480 : JumpDest(), 1481 HasCancel ? CGF.getJumpDestInCurrentScope("cancel.cont") 1482 : JumpDest()}); 1483 } 1484 /// Emits default exit point for the cancel construct (if the special one 1485 /// has not be used) + join point for cancel/normal exits. 1486 void exit(CodeGenFunction &CGF) { 1487 if (getExitBlock().isValid()) { 1488 assert(CGF.getOMPCancelDestination(Stack.back().Kind).isValid()); 1489 bool HaveIP = CGF.HaveInsertPoint(); 1490 if (!Stack.back().HasBeenEmitted) { 1491 if (HaveIP) 1492 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1493 CGF.EmitBlock(Stack.back().ExitBlock.getBlock()); 1494 CGF.EmitBranchThroughCleanup(Stack.back().ContBlock); 1495 } 1496 CGF.EmitBlock(Stack.back().ContBlock.getBlock()); 1497 if (!HaveIP) { 1498 CGF.Builder.CreateUnreachable(); 1499 CGF.Builder.ClearInsertionPoint(); 1500 } 1501 } 1502 Stack.pop_back(); 1503 } 1504 }; 1505 OpenMPCancelExitStack OMPCancelStack; 1506 1507 /// Lower the Likelihood knowledge about the \p Cond via llvm.expect intrin. 1508 llvm::Value *emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond, 1509 Stmt::Likelihood LH); 1510 1511 CodeGenPGO PGO; 1512 1513 /// Calculate branch weights appropriate for PGO data 1514 llvm::MDNode *createProfileWeights(uint64_t TrueCount, 1515 uint64_t FalseCount) const; 1516 llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights) const; 1517 llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond, 1518 uint64_t LoopCount) const; 1519 1520 public: 1521 /// Increment the profiler's counter for the given statement by \p StepV. 1522 /// If \p StepV is null, the default increment is 1. 1523 void incrementProfileCounter(const Stmt *S, llvm::Value *StepV = nullptr) { 1524 if (CGM.getCodeGenOpts().hasProfileClangInstr() && 1525 !CurFn->hasFnAttribute(llvm::Attribute::NoProfile)) 1526 PGO.emitCounterIncrement(Builder, S, StepV); 1527 PGO.setCurrentStmt(S); 1528 } 1529 1530 /// Get the profiler's count for the given statement. 1531 uint64_t getProfileCount(const Stmt *S) { 1532 Optional<uint64_t> Count = PGO.getStmtCount(S); 1533 if (!Count.hasValue()) 1534 return 0; 1535 return *Count; 1536 } 1537 1538 /// Set the profiler's current count. 1539 void setCurrentProfileCount(uint64_t Count) { 1540 PGO.setCurrentRegionCount(Count); 1541 } 1542 1543 /// Get the profiler's current count. This is generally the count for the most 1544 /// recently incremented counter. 1545 uint64_t getCurrentProfileCount() { 1546 return PGO.getCurrentRegionCount(); 1547 } 1548 1549 private: 1550 1551 /// SwitchInsn - This is nearest current switch instruction. It is null if 1552 /// current context is not in a switch. 1553 llvm::SwitchInst *SwitchInsn = nullptr; 1554 /// The branch weights of SwitchInsn when doing instrumentation based PGO. 1555 SmallVector<uint64_t, 16> *SwitchWeights = nullptr; 1556 1557 /// The likelihood attributes of the SwitchCase. 1558 SmallVector<Stmt::Likelihood, 16> *SwitchLikelihood = nullptr; 1559 1560 /// CaseRangeBlock - This block holds if condition check for last case 1561 /// statement range in current switch instruction. 1562 llvm::BasicBlock *CaseRangeBlock = nullptr; 1563 1564 /// OpaqueLValues - Keeps track of the current set of opaque value 1565 /// expressions. 1566 llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues; 1567 llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues; 1568 1569 // VLASizeMap - This keeps track of the associated size for each VLA type. 1570 // We track this by the size expression rather than the type itself because 1571 // in certain situations, like a const qualifier applied to an VLA typedef, 1572 // multiple VLA types can share the same size expression. 1573 // FIXME: Maybe this could be a stack of maps that is pushed/popped as we 1574 // enter/leave scopes. 1575 llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap; 1576 1577 /// A block containing a single 'unreachable' instruction. Created 1578 /// lazily by getUnreachableBlock(). 1579 llvm::BasicBlock *UnreachableBlock = nullptr; 1580 1581 /// Counts of the number return expressions in the function. 1582 unsigned NumReturnExprs = 0; 1583 1584 /// Count the number of simple (constant) return expressions in the function. 1585 unsigned NumSimpleReturnExprs = 0; 1586 1587 /// The last regular (non-return) debug location (breakpoint) in the function. 1588 SourceLocation LastStopPoint; 1589 1590 public: 1591 /// Source location information about the default argument or member 1592 /// initializer expression we're evaluating, if any. 1593 CurrentSourceLocExprScope CurSourceLocExprScope; 1594 using SourceLocExprScopeGuard = 1595 CurrentSourceLocExprScope::SourceLocExprScopeGuard; 1596 1597 /// A scope within which we are constructing the fields of an object which 1598 /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use 1599 /// if we need to evaluate a CXXDefaultInitExpr within the evaluation. 1600 class FieldConstructionScope { 1601 public: 1602 FieldConstructionScope(CodeGenFunction &CGF, Address This) 1603 : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) { 1604 CGF.CXXDefaultInitExprThis = This; 1605 } 1606 ~FieldConstructionScope() { 1607 CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis; 1608 } 1609 1610 private: 1611 CodeGenFunction &CGF; 1612 Address OldCXXDefaultInitExprThis; 1613 }; 1614 1615 /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this' 1616 /// is overridden to be the object under construction. 1617 class CXXDefaultInitExprScope { 1618 public: 1619 CXXDefaultInitExprScope(CodeGenFunction &CGF, const CXXDefaultInitExpr *E) 1620 : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue), 1621 OldCXXThisAlignment(CGF.CXXThisAlignment), 1622 SourceLocScope(E, CGF.CurSourceLocExprScope) { 1623 CGF.CXXThisValue = CGF.CXXDefaultInitExprThis.getPointer(); 1624 CGF.CXXThisAlignment = CGF.CXXDefaultInitExprThis.getAlignment(); 1625 } 1626 ~CXXDefaultInitExprScope() { 1627 CGF.CXXThisValue = OldCXXThisValue; 1628 CGF.CXXThisAlignment = OldCXXThisAlignment; 1629 } 1630 1631 public: 1632 CodeGenFunction &CGF; 1633 llvm::Value *OldCXXThisValue; 1634 CharUnits OldCXXThisAlignment; 1635 SourceLocExprScopeGuard SourceLocScope; 1636 }; 1637 1638 struct CXXDefaultArgExprScope : SourceLocExprScopeGuard { 1639 CXXDefaultArgExprScope(CodeGenFunction &CGF, const CXXDefaultArgExpr *E) 1640 : SourceLocExprScopeGuard(E, CGF.CurSourceLocExprScope) {} 1641 }; 1642 1643 /// The scope of an ArrayInitLoopExpr. Within this scope, the value of the 1644 /// current loop index is overridden. 1645 class ArrayInitLoopExprScope { 1646 public: 1647 ArrayInitLoopExprScope(CodeGenFunction &CGF, llvm::Value *Index) 1648 : CGF(CGF), OldArrayInitIndex(CGF.ArrayInitIndex) { 1649 CGF.ArrayInitIndex = Index; 1650 } 1651 ~ArrayInitLoopExprScope() { 1652 CGF.ArrayInitIndex = OldArrayInitIndex; 1653 } 1654 1655 private: 1656 CodeGenFunction &CGF; 1657 llvm::Value *OldArrayInitIndex; 1658 }; 1659 1660 class InlinedInheritingConstructorScope { 1661 public: 1662 InlinedInheritingConstructorScope(CodeGenFunction &CGF, GlobalDecl GD) 1663 : CGF(CGF), OldCurGD(CGF.CurGD), OldCurFuncDecl(CGF.CurFuncDecl), 1664 OldCurCodeDecl(CGF.CurCodeDecl), 1665 OldCXXABIThisDecl(CGF.CXXABIThisDecl), 1666 OldCXXABIThisValue(CGF.CXXABIThisValue), 1667 OldCXXThisValue(CGF.CXXThisValue), 1668 OldCXXABIThisAlignment(CGF.CXXABIThisAlignment), 1669 OldCXXThisAlignment(CGF.CXXThisAlignment), 1670 OldReturnValue(CGF.ReturnValue), OldFnRetTy(CGF.FnRetTy), 1671 OldCXXInheritedCtorInitExprArgs( 1672 std::move(CGF.CXXInheritedCtorInitExprArgs)) { 1673 CGF.CurGD = GD; 1674 CGF.CurFuncDecl = CGF.CurCodeDecl = 1675 cast<CXXConstructorDecl>(GD.getDecl()); 1676 CGF.CXXABIThisDecl = nullptr; 1677 CGF.CXXABIThisValue = nullptr; 1678 CGF.CXXThisValue = nullptr; 1679 CGF.CXXABIThisAlignment = CharUnits(); 1680 CGF.CXXThisAlignment = CharUnits(); 1681 CGF.ReturnValue = Address::invalid(); 1682 CGF.FnRetTy = QualType(); 1683 CGF.CXXInheritedCtorInitExprArgs.clear(); 1684 } 1685 ~InlinedInheritingConstructorScope() { 1686 CGF.CurGD = OldCurGD; 1687 CGF.CurFuncDecl = OldCurFuncDecl; 1688 CGF.CurCodeDecl = OldCurCodeDecl; 1689 CGF.CXXABIThisDecl = OldCXXABIThisDecl; 1690 CGF.CXXABIThisValue = OldCXXABIThisValue; 1691 CGF.CXXThisValue = OldCXXThisValue; 1692 CGF.CXXABIThisAlignment = OldCXXABIThisAlignment; 1693 CGF.CXXThisAlignment = OldCXXThisAlignment; 1694 CGF.ReturnValue = OldReturnValue; 1695 CGF.FnRetTy = OldFnRetTy; 1696 CGF.CXXInheritedCtorInitExprArgs = 1697 std::move(OldCXXInheritedCtorInitExprArgs); 1698 } 1699 1700 private: 1701 CodeGenFunction &CGF; 1702 GlobalDecl OldCurGD; 1703 const Decl *OldCurFuncDecl; 1704 const Decl *OldCurCodeDecl; 1705 ImplicitParamDecl *OldCXXABIThisDecl; 1706 llvm::Value *OldCXXABIThisValue; 1707 llvm::Value *OldCXXThisValue; 1708 CharUnits OldCXXABIThisAlignment; 1709 CharUnits OldCXXThisAlignment; 1710 Address OldReturnValue; 1711 QualType OldFnRetTy; 1712 CallArgList OldCXXInheritedCtorInitExprArgs; 1713 }; 1714 1715 // Helper class for the OpenMP IR Builder. Allows reusability of code used for 1716 // region body, and finalization codegen callbacks. This will class will also 1717 // contain privatization functions used by the privatization call backs 1718 // 1719 // TODO: this is temporary class for things that are being moved out of 1720 // CGOpenMPRuntime, new versions of current CodeGenFunction methods, or 1721 // utility function for use with the OMPBuilder. Once that move to use the 1722 // OMPBuilder is done, everything here will either become part of CodeGenFunc. 1723 // directly, or a new helper class that will contain functions used by both 1724 // this and the OMPBuilder 1725 1726 struct OMPBuilderCBHelpers { 1727 1728 OMPBuilderCBHelpers() = delete; 1729 OMPBuilderCBHelpers(const OMPBuilderCBHelpers &) = delete; 1730 OMPBuilderCBHelpers &operator=(const OMPBuilderCBHelpers &) = delete; 1731 1732 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 1733 1734 /// Cleanup action for allocate support. 1735 class OMPAllocateCleanupTy final : public EHScopeStack::Cleanup { 1736 1737 private: 1738 llvm::CallInst *RTLFnCI; 1739 1740 public: 1741 OMPAllocateCleanupTy(llvm::CallInst *RLFnCI) : RTLFnCI(RLFnCI) { 1742 RLFnCI->removeFromParent(); 1743 } 1744 1745 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { 1746 if (!CGF.HaveInsertPoint()) 1747 return; 1748 CGF.Builder.Insert(RTLFnCI); 1749 } 1750 }; 1751 1752 /// Returns address of the threadprivate variable for the current 1753 /// thread. This Also create any necessary OMP runtime calls. 1754 /// 1755 /// \param VD VarDecl for Threadprivate variable. 1756 /// \param VDAddr Address of the Vardecl 1757 /// \param Loc The location where the barrier directive was encountered 1758 static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, 1759 const VarDecl *VD, Address VDAddr, 1760 SourceLocation Loc); 1761 1762 /// Gets the OpenMP-specific address of the local variable /p VD. 1763 static Address getAddressOfLocalVariable(CodeGenFunction &CGF, 1764 const VarDecl *VD); 1765 /// Get the platform-specific name separator. 1766 /// \param Parts different parts of the final name that needs separation 1767 /// \param FirstSeparator First separator used between the initial two 1768 /// parts of the name. 1769 /// \param Separator separator used between all of the rest consecutinve 1770 /// parts of the name 1771 static std::string getNameWithSeparators(ArrayRef<StringRef> Parts, 1772 StringRef FirstSeparator = ".", 1773 StringRef Separator = "."); 1774 /// Emit the Finalization for an OMP region 1775 /// \param CGF The Codegen function this belongs to 1776 /// \param IP Insertion point for generating the finalization code. 1777 static void FinalizeOMPRegion(CodeGenFunction &CGF, InsertPointTy IP) { 1778 CGBuilderTy::InsertPointGuard IPG(CGF.Builder); 1779 assert(IP.getBlock()->end() != IP.getPoint() && 1780 "OpenMP IR Builder should cause terminated block!"); 1781 1782 llvm::BasicBlock *IPBB = IP.getBlock(); 1783 llvm::BasicBlock *DestBB = IPBB->getUniqueSuccessor(); 1784 assert(DestBB && "Finalization block should have one successor!"); 1785 1786 // erase and replace with cleanup branch. 1787 IPBB->getTerminator()->eraseFromParent(); 1788 CGF.Builder.SetInsertPoint(IPBB); 1789 CodeGenFunction::JumpDest Dest = CGF.getJumpDestInCurrentScope(DestBB); 1790 CGF.EmitBranchThroughCleanup(Dest); 1791 } 1792 1793 /// Emit the body of an OMP region 1794 /// \param CGF The Codegen function this belongs to 1795 /// \param RegionBodyStmt The body statement for the OpenMP region being 1796 /// generated 1797 /// \param CodeGenIP Insertion point for generating the body code. 1798 /// \param FiniBB The finalization basic block 1799 static void EmitOMPRegionBody(CodeGenFunction &CGF, 1800 const Stmt *RegionBodyStmt, 1801 InsertPointTy CodeGenIP, 1802 llvm::BasicBlock &FiniBB) { 1803 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock(); 1804 if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator()) 1805 CodeGenIPBBTI->eraseFromParent(); 1806 1807 CGF.Builder.SetInsertPoint(CodeGenIPBB); 1808 1809 CGF.EmitStmt(RegionBodyStmt); 1810 1811 if (CGF.Builder.saveIP().isSet()) 1812 CGF.Builder.CreateBr(&FiniBB); 1813 } 1814 1815 static void EmitCaptureStmt(CodeGenFunction &CGF, InsertPointTy CodeGenIP, 1816 llvm::BasicBlock &FiniBB, llvm::Function *Fn, 1817 ArrayRef<llvm::Value *> Args) { 1818 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock(); 1819 if (llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator()) 1820 CodeGenIPBBTI->eraseFromParent(); 1821 1822 CGF.Builder.SetInsertPoint(CodeGenIPBB); 1823 1824 if (Fn->doesNotThrow()) 1825 CGF.EmitNounwindRuntimeCall(Fn, Args); 1826 else 1827 CGF.EmitRuntimeCall(Fn, Args); 1828 1829 if (CGF.Builder.saveIP().isSet()) 1830 CGF.Builder.CreateBr(&FiniBB); 1831 } 1832 1833 /// RAII for preserving necessary info during Outlined region body codegen. 1834 class OutlinedRegionBodyRAII { 1835 1836 llvm::AssertingVH<llvm::Instruction> OldAllocaIP; 1837 CodeGenFunction::JumpDest OldReturnBlock; 1838 CGBuilderTy::InsertPoint IP; 1839 CodeGenFunction &CGF; 1840 1841 public: 1842 OutlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP, 1843 llvm::BasicBlock &RetBB) 1844 : CGF(cgf) { 1845 assert(AllocaIP.isSet() && 1846 "Must specify Insertion point for allocas of outlined function"); 1847 OldAllocaIP = CGF.AllocaInsertPt; 1848 CGF.AllocaInsertPt = &*AllocaIP.getPoint(); 1849 IP = CGF.Builder.saveIP(); 1850 1851 OldReturnBlock = CGF.ReturnBlock; 1852 CGF.ReturnBlock = CGF.getJumpDestInCurrentScope(&RetBB); 1853 } 1854 1855 ~OutlinedRegionBodyRAII() { 1856 CGF.AllocaInsertPt = OldAllocaIP; 1857 CGF.ReturnBlock = OldReturnBlock; 1858 CGF.Builder.restoreIP(IP); 1859 } 1860 }; 1861 1862 /// RAII for preserving necessary info during inlined region body codegen. 1863 class InlinedRegionBodyRAII { 1864 1865 llvm::AssertingVH<llvm::Instruction> OldAllocaIP; 1866 CodeGenFunction &CGF; 1867 1868 public: 1869 InlinedRegionBodyRAII(CodeGenFunction &cgf, InsertPointTy &AllocaIP, 1870 llvm::BasicBlock &FiniBB) 1871 : CGF(cgf) { 1872 // Alloca insertion block should be in the entry block of the containing 1873 // function so it expects an empty AllocaIP in which case will reuse the 1874 // old alloca insertion point, or a new AllocaIP in the same block as 1875 // the old one 1876 assert((!AllocaIP.isSet() || 1877 CGF.AllocaInsertPt->getParent() == AllocaIP.getBlock()) && 1878 "Insertion point should be in the entry block of containing " 1879 "function!"); 1880 OldAllocaIP = CGF.AllocaInsertPt; 1881 if (AllocaIP.isSet()) 1882 CGF.AllocaInsertPt = &*AllocaIP.getPoint(); 1883 1884 // TODO: Remove the call, after making sure the counter is not used by 1885 // the EHStack. 1886 // Since this is an inlined region, it should not modify the 1887 // ReturnBlock, and should reuse the one for the enclosing outlined 1888 // region. So, the JumpDest being return by the function is discarded 1889 (void)CGF.getJumpDestInCurrentScope(&FiniBB); 1890 } 1891 1892 ~InlinedRegionBodyRAII() { CGF.AllocaInsertPt = OldAllocaIP; } 1893 }; 1894 }; 1895 1896 private: 1897 /// CXXThisDecl - When generating code for a C++ member function, 1898 /// this will hold the implicit 'this' declaration. 1899 ImplicitParamDecl *CXXABIThisDecl = nullptr; 1900 llvm::Value *CXXABIThisValue = nullptr; 1901 llvm::Value *CXXThisValue = nullptr; 1902 CharUnits CXXABIThisAlignment; 1903 CharUnits CXXThisAlignment; 1904 1905 /// The value of 'this' to use when evaluating CXXDefaultInitExprs within 1906 /// this expression. 1907 Address CXXDefaultInitExprThis = Address::invalid(); 1908 1909 /// The current array initialization index when evaluating an 1910 /// ArrayInitIndexExpr within an ArrayInitLoopExpr. 1911 llvm::Value *ArrayInitIndex = nullptr; 1912 1913 /// The values of function arguments to use when evaluating 1914 /// CXXInheritedCtorInitExprs within this context. 1915 CallArgList CXXInheritedCtorInitExprArgs; 1916 1917 /// CXXStructorImplicitParamDecl - When generating code for a constructor or 1918 /// destructor, this will hold the implicit argument (e.g. VTT). 1919 ImplicitParamDecl *CXXStructorImplicitParamDecl = nullptr; 1920 llvm::Value *CXXStructorImplicitParamValue = nullptr; 1921 1922 /// OutermostConditional - Points to the outermost active 1923 /// conditional control. This is used so that we know if a 1924 /// temporary should be destroyed conditionally. 1925 ConditionalEvaluation *OutermostConditional = nullptr; 1926 1927 /// The current lexical scope. 1928 LexicalScope *CurLexicalScope = nullptr; 1929 1930 /// The current source location that should be used for exception 1931 /// handling code. 1932 SourceLocation CurEHLocation; 1933 1934 /// BlockByrefInfos - For each __block variable, contains 1935 /// information about the layout of the variable. 1936 llvm::DenseMap<const ValueDecl *, BlockByrefInfo> BlockByrefInfos; 1937 1938 /// Used by -fsanitize=nullability-return to determine whether the return 1939 /// value can be checked. 1940 llvm::Value *RetValNullabilityPrecondition = nullptr; 1941 1942 /// Check if -fsanitize=nullability-return instrumentation is required for 1943 /// this function. 1944 bool requiresReturnValueNullabilityCheck() const { 1945 return RetValNullabilityPrecondition; 1946 } 1947 1948 /// Used to store precise source locations for return statements by the 1949 /// runtime return value checks. 1950 Address ReturnLocation = Address::invalid(); 1951 1952 /// Check if the return value of this function requires sanitization. 1953 bool requiresReturnValueCheck() const; 1954 1955 llvm::BasicBlock *TerminateLandingPad = nullptr; 1956 llvm::BasicBlock *TerminateHandler = nullptr; 1957 llvm::SmallVector<llvm::BasicBlock *, 2> TrapBBs; 1958 1959 /// Terminate funclets keyed by parent funclet pad. 1960 llvm::MapVector<llvm::Value *, llvm::BasicBlock *> TerminateFunclets; 1961 1962 /// Largest vector width used in ths function. Will be used to create a 1963 /// function attribute. 1964 unsigned LargestVectorWidth = 0; 1965 1966 /// True if we need emit the life-time markers. This is initially set in 1967 /// the constructor, but could be overwritten to true if this is a coroutine. 1968 bool ShouldEmitLifetimeMarkers; 1969 1970 /// Add OpenCL kernel arg metadata and the kernel attribute metadata to 1971 /// the function metadata. 1972 void EmitOpenCLKernelMetadata(const FunctionDecl *FD, 1973 llvm::Function *Fn); 1974 1975 public: 1976 CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false); 1977 ~CodeGenFunction(); 1978 1979 CodeGenTypes &getTypes() const { return CGM.getTypes(); } 1980 ASTContext &getContext() const { return CGM.getContext(); } 1981 CGDebugInfo *getDebugInfo() { 1982 if (DisableDebugInfo) 1983 return nullptr; 1984 return DebugInfo; 1985 } 1986 void disableDebugInfo() { DisableDebugInfo = true; } 1987 void enableDebugInfo() { DisableDebugInfo = false; } 1988 1989 bool shouldUseFusedARCCalls() { 1990 return CGM.getCodeGenOpts().OptimizationLevel == 0; 1991 } 1992 1993 const LangOptions &getLangOpts() const { return CGM.getLangOpts(); } 1994 1995 /// Returns a pointer to the function's exception object and selector slot, 1996 /// which is assigned in every landing pad. 1997 Address getExceptionSlot(); 1998 Address getEHSelectorSlot(); 1999 2000 /// Returns the contents of the function's exception object and selector 2001 /// slots. 2002 llvm::Value *getExceptionFromSlot(); 2003 llvm::Value *getSelectorFromSlot(); 2004 2005 Address getNormalCleanupDestSlot(); 2006 2007 llvm::BasicBlock *getUnreachableBlock() { 2008 if (!UnreachableBlock) { 2009 UnreachableBlock = createBasicBlock("unreachable"); 2010 new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock); 2011 } 2012 return UnreachableBlock; 2013 } 2014 2015 llvm::BasicBlock *getInvokeDest() { 2016 if (!EHStack.requiresLandingPad()) return nullptr; 2017 return getInvokeDestImpl(); 2018 } 2019 2020 bool currentFunctionUsesSEHTry() const { return CurSEHParent != nullptr; } 2021 2022 const TargetInfo &getTarget() const { return Target; } 2023 llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); } 2024 const TargetCodeGenInfo &getTargetHooks() const { 2025 return CGM.getTargetCodeGenInfo(); 2026 } 2027 2028 //===--------------------------------------------------------------------===// 2029 // Cleanups 2030 //===--------------------------------------------------------------------===// 2031 2032 typedef void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty); 2033 2034 void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 2035 Address arrayEndPointer, 2036 QualType elementType, 2037 CharUnits elementAlignment, 2038 Destroyer *destroyer); 2039 void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 2040 llvm::Value *arrayEnd, 2041 QualType elementType, 2042 CharUnits elementAlignment, 2043 Destroyer *destroyer); 2044 2045 void pushDestroy(QualType::DestructionKind dtorKind, 2046 Address addr, QualType type); 2047 void pushEHDestroy(QualType::DestructionKind dtorKind, 2048 Address addr, QualType type); 2049 void pushDestroy(CleanupKind kind, Address addr, QualType type, 2050 Destroyer *destroyer, bool useEHCleanupForArray); 2051 void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, 2052 QualType type, Destroyer *destroyer, 2053 bool useEHCleanupForArray); 2054 void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 2055 llvm::Value *CompletePtr, 2056 QualType ElementType); 2057 void pushStackRestore(CleanupKind kind, Address SPMem); 2058 void emitDestroy(Address addr, QualType type, Destroyer *destroyer, 2059 bool useEHCleanupForArray); 2060 llvm::Function *generateDestroyHelper(Address addr, QualType type, 2061 Destroyer *destroyer, 2062 bool useEHCleanupForArray, 2063 const VarDecl *VD); 2064 void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, 2065 QualType elementType, CharUnits elementAlign, 2066 Destroyer *destroyer, 2067 bool checkZeroLength, bool useEHCleanup); 2068 2069 Destroyer *getDestroyer(QualType::DestructionKind destructionKind); 2070 2071 /// Determines whether an EH cleanup is required to destroy a type 2072 /// with the given destruction kind. 2073 bool needsEHCleanup(QualType::DestructionKind kind) { 2074 switch (kind) { 2075 case QualType::DK_none: 2076 return false; 2077 case QualType::DK_cxx_destructor: 2078 case QualType::DK_objc_weak_lifetime: 2079 case QualType::DK_nontrivial_c_struct: 2080 return getLangOpts().Exceptions; 2081 case QualType::DK_objc_strong_lifetime: 2082 return getLangOpts().Exceptions && 2083 CGM.getCodeGenOpts().ObjCAutoRefCountExceptions; 2084 } 2085 llvm_unreachable("bad destruction kind"); 2086 } 2087 2088 CleanupKind getCleanupKind(QualType::DestructionKind kind) { 2089 return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup); 2090 } 2091 2092 //===--------------------------------------------------------------------===// 2093 // Objective-C 2094 //===--------------------------------------------------------------------===// 2095 2096 void GenerateObjCMethod(const ObjCMethodDecl *OMD); 2097 2098 void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD); 2099 2100 /// GenerateObjCGetter - Synthesize an Objective-C property getter function. 2101 void GenerateObjCGetter(ObjCImplementationDecl *IMP, 2102 const ObjCPropertyImplDecl *PID); 2103 void generateObjCGetterBody(const ObjCImplementationDecl *classImpl, 2104 const ObjCPropertyImplDecl *propImpl, 2105 const ObjCMethodDecl *GetterMothodDecl, 2106 llvm::Constant *AtomicHelperFn); 2107 2108 void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP, 2109 ObjCMethodDecl *MD, bool ctor); 2110 2111 /// GenerateObjCSetter - Synthesize an Objective-C property setter function 2112 /// for the given property. 2113 void GenerateObjCSetter(ObjCImplementationDecl *IMP, 2114 const ObjCPropertyImplDecl *PID); 2115 void generateObjCSetterBody(const ObjCImplementationDecl *classImpl, 2116 const ObjCPropertyImplDecl *propImpl, 2117 llvm::Constant *AtomicHelperFn); 2118 2119 //===--------------------------------------------------------------------===// 2120 // Block Bits 2121 //===--------------------------------------------------------------------===// 2122 2123 /// Emit block literal. 2124 /// \return an LLVM value which is a pointer to a struct which contains 2125 /// information about the block, including the block invoke function, the 2126 /// captured variables, etc. 2127 llvm::Value *EmitBlockLiteral(const BlockExpr *); 2128 2129 llvm::Function *GenerateBlockFunction(GlobalDecl GD, 2130 const CGBlockInfo &Info, 2131 const DeclMapTy &ldm, 2132 bool IsLambdaConversionToBlock, 2133 bool BuildGlobalBlock); 2134 2135 /// Check if \p T is a C++ class that has a destructor that can throw. 2136 static bool cxxDestructorCanThrow(QualType T); 2137 2138 llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo); 2139 llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo); 2140 llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction( 2141 const ObjCPropertyImplDecl *PID); 2142 llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction( 2143 const ObjCPropertyImplDecl *PID); 2144 llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty); 2145 2146 void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags, 2147 bool CanThrow); 2148 2149 class AutoVarEmission; 2150 2151 void emitByrefStructureInit(const AutoVarEmission &emission); 2152 2153 /// Enter a cleanup to destroy a __block variable. Note that this 2154 /// cleanup should be a no-op if the variable hasn't left the stack 2155 /// yet; if a cleanup is required for the variable itself, that needs 2156 /// to be done externally. 2157 /// 2158 /// \param Kind Cleanup kind. 2159 /// 2160 /// \param Addr When \p LoadBlockVarAddr is false, the address of the __block 2161 /// structure that will be passed to _Block_object_dispose. When 2162 /// \p LoadBlockVarAddr is true, the address of the field of the block 2163 /// structure that holds the address of the __block structure. 2164 /// 2165 /// \param Flags The flag that will be passed to _Block_object_dispose. 2166 /// 2167 /// \param LoadBlockVarAddr Indicates whether we need to emit a load from 2168 /// \p Addr to get the address of the __block structure. 2169 void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, 2170 bool LoadBlockVarAddr, bool CanThrow); 2171 2172 void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, 2173 llvm::Value *ptr); 2174 2175 Address LoadBlockStruct(); 2176 Address GetAddrOfBlockDecl(const VarDecl *var); 2177 2178 /// BuildBlockByrefAddress - Computes the location of the 2179 /// data in a variable which is declared as __block. 2180 Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, 2181 bool followForward = true); 2182 Address emitBlockByrefAddress(Address baseAddr, 2183 const BlockByrefInfo &info, 2184 bool followForward, 2185 const llvm::Twine &name); 2186 2187 const BlockByrefInfo &getBlockByrefInfo(const VarDecl *var); 2188 2189 QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args); 2190 2191 void GenerateCode(GlobalDecl GD, llvm::Function *Fn, 2192 const CGFunctionInfo &FnInfo); 2193 2194 /// Annotate the function with an attribute that disables TSan checking at 2195 /// runtime. 2196 void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn); 2197 2198 /// Emit code for the start of a function. 2199 /// \param Loc The location to be associated with the function. 2200 /// \param StartLoc The location of the function body. 2201 void StartFunction(GlobalDecl GD, 2202 QualType RetTy, 2203 llvm::Function *Fn, 2204 const CGFunctionInfo &FnInfo, 2205 const FunctionArgList &Args, 2206 SourceLocation Loc = SourceLocation(), 2207 SourceLocation StartLoc = SourceLocation()); 2208 2209 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor); 2210 2211 void EmitConstructorBody(FunctionArgList &Args); 2212 void EmitDestructorBody(FunctionArgList &Args); 2213 void emitImplicitAssignmentOperatorBody(FunctionArgList &Args); 2214 void EmitFunctionBody(const Stmt *Body); 2215 void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S); 2216 2217 void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator, 2218 CallArgList &CallArgs); 2219 void EmitLambdaBlockInvokeBody(); 2220 void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD); 2221 void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD); 2222 void EmitLambdaVLACapture(const VariableArrayType *VAT, LValue LV) { 2223 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 2224 } 2225 void EmitAsanPrologueOrEpilogue(bool Prologue); 2226 2227 /// Emit the unified return block, trying to avoid its emission when 2228 /// possible. 2229 /// \return The debug location of the user written return statement if the 2230 /// return block is is avoided. 2231 llvm::DebugLoc EmitReturnBlock(); 2232 2233 /// FinishFunction - Complete IR generation of the current function. It is 2234 /// legal to call this function even if there is no current insertion point. 2235 void FinishFunction(SourceLocation EndLoc=SourceLocation()); 2236 2237 void StartThunk(llvm::Function *Fn, GlobalDecl GD, 2238 const CGFunctionInfo &FnInfo, bool IsUnprototyped); 2239 2240 void EmitCallAndReturnForThunk(llvm::FunctionCallee Callee, 2241 const ThunkInfo *Thunk, bool IsUnprototyped); 2242 2243 void FinishThunk(); 2244 2245 /// Emit a musttail call for a thunk with a potentially adjusted this pointer. 2246 void EmitMustTailThunk(GlobalDecl GD, llvm::Value *AdjustedThisPtr, 2247 llvm::FunctionCallee Callee); 2248 2249 /// Generate a thunk for the given method. 2250 void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo, 2251 GlobalDecl GD, const ThunkInfo &Thunk, 2252 bool IsUnprototyped); 2253 2254 llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn, 2255 const CGFunctionInfo &FnInfo, 2256 GlobalDecl GD, const ThunkInfo &Thunk); 2257 2258 void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type, 2259 FunctionArgList &Args); 2260 2261 void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init); 2262 2263 /// Struct with all information about dynamic [sub]class needed to set vptr. 2264 struct VPtr { 2265 BaseSubobject Base; 2266 const CXXRecordDecl *NearestVBase; 2267 CharUnits OffsetFromNearestVBase; 2268 const CXXRecordDecl *VTableClass; 2269 }; 2270 2271 /// Initialize the vtable pointer of the given subobject. 2272 void InitializeVTablePointer(const VPtr &vptr); 2273 2274 typedef llvm::SmallVector<VPtr, 4> VPtrsVector; 2275 2276 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy; 2277 VPtrsVector getVTablePointers(const CXXRecordDecl *VTableClass); 2278 2279 void getVTablePointers(BaseSubobject Base, const CXXRecordDecl *NearestVBase, 2280 CharUnits OffsetFromNearestVBase, 2281 bool BaseIsNonVirtualPrimaryBase, 2282 const CXXRecordDecl *VTableClass, 2283 VisitedVirtualBasesSetTy &VBases, VPtrsVector &vptrs); 2284 2285 void InitializeVTablePointers(const CXXRecordDecl *ClassDecl); 2286 2287 /// GetVTablePtr - Return the Value of the vtable pointer member pointed 2288 /// to by This. 2289 llvm::Value *GetVTablePtr(Address This, llvm::Type *VTableTy, 2290 const CXXRecordDecl *VTableClass); 2291 2292 enum CFITypeCheckKind { 2293 CFITCK_VCall, 2294 CFITCK_NVCall, 2295 CFITCK_DerivedCast, 2296 CFITCK_UnrelatedCast, 2297 CFITCK_ICall, 2298 CFITCK_NVMFCall, 2299 CFITCK_VMFCall, 2300 }; 2301 2302 /// Derived is the presumed address of an object of type T after a 2303 /// cast. If T is a polymorphic class type, emit a check that the virtual 2304 /// table for Derived belongs to a class derived from T. 2305 void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived, 2306 bool MayBeNull, CFITypeCheckKind TCK, 2307 SourceLocation Loc); 2308 2309 /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable. 2310 /// If vptr CFI is enabled, emit a check that VTable is valid. 2311 void EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, llvm::Value *VTable, 2312 CFITypeCheckKind TCK, SourceLocation Loc); 2313 2314 /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for 2315 /// RD using llvm.type.test. 2316 void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable, 2317 CFITypeCheckKind TCK, SourceLocation Loc); 2318 2319 /// If whole-program virtual table optimization is enabled, emit an assumption 2320 /// that VTable is a member of RD's type identifier. Or, if vptr CFI is 2321 /// enabled, emit a check that VTable is a member of RD's type identifier. 2322 void EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 2323 llvm::Value *VTable, SourceLocation Loc); 2324 2325 /// Returns whether we should perform a type checked load when loading a 2326 /// virtual function for virtual calls to members of RD. This is generally 2327 /// true when both vcall CFI and whole-program-vtables are enabled. 2328 bool ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD); 2329 2330 /// Emit a type checked load from the given vtable. 2331 llvm::Value *EmitVTableTypeCheckedLoad(const CXXRecordDecl *RD, llvm::Value *VTable, 2332 uint64_t VTableByteOffset); 2333 2334 /// EnterDtorCleanups - Enter the cleanups necessary to complete the 2335 /// given phase of destruction for a destructor. The end result 2336 /// should call destructors on members and base classes in reverse 2337 /// order of their construction. 2338 void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type); 2339 2340 /// ShouldInstrumentFunction - Return true if the current function should be 2341 /// instrumented with __cyg_profile_func_* calls 2342 bool ShouldInstrumentFunction(); 2343 2344 /// ShouldSkipSanitizerInstrumentation - Return true if the current function 2345 /// should not be instrumented with sanitizers. 2346 bool ShouldSkipSanitizerInstrumentation(); 2347 2348 /// ShouldXRayInstrument - Return true if the current function should be 2349 /// instrumented with XRay nop sleds. 2350 bool ShouldXRayInstrumentFunction() const; 2351 2352 /// AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit 2353 /// XRay custom event handling calls. 2354 bool AlwaysEmitXRayCustomEvents() const; 2355 2356 /// AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit 2357 /// XRay typed event handling calls. 2358 bool AlwaysEmitXRayTypedEvents() const; 2359 2360 /// Encode an address into a form suitable for use in a function prologue. 2361 llvm::Constant *EncodeAddrForUseInPrologue(llvm::Function *F, 2362 llvm::Constant *Addr); 2363 2364 /// Decode an address used in a function prologue, encoded by \c 2365 /// EncodeAddrForUseInPrologue. 2366 llvm::Value *DecodeAddrUsedInPrologue(llvm::Value *F, 2367 llvm::Value *EncodedAddr); 2368 2369 /// EmitFunctionProlog - Emit the target specific LLVM code to load the 2370 /// arguments for the given function. This is also responsible for naming the 2371 /// LLVM function arguments. 2372 void EmitFunctionProlog(const CGFunctionInfo &FI, 2373 llvm::Function *Fn, 2374 const FunctionArgList &Args); 2375 2376 /// EmitFunctionEpilog - Emit the target specific LLVM code to return the 2377 /// given temporary. 2378 void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, 2379 SourceLocation EndLoc); 2380 2381 /// Emit a test that checks if the return value \p RV is nonnull. 2382 void EmitReturnValueCheck(llvm::Value *RV); 2383 2384 /// EmitStartEHSpec - Emit the start of the exception spec. 2385 void EmitStartEHSpec(const Decl *D); 2386 2387 /// EmitEndEHSpec - Emit the end of the exception spec. 2388 void EmitEndEHSpec(const Decl *D); 2389 2390 /// getTerminateLandingPad - Return a landing pad that just calls terminate. 2391 llvm::BasicBlock *getTerminateLandingPad(); 2392 2393 /// getTerminateLandingPad - Return a cleanup funclet that just calls 2394 /// terminate. 2395 llvm::BasicBlock *getTerminateFunclet(); 2396 2397 /// getTerminateHandler - Return a handler (not a landing pad, just 2398 /// a catch handler) that just calls terminate. This is used when 2399 /// a terminate scope encloses a try. 2400 llvm::BasicBlock *getTerminateHandler(); 2401 2402 llvm::Type *ConvertTypeForMem(QualType T); 2403 llvm::Type *ConvertType(QualType T); 2404 llvm::Type *ConvertType(const TypeDecl *T) { 2405 return ConvertType(getContext().getTypeDeclType(T)); 2406 } 2407 2408 /// LoadObjCSelf - Load the value of self. This function is only valid while 2409 /// generating code for an Objective-C method. 2410 llvm::Value *LoadObjCSelf(); 2411 2412 /// TypeOfSelfObject - Return type of object that this self represents. 2413 QualType TypeOfSelfObject(); 2414 2415 /// getEvaluationKind - Return the TypeEvaluationKind of QualType \c T. 2416 static TypeEvaluationKind getEvaluationKind(QualType T); 2417 2418 static bool hasScalarEvaluationKind(QualType T) { 2419 return getEvaluationKind(T) == TEK_Scalar; 2420 } 2421 2422 static bool hasAggregateEvaluationKind(QualType T) { 2423 return getEvaluationKind(T) == TEK_Aggregate; 2424 } 2425 2426 /// createBasicBlock - Create an LLVM basic block. 2427 llvm::BasicBlock *createBasicBlock(const Twine &name = "", 2428 llvm::Function *parent = nullptr, 2429 llvm::BasicBlock *before = nullptr) { 2430 return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before); 2431 } 2432 2433 /// getBasicBlockForLabel - Return the LLVM basicblock that the specified 2434 /// label maps to. 2435 JumpDest getJumpDestForLabel(const LabelDecl *S); 2436 2437 /// SimplifyForwardingBlocks - If the given basic block is only a branch to 2438 /// another basic block, simplify it. This assumes that no other code could 2439 /// potentially reference the basic block. 2440 void SimplifyForwardingBlocks(llvm::BasicBlock *BB); 2441 2442 /// EmitBlock - Emit the given block \arg BB and set it as the insert point, 2443 /// adding a fall-through branch from the current insert block if 2444 /// necessary. It is legal to call this function even if there is no current 2445 /// insertion point. 2446 /// 2447 /// IsFinished - If true, indicates that the caller has finished emitting 2448 /// branches to the given block and does not expect to emit code into it. This 2449 /// means the block can be ignored if it is unreachable. 2450 void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false); 2451 2452 /// EmitBlockAfterUses - Emit the given block somewhere hopefully 2453 /// near its uses, and leave the insertion point in it. 2454 void EmitBlockAfterUses(llvm::BasicBlock *BB); 2455 2456 /// EmitBranch - Emit a branch to the specified basic block from the current 2457 /// insert block, taking care to avoid creation of branches from dummy 2458 /// blocks. It is legal to call this function even if there is no current 2459 /// insertion point. 2460 /// 2461 /// This function clears the current insertion point. The caller should follow 2462 /// calls to this function with calls to Emit*Block prior to generation new 2463 /// code. 2464 void EmitBranch(llvm::BasicBlock *Block); 2465 2466 /// HaveInsertPoint - True if an insertion point is defined. If not, this 2467 /// indicates that the current code being emitted is unreachable. 2468 bool HaveInsertPoint() const { 2469 return Builder.GetInsertBlock() != nullptr; 2470 } 2471 2472 /// EnsureInsertPoint - Ensure that an insertion point is defined so that 2473 /// emitted IR has a place to go. Note that by definition, if this function 2474 /// creates a block then that block is unreachable; callers may do better to 2475 /// detect when no insertion point is defined and simply skip IR generation. 2476 void EnsureInsertPoint() { 2477 if (!HaveInsertPoint()) 2478 EmitBlock(createBasicBlock()); 2479 } 2480 2481 /// ErrorUnsupported - Print out an error that codegen doesn't support the 2482 /// specified stmt yet. 2483 void ErrorUnsupported(const Stmt *S, const char *Type); 2484 2485 //===--------------------------------------------------------------------===// 2486 // Helpers 2487 //===--------------------------------------------------------------------===// 2488 2489 LValue MakeAddrLValue(Address Addr, QualType T, 2490 AlignmentSource Source = AlignmentSource::Type) { 2491 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2492 CGM.getTBAAAccessInfo(T)); 2493 } 2494 2495 LValue MakeAddrLValue(Address Addr, QualType T, LValueBaseInfo BaseInfo, 2496 TBAAAccessInfo TBAAInfo) { 2497 return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo); 2498 } 2499 2500 LValue MakeAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, 2501 AlignmentSource Source = AlignmentSource::Type) { 2502 Address Addr(V, ConvertTypeForMem(T), Alignment); 2503 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2504 CGM.getTBAAAccessInfo(T)); 2505 } 2506 2507 LValue 2508 MakeAddrLValueWithoutTBAA(Address Addr, QualType T, 2509 AlignmentSource Source = AlignmentSource::Type) { 2510 return LValue::MakeAddr(Addr, T, getContext(), LValueBaseInfo(Source), 2511 TBAAAccessInfo()); 2512 } 2513 2514 LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T); 2515 LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T); 2516 2517 Address EmitLoadOfReference(LValue RefLVal, 2518 LValueBaseInfo *PointeeBaseInfo = nullptr, 2519 TBAAAccessInfo *PointeeTBAAInfo = nullptr); 2520 LValue EmitLoadOfReferenceLValue(LValue RefLVal); 2521 LValue EmitLoadOfReferenceLValue(Address RefAddr, QualType RefTy, 2522 AlignmentSource Source = 2523 AlignmentSource::Type) { 2524 LValue RefLVal = MakeAddrLValue(RefAddr, RefTy, LValueBaseInfo(Source), 2525 CGM.getTBAAAccessInfo(RefTy)); 2526 return EmitLoadOfReferenceLValue(RefLVal); 2527 } 2528 2529 Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, 2530 LValueBaseInfo *BaseInfo = nullptr, 2531 TBAAAccessInfo *TBAAInfo = nullptr); 2532 LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy); 2533 2534 /// CreateTempAlloca - This creates an alloca and inserts it into the entry 2535 /// block if \p ArraySize is nullptr, otherwise inserts it at the current 2536 /// insertion point of the builder. The caller is responsible for setting an 2537 /// appropriate alignment on 2538 /// the alloca. 2539 /// 2540 /// \p ArraySize is the number of array elements to be allocated if it 2541 /// is not nullptr. 2542 /// 2543 /// LangAS::Default is the address space of pointers to local variables and 2544 /// temporaries, as exposed in the source language. In certain 2545 /// configurations, this is not the same as the alloca address space, and a 2546 /// cast is needed to lift the pointer from the alloca AS into 2547 /// LangAS::Default. This can happen when the target uses a restricted 2548 /// address space for the stack but the source language requires 2549 /// LangAS::Default to be a generic address space. The latter condition is 2550 /// common for most programming languages; OpenCL is an exception in that 2551 /// LangAS::Default is the private address space, which naturally maps 2552 /// to the stack. 2553 /// 2554 /// Because the address of a temporary is often exposed to the program in 2555 /// various ways, this function will perform the cast. The original alloca 2556 /// instruction is returned through \p Alloca if it is not nullptr. 2557 /// 2558 /// The cast is not performaed in CreateTempAllocaWithoutCast. This is 2559 /// more efficient if the caller knows that the address will not be exposed. 2560 llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty, const Twine &Name = "tmp", 2561 llvm::Value *ArraySize = nullptr); 2562 Address CreateTempAlloca(llvm::Type *Ty, CharUnits align, 2563 const Twine &Name = "tmp", 2564 llvm::Value *ArraySize = nullptr, 2565 Address *Alloca = nullptr); 2566 Address CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, 2567 const Twine &Name = "tmp", 2568 llvm::Value *ArraySize = nullptr); 2569 2570 /// CreateDefaultAlignedTempAlloca - This creates an alloca with the 2571 /// default ABI alignment of the given LLVM type. 2572 /// 2573 /// IMPORTANT NOTE: This is *not* generally the right alignment for 2574 /// any given AST type that happens to have been lowered to the 2575 /// given IR type. This should only ever be used for function-local, 2576 /// IR-driven manipulations like saving and restoring a value. Do 2577 /// not hand this address off to arbitrary IRGen routines, and especially 2578 /// do not pass it as an argument to a function that might expect a 2579 /// properly ABI-aligned value. 2580 Address CreateDefaultAlignTempAlloca(llvm::Type *Ty, 2581 const Twine &Name = "tmp"); 2582 2583 /// CreateIRTemp - Create a temporary IR object of the given type, with 2584 /// appropriate alignment. This routine should only be used when an temporary 2585 /// value needs to be stored into an alloca (for example, to avoid explicit 2586 /// PHI construction), but the type is the IR type, not the type appropriate 2587 /// for storing in memory. 2588 /// 2589 /// That is, this is exactly equivalent to CreateMemTemp, but calling 2590 /// ConvertType instead of ConvertTypeForMem. 2591 Address CreateIRTemp(QualType T, const Twine &Name = "tmp"); 2592 2593 /// CreateMemTemp - Create a temporary memory object of the given type, with 2594 /// appropriate alignmen and cast it to the default address space. Returns 2595 /// the original alloca instruction by \p Alloca if it is not nullptr. 2596 Address CreateMemTemp(QualType T, const Twine &Name = "tmp", 2597 Address *Alloca = nullptr); 2598 Address CreateMemTemp(QualType T, CharUnits Align, const Twine &Name = "tmp", 2599 Address *Alloca = nullptr); 2600 2601 /// CreateMemTemp - Create a temporary memory object of the given type, with 2602 /// appropriate alignmen without casting it to the default address space. 2603 Address CreateMemTempWithoutCast(QualType T, const Twine &Name = "tmp"); 2604 Address CreateMemTempWithoutCast(QualType T, CharUnits Align, 2605 const Twine &Name = "tmp"); 2606 2607 /// CreateAggTemp - Create a temporary memory object for the given 2608 /// aggregate type. 2609 AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp", 2610 Address *Alloca = nullptr) { 2611 return AggValueSlot::forAddr(CreateMemTemp(T, Name, Alloca), 2612 T.getQualifiers(), 2613 AggValueSlot::IsNotDestructed, 2614 AggValueSlot::DoesNotNeedGCBarriers, 2615 AggValueSlot::IsNotAliased, 2616 AggValueSlot::DoesNotOverlap); 2617 } 2618 2619 /// Emit a cast to void* in the appropriate address space. 2620 llvm::Value *EmitCastToVoidPtr(llvm::Value *value); 2621 2622 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified 2623 /// expression and compare the result against zero, returning an Int1Ty value. 2624 llvm::Value *EvaluateExprAsBool(const Expr *E); 2625 2626 /// EmitIgnoredExpr - Emit an expression in a context which ignores the result. 2627 void EmitIgnoredExpr(const Expr *E); 2628 2629 /// EmitAnyExpr - Emit code to compute the specified expression which can have 2630 /// any type. The result is returned as an RValue struct. If this is an 2631 /// aggregate expression, the aggloc/agglocvolatile arguments indicate where 2632 /// the result should be returned. 2633 /// 2634 /// \param ignoreResult True if the resulting value isn't used. 2635 RValue EmitAnyExpr(const Expr *E, 2636 AggValueSlot aggSlot = AggValueSlot::ignored(), 2637 bool ignoreResult = false); 2638 2639 // EmitVAListRef - Emit a "reference" to a va_list; this is either the address 2640 // or the value of the expression, depending on how va_list is defined. 2641 Address EmitVAListRef(const Expr *E); 2642 2643 /// Emit a "reference" to a __builtin_ms_va_list; this is 2644 /// always the value of the expression, because a __builtin_ms_va_list is a 2645 /// pointer to a char. 2646 Address EmitMSVAListRef(const Expr *E); 2647 2648 /// EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will 2649 /// always be accessible even if no aggregate location is provided. 2650 RValue EmitAnyExprToTemp(const Expr *E); 2651 2652 /// EmitAnyExprToMem - Emits the code necessary to evaluate an 2653 /// arbitrary expression into the given memory location. 2654 void EmitAnyExprToMem(const Expr *E, Address Location, 2655 Qualifiers Quals, bool IsInitializer); 2656 2657 void EmitAnyExprToExn(const Expr *E, Address Addr); 2658 2659 /// EmitExprAsInit - Emits the code necessary to initialize a 2660 /// location in memory with the given initializer. 2661 void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, 2662 bool capturedByInit); 2663 2664 /// hasVolatileMember - returns true if aggregate type has a volatile 2665 /// member. 2666 bool hasVolatileMember(QualType T) { 2667 if (const RecordType *RT = T->getAs<RecordType>()) { 2668 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl()); 2669 return RD->hasVolatileMember(); 2670 } 2671 return false; 2672 } 2673 2674 /// Determine whether a return value slot may overlap some other object. 2675 AggValueSlot::Overlap_t getOverlapForReturnValue() { 2676 // FIXME: Assuming no overlap here breaks guaranteed copy elision for base 2677 // class subobjects. These cases may need to be revisited depending on the 2678 // resolution of the relevant core issue. 2679 return AggValueSlot::DoesNotOverlap; 2680 } 2681 2682 /// Determine whether a field initialization may overlap some other object. 2683 AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD); 2684 2685 /// Determine whether a base class initialization may overlap some other 2686 /// object. 2687 AggValueSlot::Overlap_t getOverlapForBaseInit(const CXXRecordDecl *RD, 2688 const CXXRecordDecl *BaseRD, 2689 bool IsVirtual); 2690 2691 /// Emit an aggregate assignment. 2692 void EmitAggregateAssign(LValue Dest, LValue Src, QualType EltTy) { 2693 bool IsVolatile = hasVolatileMember(EltTy); 2694 EmitAggregateCopy(Dest, Src, EltTy, AggValueSlot::MayOverlap, IsVolatile); 2695 } 2696 2697 void EmitAggregateCopyCtor(LValue Dest, LValue Src, 2698 AggValueSlot::Overlap_t MayOverlap) { 2699 EmitAggregateCopy(Dest, Src, Src.getType(), MayOverlap); 2700 } 2701 2702 /// EmitAggregateCopy - Emit an aggregate copy. 2703 /// 2704 /// \param isVolatile \c true iff either the source or the destination is 2705 /// volatile. 2706 /// \param MayOverlap Whether the tail padding of the destination might be 2707 /// occupied by some other object. More efficient code can often be 2708 /// generated if not. 2709 void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, 2710 AggValueSlot::Overlap_t MayOverlap, 2711 bool isVolatile = false); 2712 2713 /// GetAddrOfLocalVar - Return the address of a local variable. 2714 Address GetAddrOfLocalVar(const VarDecl *VD) { 2715 auto it = LocalDeclMap.find(VD); 2716 assert(it != LocalDeclMap.end() && 2717 "Invalid argument to GetAddrOfLocalVar(), no decl!"); 2718 return it->second; 2719 } 2720 2721 /// Given an opaque value expression, return its LValue mapping if it exists, 2722 /// otherwise create one. 2723 LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e); 2724 2725 /// Given an opaque value expression, return its RValue mapping if it exists, 2726 /// otherwise create one. 2727 RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e); 2728 2729 /// Get the index of the current ArrayInitLoopExpr, if any. 2730 llvm::Value *getArrayInitIndex() { return ArrayInitIndex; } 2731 2732 /// getAccessedFieldNo - Given an encoded value and a result number, return 2733 /// the input field number being accessed. 2734 static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts); 2735 2736 llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L); 2737 llvm::BasicBlock *GetIndirectGotoBlock(); 2738 2739 /// Check if \p E is a C++ "this" pointer wrapped in value-preserving casts. 2740 static bool IsWrappedCXXThis(const Expr *E); 2741 2742 /// EmitNullInitialization - Generate code to set a value of the given type to 2743 /// null, If the type contains data member pointers, they will be initialized 2744 /// to -1 in accordance with the Itanium C++ ABI. 2745 void EmitNullInitialization(Address DestPtr, QualType Ty); 2746 2747 /// Emits a call to an LLVM variable-argument intrinsic, either 2748 /// \c llvm.va_start or \c llvm.va_end. 2749 /// \param ArgValue A reference to the \c va_list as emitted by either 2750 /// \c EmitVAListRef or \c EmitMSVAListRef. 2751 /// \param IsStart If \c true, emits a call to \c llvm.va_start; otherwise, 2752 /// calls \c llvm.va_end. 2753 llvm::Value *EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart); 2754 2755 /// Generate code to get an argument from the passed in pointer 2756 /// and update it accordingly. 2757 /// \param VE The \c VAArgExpr for which to generate code. 2758 /// \param VAListAddr Receives a reference to the \c va_list as emitted by 2759 /// either \c EmitVAListRef or \c EmitMSVAListRef. 2760 /// \returns A pointer to the argument. 2761 // FIXME: We should be able to get rid of this method and use the va_arg 2762 // instruction in LLVM instead once it works well enough. 2763 Address EmitVAArg(VAArgExpr *VE, Address &VAListAddr); 2764 2765 /// emitArrayLength - Compute the length of an array, even if it's a 2766 /// VLA, and drill down to the base element type. 2767 llvm::Value *emitArrayLength(const ArrayType *arrayType, 2768 QualType &baseType, 2769 Address &addr); 2770 2771 /// EmitVLASize - Capture all the sizes for the VLA expressions in 2772 /// the given variably-modified type and store them in the VLASizeMap. 2773 /// 2774 /// This function can be called with a null (unreachable) insert point. 2775 void EmitVariablyModifiedType(QualType Ty); 2776 2777 struct VlaSizePair { 2778 llvm::Value *NumElts; 2779 QualType Type; 2780 2781 VlaSizePair(llvm::Value *NE, QualType T) : NumElts(NE), Type(T) {} 2782 }; 2783 2784 /// Return the number of elements for a single dimension 2785 /// for the given array type. 2786 VlaSizePair getVLAElements1D(const VariableArrayType *vla); 2787 VlaSizePair getVLAElements1D(QualType vla); 2788 2789 /// Returns an LLVM value that corresponds to the size, 2790 /// in non-variably-sized elements, of a variable length array type, 2791 /// plus that largest non-variably-sized element type. Assumes that 2792 /// the type has already been emitted with EmitVariablyModifiedType. 2793 VlaSizePair getVLASize(const VariableArrayType *vla); 2794 VlaSizePair getVLASize(QualType vla); 2795 2796 /// LoadCXXThis - Load the value of 'this'. This function is only valid while 2797 /// generating code for an C++ member function. 2798 llvm::Value *LoadCXXThis() { 2799 assert(CXXThisValue && "no 'this' value for this function"); 2800 return CXXThisValue; 2801 } 2802 Address LoadCXXThisAddress(); 2803 2804 /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have 2805 /// virtual bases. 2806 // FIXME: Every place that calls LoadCXXVTT is something 2807 // that needs to be abstracted properly. 2808 llvm::Value *LoadCXXVTT() { 2809 assert(CXXStructorImplicitParamValue && "no VTT value for this function"); 2810 return CXXStructorImplicitParamValue; 2811 } 2812 2813 /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a 2814 /// complete class to the given direct base. 2815 Address 2816 GetAddressOfDirectBaseInCompleteClass(Address Value, 2817 const CXXRecordDecl *Derived, 2818 const CXXRecordDecl *Base, 2819 bool BaseIsVirtual); 2820 2821 static bool ShouldNullCheckClassCastValue(const CastExpr *Cast); 2822 2823 /// GetAddressOfBaseClass - This function will add the necessary delta to the 2824 /// load of 'this' and returns address of the base class. 2825 Address GetAddressOfBaseClass(Address Value, 2826 const CXXRecordDecl *Derived, 2827 CastExpr::path_const_iterator PathBegin, 2828 CastExpr::path_const_iterator PathEnd, 2829 bool NullCheckValue, SourceLocation Loc); 2830 2831 Address GetAddressOfDerivedClass(Address Value, 2832 const CXXRecordDecl *Derived, 2833 CastExpr::path_const_iterator PathBegin, 2834 CastExpr::path_const_iterator PathEnd, 2835 bool NullCheckValue); 2836 2837 /// GetVTTParameter - Return the VTT parameter that should be passed to a 2838 /// base constructor/destructor with virtual bases. 2839 /// FIXME: VTTs are Itanium ABI-specific, so the definition should move 2840 /// to ItaniumCXXABI.cpp together with all the references to VTT. 2841 llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase, 2842 bool Delegating); 2843 2844 void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2845 CXXCtorType CtorType, 2846 const FunctionArgList &Args, 2847 SourceLocation Loc); 2848 // It's important not to confuse this and the previous function. Delegating 2849 // constructors are the C++0x feature. The constructor delegate optimization 2850 // is used to reduce duplication in the base and complete consturctors where 2851 // they are substantially the same. 2852 void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2853 const FunctionArgList &Args); 2854 2855 /// Emit a call to an inheriting constructor (that is, one that invokes a 2856 /// constructor inherited from a base class) by inlining its definition. This 2857 /// is necessary if the ABI does not support forwarding the arguments to the 2858 /// base class constructor (because they're variadic or similar). 2859 void EmitInlinedInheritingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2860 CXXCtorType CtorType, 2861 bool ForVirtualBase, 2862 bool Delegating, 2863 CallArgList &Args); 2864 2865 /// Emit a call to a constructor inherited from a base class, passing the 2866 /// current constructor's arguments along unmodified (without even making 2867 /// a copy). 2868 void EmitInheritedCXXConstructorCall(const CXXConstructorDecl *D, 2869 bool ForVirtualBase, Address This, 2870 bool InheritedFromVBase, 2871 const CXXInheritedCtorInitExpr *E); 2872 2873 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2874 bool ForVirtualBase, bool Delegating, 2875 AggValueSlot ThisAVS, const CXXConstructExpr *E); 2876 2877 void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type, 2878 bool ForVirtualBase, bool Delegating, 2879 Address This, CallArgList &Args, 2880 AggValueSlot::Overlap_t Overlap, 2881 SourceLocation Loc, bool NewPointerIsChecked); 2882 2883 /// Emit assumption load for all bases. Requires to be be called only on 2884 /// most-derived class and not under construction of the object. 2885 void EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, Address This); 2886 2887 /// Emit assumption that vptr load == global vtable. 2888 void EmitVTableAssumptionLoad(const VPtr &vptr, Address This); 2889 2890 void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2891 Address This, Address Src, 2892 const CXXConstructExpr *E); 2893 2894 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2895 const ArrayType *ArrayTy, 2896 Address ArrayPtr, 2897 const CXXConstructExpr *E, 2898 bool NewPointerIsChecked, 2899 bool ZeroInitialization = false); 2900 2901 void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 2902 llvm::Value *NumElements, 2903 Address ArrayPtr, 2904 const CXXConstructExpr *E, 2905 bool NewPointerIsChecked, 2906 bool ZeroInitialization = false); 2907 2908 static Destroyer destroyCXXObject; 2909 2910 void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, 2911 bool ForVirtualBase, bool Delegating, Address This, 2912 QualType ThisTy); 2913 2914 void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType, 2915 llvm::Type *ElementTy, Address NewPtr, 2916 llvm::Value *NumElements, 2917 llvm::Value *AllocSizeWithoutCookie); 2918 2919 void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, 2920 Address Ptr); 2921 2922 void EmitSehCppScopeBegin(); 2923 void EmitSehCppScopeEnd(); 2924 void EmitSehTryScopeBegin(); 2925 void EmitSehTryScopeEnd(); 2926 2927 llvm::Value *EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr); 2928 void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr); 2929 2930 llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E); 2931 void EmitCXXDeleteExpr(const CXXDeleteExpr *E); 2932 2933 void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr, 2934 QualType DeleteTy, llvm::Value *NumElements = nullptr, 2935 CharUnits CookieSize = CharUnits()); 2936 2937 RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 2938 const CallExpr *TheCallExpr, bool IsDelete); 2939 2940 llvm::Value *EmitCXXTypeidExpr(const CXXTypeidExpr *E); 2941 llvm::Value *EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE); 2942 Address EmitCXXUuidofExpr(const CXXUuidofExpr *E); 2943 2944 /// Situations in which we might emit a check for the suitability of a 2945 /// pointer or glvalue. Needs to be kept in sync with ubsan_handlers.cpp in 2946 /// compiler-rt. 2947 enum TypeCheckKind { 2948 /// Checking the operand of a load. Must be suitably sized and aligned. 2949 TCK_Load, 2950 /// Checking the destination of a store. Must be suitably sized and aligned. 2951 TCK_Store, 2952 /// Checking the bound value in a reference binding. Must be suitably sized 2953 /// and aligned, but is not required to refer to an object (until the 2954 /// reference is used), per core issue 453. 2955 TCK_ReferenceBinding, 2956 /// Checking the object expression in a non-static data member access. Must 2957 /// be an object within its lifetime. 2958 TCK_MemberAccess, 2959 /// Checking the 'this' pointer for a call to a non-static member function. 2960 /// Must be an object within its lifetime. 2961 TCK_MemberCall, 2962 /// Checking the 'this' pointer for a constructor call. 2963 TCK_ConstructorCall, 2964 /// Checking the operand of a static_cast to a derived pointer type. Must be 2965 /// null or an object within its lifetime. 2966 TCK_DowncastPointer, 2967 /// Checking the operand of a static_cast to a derived reference type. Must 2968 /// be an object within its lifetime. 2969 TCK_DowncastReference, 2970 /// Checking the operand of a cast to a base object. Must be suitably sized 2971 /// and aligned. 2972 TCK_Upcast, 2973 /// Checking the operand of a cast to a virtual base object. Must be an 2974 /// object within its lifetime. 2975 TCK_UpcastToVirtualBase, 2976 /// Checking the value assigned to a _Nonnull pointer. Must not be null. 2977 TCK_NonnullAssign, 2978 /// Checking the operand of a dynamic_cast or a typeid expression. Must be 2979 /// null or an object within its lifetime. 2980 TCK_DynamicOperation 2981 }; 2982 2983 /// Determine whether the pointer type check \p TCK permits null pointers. 2984 static bool isNullPointerAllowed(TypeCheckKind TCK); 2985 2986 /// Determine whether the pointer type check \p TCK requires a vptr check. 2987 static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty); 2988 2989 /// Whether any type-checking sanitizers are enabled. If \c false, 2990 /// calls to EmitTypeCheck can be skipped. 2991 bool sanitizePerformTypeCheck() const; 2992 2993 /// Emit a check that \p V is the address of storage of the 2994 /// appropriate size and alignment for an object of type \p Type 2995 /// (or if ArraySize is provided, for an array of that bound). 2996 void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V, 2997 QualType Type, CharUnits Alignment = CharUnits::Zero(), 2998 SanitizerSet SkippedChecks = SanitizerSet(), 2999 llvm::Value *ArraySize = nullptr); 3000 3001 /// Emit a check that \p Base points into an array object, which 3002 /// we can access at index \p Index. \p Accessed should be \c false if we 3003 /// this expression is used as an lvalue, for instance in "&Arr[Idx]". 3004 void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, 3005 QualType IndexType, bool Accessed); 3006 3007 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, 3008 bool isInc, bool isPre); 3009 ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, 3010 bool isInc, bool isPre); 3011 3012 /// Converts Location to a DebugLoc, if debug information is enabled. 3013 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location); 3014 3015 /// Get the record field index as represented in debug info. 3016 unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex); 3017 3018 3019 //===--------------------------------------------------------------------===// 3020 // Declaration Emission 3021 //===--------------------------------------------------------------------===// 3022 3023 /// EmitDecl - Emit a declaration. 3024 /// 3025 /// This function can be called with a null (unreachable) insert point. 3026 void EmitDecl(const Decl &D); 3027 3028 /// EmitVarDecl - Emit a local variable declaration. 3029 /// 3030 /// This function can be called with a null (unreachable) insert point. 3031 void EmitVarDecl(const VarDecl &D); 3032 3033 void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, 3034 bool capturedByInit); 3035 3036 typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D, 3037 llvm::Value *Address); 3038 3039 /// Determine whether the given initializer is trivial in the sense 3040 /// that it requires no code to be generated. 3041 bool isTrivialInitializer(const Expr *Init); 3042 3043 /// EmitAutoVarDecl - Emit an auto variable declaration. 3044 /// 3045 /// This function can be called with a null (unreachable) insert point. 3046 void EmitAutoVarDecl(const VarDecl &D); 3047 3048 class AutoVarEmission { 3049 friend class CodeGenFunction; 3050 3051 const VarDecl *Variable; 3052 3053 /// The address of the alloca for languages with explicit address space 3054 /// (e.g. OpenCL) or alloca casted to generic pointer for address space 3055 /// agnostic languages (e.g. C++). Invalid if the variable was emitted 3056 /// as a global constant. 3057 Address Addr; 3058 3059 llvm::Value *NRVOFlag; 3060 3061 /// True if the variable is a __block variable that is captured by an 3062 /// escaping block. 3063 bool IsEscapingByRef; 3064 3065 /// True if the variable is of aggregate type and has a constant 3066 /// initializer. 3067 bool IsConstantAggregate; 3068 3069 /// Non-null if we should use lifetime annotations. 3070 llvm::Value *SizeForLifetimeMarkers; 3071 3072 /// Address with original alloca instruction. Invalid if the variable was 3073 /// emitted as a global constant. 3074 Address AllocaAddr; 3075 3076 struct Invalid {}; 3077 AutoVarEmission(Invalid) 3078 : Variable(nullptr), Addr(Address::invalid()), 3079 AllocaAddr(Address::invalid()) {} 3080 3081 AutoVarEmission(const VarDecl &variable) 3082 : Variable(&variable), Addr(Address::invalid()), NRVOFlag(nullptr), 3083 IsEscapingByRef(false), IsConstantAggregate(false), 3084 SizeForLifetimeMarkers(nullptr), AllocaAddr(Address::invalid()) {} 3085 3086 bool wasEmittedAsGlobal() const { return !Addr.isValid(); } 3087 3088 public: 3089 static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); } 3090 3091 bool useLifetimeMarkers() const { 3092 return SizeForLifetimeMarkers != nullptr; 3093 } 3094 llvm::Value *getSizeForLifetimeMarkers() const { 3095 assert(useLifetimeMarkers()); 3096 return SizeForLifetimeMarkers; 3097 } 3098 3099 /// Returns the raw, allocated address, which is not necessarily 3100 /// the address of the object itself. It is casted to default 3101 /// address space for address space agnostic languages. 3102 Address getAllocatedAddress() const { 3103 return Addr; 3104 } 3105 3106 /// Returns the address for the original alloca instruction. 3107 Address getOriginalAllocatedAddress() const { return AllocaAddr; } 3108 3109 /// Returns the address of the object within this declaration. 3110 /// Note that this does not chase the forwarding pointer for 3111 /// __block decls. 3112 Address getObjectAddress(CodeGenFunction &CGF) const { 3113 if (!IsEscapingByRef) return Addr; 3114 3115 return CGF.emitBlockByrefAddress(Addr, Variable, /*forward*/ false); 3116 } 3117 }; 3118 AutoVarEmission EmitAutoVarAlloca(const VarDecl &var); 3119 void EmitAutoVarInit(const AutoVarEmission &emission); 3120 void EmitAutoVarCleanups(const AutoVarEmission &emission); 3121 void emitAutoVarTypeCleanup(const AutoVarEmission &emission, 3122 QualType::DestructionKind dtorKind); 3123 3124 /// Emits the alloca and debug information for the size expressions for each 3125 /// dimension of an array. It registers the association of its (1-dimensional) 3126 /// QualTypes and size expression's debug node, so that CGDebugInfo can 3127 /// reference this node when creating the DISubrange object to describe the 3128 /// array types. 3129 void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, 3130 const VarDecl &D, 3131 bool EmitDebugInfo); 3132 3133 void EmitStaticVarDecl(const VarDecl &D, 3134 llvm::GlobalValue::LinkageTypes Linkage); 3135 3136 class ParamValue { 3137 llvm::Value *Value; 3138 llvm::Type *ElementType; 3139 unsigned Alignment; 3140 ParamValue(llvm::Value *V, llvm::Type *T, unsigned A) 3141 : Value(V), ElementType(T), Alignment(A) {} 3142 public: 3143 static ParamValue forDirect(llvm::Value *value) { 3144 return ParamValue(value, nullptr, 0); 3145 } 3146 static ParamValue forIndirect(Address addr) { 3147 assert(!addr.getAlignment().isZero()); 3148 return ParamValue(addr.getPointer(), addr.getElementType(), 3149 addr.getAlignment().getQuantity()); 3150 } 3151 3152 bool isIndirect() const { return Alignment != 0; } 3153 llvm::Value *getAnyValue() const { return Value; } 3154 3155 llvm::Value *getDirectValue() const { 3156 assert(!isIndirect()); 3157 return Value; 3158 } 3159 3160 Address getIndirectAddress() const { 3161 assert(isIndirect()); 3162 return Address(Value, ElementType, CharUnits::fromQuantity(Alignment)); 3163 } 3164 }; 3165 3166 /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl. 3167 void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo); 3168 3169 /// protectFromPeepholes - Protect a value that we're intending to 3170 /// store to the side, but which will probably be used later, from 3171 /// aggressive peepholing optimizations that might delete it. 3172 /// 3173 /// Pass the result to unprotectFromPeepholes to declare that 3174 /// protection is no longer required. 3175 /// 3176 /// There's no particular reason why this shouldn't apply to 3177 /// l-values, it's just that no existing peepholes work on pointers. 3178 PeepholeProtection protectFromPeepholes(RValue rvalue); 3179 void unprotectFromPeepholes(PeepholeProtection protection); 3180 3181 void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, 3182 SourceLocation Loc, 3183 SourceLocation AssumptionLoc, 3184 llvm::Value *Alignment, 3185 llvm::Value *OffsetValue, 3186 llvm::Value *TheCheck, 3187 llvm::Instruction *Assumption); 3188 3189 void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, 3190 SourceLocation Loc, SourceLocation AssumptionLoc, 3191 llvm::Value *Alignment, 3192 llvm::Value *OffsetValue = nullptr); 3193 3194 void emitAlignmentAssumption(llvm::Value *PtrValue, const Expr *E, 3195 SourceLocation AssumptionLoc, 3196 llvm::Value *Alignment, 3197 llvm::Value *OffsetValue = nullptr); 3198 3199 //===--------------------------------------------------------------------===// 3200 // Statement Emission 3201 //===--------------------------------------------------------------------===// 3202 3203 /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info. 3204 void EmitStopPoint(const Stmt *S); 3205 3206 /// EmitStmt - Emit the code for the statement \arg S. It is legal to call 3207 /// this function even if there is no current insertion point. 3208 /// 3209 /// This function may clear the current insertion point; callers should use 3210 /// EnsureInsertPoint if they wish to subsequently generate code without first 3211 /// calling EmitBlock, EmitBranch, or EmitStmt. 3212 void EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs = None); 3213 3214 /// EmitSimpleStmt - Try to emit a "simple" statement which does not 3215 /// necessarily require an insertion point or debug information; typically 3216 /// because the statement amounts to a jump or a container of other 3217 /// statements. 3218 /// 3219 /// \return True if the statement was handled. 3220 bool EmitSimpleStmt(const Stmt *S, ArrayRef<const Attr *> Attrs); 3221 3222 Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false, 3223 AggValueSlot AVS = AggValueSlot::ignored()); 3224 Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, 3225 bool GetLast = false, 3226 AggValueSlot AVS = 3227 AggValueSlot::ignored()); 3228 3229 /// EmitLabel - Emit the block for the given label. It is legal to call this 3230 /// function even if there is no current insertion point. 3231 void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt. 3232 3233 void EmitLabelStmt(const LabelStmt &S); 3234 void EmitAttributedStmt(const AttributedStmt &S); 3235 void EmitGotoStmt(const GotoStmt &S); 3236 void EmitIndirectGotoStmt(const IndirectGotoStmt &S); 3237 void EmitIfStmt(const IfStmt &S); 3238 3239 void EmitWhileStmt(const WhileStmt &S, 3240 ArrayRef<const Attr *> Attrs = None); 3241 void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None); 3242 void EmitForStmt(const ForStmt &S, 3243 ArrayRef<const Attr *> Attrs = None); 3244 void EmitReturnStmt(const ReturnStmt &S); 3245 void EmitDeclStmt(const DeclStmt &S); 3246 void EmitBreakStmt(const BreakStmt &S); 3247 void EmitContinueStmt(const ContinueStmt &S); 3248 void EmitSwitchStmt(const SwitchStmt &S); 3249 void EmitDefaultStmt(const DefaultStmt &S, ArrayRef<const Attr *> Attrs); 3250 void EmitCaseStmt(const CaseStmt &S, ArrayRef<const Attr *> Attrs); 3251 void EmitCaseStmtRange(const CaseStmt &S, ArrayRef<const Attr *> Attrs); 3252 void EmitAsmStmt(const AsmStmt &S); 3253 3254 void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S); 3255 void EmitObjCAtTryStmt(const ObjCAtTryStmt &S); 3256 void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S); 3257 void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S); 3258 void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S); 3259 3260 void EmitCoroutineBody(const CoroutineBodyStmt &S); 3261 void EmitCoreturnStmt(const CoreturnStmt &S); 3262 RValue EmitCoawaitExpr(const CoawaitExpr &E, 3263 AggValueSlot aggSlot = AggValueSlot::ignored(), 3264 bool ignoreResult = false); 3265 LValue EmitCoawaitLValue(const CoawaitExpr *E); 3266 RValue EmitCoyieldExpr(const CoyieldExpr &E, 3267 AggValueSlot aggSlot = AggValueSlot::ignored(), 3268 bool ignoreResult = false); 3269 LValue EmitCoyieldLValue(const CoyieldExpr *E); 3270 RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID); 3271 3272 void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 3273 void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false); 3274 3275 void EmitCXXTryStmt(const CXXTryStmt &S); 3276 void EmitSEHTryStmt(const SEHTryStmt &S); 3277 void EmitSEHLeaveStmt(const SEHLeaveStmt &S); 3278 void EnterSEHTryStmt(const SEHTryStmt &S); 3279 void ExitSEHTryStmt(const SEHTryStmt &S); 3280 void VolatilizeTryBlocks(llvm::BasicBlock *BB, 3281 llvm::SmallPtrSet<llvm::BasicBlock *, 10> &V); 3282 3283 void pushSEHCleanup(CleanupKind kind, 3284 llvm::Function *FinallyFunc); 3285 void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter, 3286 const Stmt *OutlinedStmt); 3287 3288 llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF, 3289 const SEHExceptStmt &Except); 3290 3291 llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF, 3292 const SEHFinallyStmt &Finally); 3293 3294 void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF, 3295 llvm::Value *ParentFP, 3296 llvm::Value *EntryEBP); 3297 llvm::Value *EmitSEHExceptionCode(); 3298 llvm::Value *EmitSEHExceptionInfo(); 3299 llvm::Value *EmitSEHAbnormalTermination(); 3300 3301 /// Emit simple code for OpenMP directives in Simd-only mode. 3302 void EmitSimpleOMPExecutableDirective(const OMPExecutableDirective &D); 3303 3304 /// Scan the outlined statement for captures from the parent function. For 3305 /// each capture, mark the capture as escaped and emit a call to 3306 /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap. 3307 void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt, 3308 bool IsFilter); 3309 3310 /// Recovers the address of a local in a parent function. ParentVar is the 3311 /// address of the variable used in the immediate parent function. It can 3312 /// either be an alloca or a call to llvm.localrecover if there are nested 3313 /// outlined functions. ParentFP is the frame pointer of the outermost parent 3314 /// frame. 3315 Address recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF, 3316 Address ParentVar, 3317 llvm::Value *ParentFP); 3318 3319 void EmitCXXForRangeStmt(const CXXForRangeStmt &S, 3320 ArrayRef<const Attr *> Attrs = None); 3321 3322 /// Controls insertion of cancellation exit blocks in worksharing constructs. 3323 class OMPCancelStackRAII { 3324 CodeGenFunction &CGF; 3325 3326 public: 3327 OMPCancelStackRAII(CodeGenFunction &CGF, OpenMPDirectiveKind Kind, 3328 bool HasCancel) 3329 : CGF(CGF) { 3330 CGF.OMPCancelStack.enter(CGF, Kind, HasCancel); 3331 } 3332 ~OMPCancelStackRAII() { CGF.OMPCancelStack.exit(CGF); } 3333 }; 3334 3335 /// Returns calculated size of the specified type. 3336 llvm::Value *getTypeSize(QualType Ty); 3337 LValue InitCapturedStruct(const CapturedStmt &S); 3338 llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K); 3339 llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S); 3340 Address GenerateCapturedStmtArgument(const CapturedStmt &S); 3341 llvm::Function *GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 3342 SourceLocation Loc); 3343 void GenerateOpenMPCapturedVars(const CapturedStmt &S, 3344 SmallVectorImpl<llvm::Value *> &CapturedVars); 3345 void emitOMPSimpleStore(LValue LVal, RValue RVal, QualType RValTy, 3346 SourceLocation Loc); 3347 /// Perform element by element copying of arrays with type \a 3348 /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure 3349 /// generated by \a CopyGen. 3350 /// 3351 /// \param DestAddr Address of the destination array. 3352 /// \param SrcAddr Address of the source array. 3353 /// \param OriginalType Type of destination and source arrays. 3354 /// \param CopyGen Copying procedure that copies value of single array element 3355 /// to another single array element. 3356 void EmitOMPAggregateAssign( 3357 Address DestAddr, Address SrcAddr, QualType OriginalType, 3358 const llvm::function_ref<void(Address, Address)> CopyGen); 3359 /// Emit proper copying of data from one variable to another. 3360 /// 3361 /// \param OriginalType Original type of the copied variables. 3362 /// \param DestAddr Destination address. 3363 /// \param SrcAddr Source address. 3364 /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has 3365 /// type of the base array element). 3366 /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of 3367 /// the base array element). 3368 /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a 3369 /// DestVD. 3370 void EmitOMPCopy(QualType OriginalType, 3371 Address DestAddr, Address SrcAddr, 3372 const VarDecl *DestVD, const VarDecl *SrcVD, 3373 const Expr *Copy); 3374 /// Emit atomic update code for constructs: \a X = \a X \a BO \a E or 3375 /// \a X = \a E \a BO \a E. 3376 /// 3377 /// \param X Value to be updated. 3378 /// \param E Update value. 3379 /// \param BO Binary operation for update operation. 3380 /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update 3381 /// expression, false otherwise. 3382 /// \param AO Atomic ordering of the generated atomic instructions. 3383 /// \param CommonGen Code generator for complex expressions that cannot be 3384 /// expressed through atomicrmw instruction. 3385 /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was 3386 /// generated, <false, RValue::get(nullptr)> otherwise. 3387 std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr( 3388 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 3389 llvm::AtomicOrdering AO, SourceLocation Loc, 3390 const llvm::function_ref<RValue(RValue)> CommonGen); 3391 bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 3392 OMPPrivateScope &PrivateScope); 3393 void EmitOMPPrivateClause(const OMPExecutableDirective &D, 3394 OMPPrivateScope &PrivateScope); 3395 void EmitOMPUseDevicePtrClause( 3396 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, 3397 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3398 void EmitOMPUseDeviceAddrClause( 3399 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, 3400 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap); 3401 /// Emit code for copyin clause in \a D directive. The next code is 3402 /// generated at the start of outlined functions for directives: 3403 /// \code 3404 /// threadprivate_var1 = master_threadprivate_var1; 3405 /// operator=(threadprivate_var2, master_threadprivate_var2); 3406 /// ... 3407 /// __kmpc_barrier(&loc, global_tid); 3408 /// \endcode 3409 /// 3410 /// \param D OpenMP directive possibly with 'copyin' clause(s). 3411 /// \returns true if at least one copyin variable is found, false otherwise. 3412 bool EmitOMPCopyinClause(const OMPExecutableDirective &D); 3413 /// Emit initial code for lastprivate variables. If some variable is 3414 /// not also firstprivate, then the default initialization is used. Otherwise 3415 /// initialization of this variable is performed by EmitOMPFirstprivateClause 3416 /// method. 3417 /// 3418 /// \param D Directive that may have 'lastprivate' directives. 3419 /// \param PrivateScope Private scope for capturing lastprivate variables for 3420 /// proper codegen in internal captured statement. 3421 /// 3422 /// \returns true if there is at least one lastprivate variable, false 3423 /// otherwise. 3424 bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D, 3425 OMPPrivateScope &PrivateScope); 3426 /// Emit final copying of lastprivate values to original variables at 3427 /// the end of the worksharing or simd directive. 3428 /// 3429 /// \param D Directive that has at least one 'lastprivate' directives. 3430 /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if 3431 /// it is the last iteration of the loop code in associated directive, or to 3432 /// 'i1 false' otherwise. If this item is nullptr, no final check is required. 3433 void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D, 3434 bool NoFinals, 3435 llvm::Value *IsLastIterCond = nullptr); 3436 /// Emit initial code for linear clauses. 3437 void EmitOMPLinearClause(const OMPLoopDirective &D, 3438 CodeGenFunction::OMPPrivateScope &PrivateScope); 3439 /// Emit final code for linear clauses. 3440 /// \param CondGen Optional conditional code for final part of codegen for 3441 /// linear clause. 3442 void EmitOMPLinearClauseFinal( 3443 const OMPLoopDirective &D, 3444 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3445 /// Emit initial code for reduction variables. Creates reduction copies 3446 /// and initializes them with the values according to OpenMP standard. 3447 /// 3448 /// \param D Directive (possibly) with the 'reduction' clause. 3449 /// \param PrivateScope Private scope for capturing reduction variables for 3450 /// proper codegen in internal captured statement. 3451 /// 3452 void EmitOMPReductionClauseInit(const OMPExecutableDirective &D, 3453 OMPPrivateScope &PrivateScope, 3454 bool ForInscan = false); 3455 /// Emit final update of reduction values to original variables at 3456 /// the end of the directive. 3457 /// 3458 /// \param D Directive that has at least one 'reduction' directives. 3459 /// \param ReductionKind The kind of reduction to perform. 3460 void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D, 3461 const OpenMPDirectiveKind ReductionKind); 3462 /// Emit initial code for linear variables. Creates private copies 3463 /// and initializes them with the values according to OpenMP standard. 3464 /// 3465 /// \param D Directive (possibly) with the 'linear' clause. 3466 /// \return true if at least one linear variable is found that should be 3467 /// initialized with the value of the original variable, false otherwise. 3468 bool EmitOMPLinearClauseInit(const OMPLoopDirective &D); 3469 3470 typedef const llvm::function_ref<void(CodeGenFunction & /*CGF*/, 3471 llvm::Function * /*OutlinedFn*/, 3472 const OMPTaskDataTy & /*Data*/)> 3473 TaskGenTy; 3474 void EmitOMPTaskBasedDirective(const OMPExecutableDirective &S, 3475 const OpenMPDirectiveKind CapturedRegion, 3476 const RegionCodeGenTy &BodyGen, 3477 const TaskGenTy &TaskGen, OMPTaskDataTy &Data); 3478 struct OMPTargetDataInfo { 3479 Address BasePointersArray = Address::invalid(); 3480 Address PointersArray = Address::invalid(); 3481 Address SizesArray = Address::invalid(); 3482 Address MappersArray = Address::invalid(); 3483 unsigned NumberOfTargetItems = 0; 3484 explicit OMPTargetDataInfo() = default; 3485 OMPTargetDataInfo(Address BasePointersArray, Address PointersArray, 3486 Address SizesArray, Address MappersArray, 3487 unsigned NumberOfTargetItems) 3488 : BasePointersArray(BasePointersArray), PointersArray(PointersArray), 3489 SizesArray(SizesArray), MappersArray(MappersArray), 3490 NumberOfTargetItems(NumberOfTargetItems) {} 3491 }; 3492 void EmitOMPTargetTaskBasedDirective(const OMPExecutableDirective &S, 3493 const RegionCodeGenTy &BodyGen, 3494 OMPTargetDataInfo &InputInfo); 3495 3496 void EmitOMPMetaDirective(const OMPMetaDirective &S); 3497 void EmitOMPParallelDirective(const OMPParallelDirective &S); 3498 void EmitOMPSimdDirective(const OMPSimdDirective &S); 3499 void EmitOMPTileDirective(const OMPTileDirective &S); 3500 void EmitOMPUnrollDirective(const OMPUnrollDirective &S); 3501 void EmitOMPForDirective(const OMPForDirective &S); 3502 void EmitOMPForSimdDirective(const OMPForSimdDirective &S); 3503 void EmitOMPSectionsDirective(const OMPSectionsDirective &S); 3504 void EmitOMPSectionDirective(const OMPSectionDirective &S); 3505 void EmitOMPSingleDirective(const OMPSingleDirective &S); 3506 void EmitOMPMasterDirective(const OMPMasterDirective &S); 3507 void EmitOMPMaskedDirective(const OMPMaskedDirective &S); 3508 void EmitOMPCriticalDirective(const OMPCriticalDirective &S); 3509 void EmitOMPParallelForDirective(const OMPParallelForDirective &S); 3510 void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S); 3511 void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S); 3512 void EmitOMPParallelMasterDirective(const OMPParallelMasterDirective &S); 3513 void EmitOMPTaskDirective(const OMPTaskDirective &S); 3514 void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S); 3515 void EmitOMPBarrierDirective(const OMPBarrierDirective &S); 3516 void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S); 3517 void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S); 3518 void EmitOMPFlushDirective(const OMPFlushDirective &S); 3519 void EmitOMPDepobjDirective(const OMPDepobjDirective &S); 3520 void EmitOMPScanDirective(const OMPScanDirective &S); 3521 void EmitOMPOrderedDirective(const OMPOrderedDirective &S); 3522 void EmitOMPAtomicDirective(const OMPAtomicDirective &S); 3523 void EmitOMPTargetDirective(const OMPTargetDirective &S); 3524 void EmitOMPTargetDataDirective(const OMPTargetDataDirective &S); 3525 void EmitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective &S); 3526 void EmitOMPTargetExitDataDirective(const OMPTargetExitDataDirective &S); 3527 void EmitOMPTargetUpdateDirective(const OMPTargetUpdateDirective &S); 3528 void EmitOMPTargetParallelDirective(const OMPTargetParallelDirective &S); 3529 void 3530 EmitOMPTargetParallelForDirective(const OMPTargetParallelForDirective &S); 3531 void EmitOMPTeamsDirective(const OMPTeamsDirective &S); 3532 void 3533 EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S); 3534 void EmitOMPCancelDirective(const OMPCancelDirective &S); 3535 void EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S); 3536 void EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S); 3537 void EmitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective &S); 3538 void EmitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective &S); 3539 void 3540 EmitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective &S); 3541 void EmitOMPParallelMasterTaskLoopDirective( 3542 const OMPParallelMasterTaskLoopDirective &S); 3543 void EmitOMPParallelMasterTaskLoopSimdDirective( 3544 const OMPParallelMasterTaskLoopSimdDirective &S); 3545 void EmitOMPDistributeDirective(const OMPDistributeDirective &S); 3546 void EmitOMPDistributeParallelForDirective( 3547 const OMPDistributeParallelForDirective &S); 3548 void EmitOMPDistributeParallelForSimdDirective( 3549 const OMPDistributeParallelForSimdDirective &S); 3550 void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S); 3551 void EmitOMPTargetParallelForSimdDirective( 3552 const OMPTargetParallelForSimdDirective &S); 3553 void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S); 3554 void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S); 3555 void 3556 EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S); 3557 void EmitOMPTeamsDistributeParallelForSimdDirective( 3558 const OMPTeamsDistributeParallelForSimdDirective &S); 3559 void EmitOMPTeamsDistributeParallelForDirective( 3560 const OMPTeamsDistributeParallelForDirective &S); 3561 void EmitOMPTargetTeamsDirective(const OMPTargetTeamsDirective &S); 3562 void EmitOMPTargetTeamsDistributeDirective( 3563 const OMPTargetTeamsDistributeDirective &S); 3564 void EmitOMPTargetTeamsDistributeParallelForDirective( 3565 const OMPTargetTeamsDistributeParallelForDirective &S); 3566 void EmitOMPTargetTeamsDistributeParallelForSimdDirective( 3567 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3568 void EmitOMPTargetTeamsDistributeSimdDirective( 3569 const OMPTargetTeamsDistributeSimdDirective &S); 3570 void EmitOMPGenericLoopDirective(const OMPGenericLoopDirective &S); 3571 3572 /// Emit device code for the target directive. 3573 static void EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 3574 StringRef ParentName, 3575 const OMPTargetDirective &S); 3576 static void 3577 EmitOMPTargetParallelDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 3578 const OMPTargetParallelDirective &S); 3579 /// Emit device code for the target parallel for directive. 3580 static void EmitOMPTargetParallelForDeviceFunction( 3581 CodeGenModule &CGM, StringRef ParentName, 3582 const OMPTargetParallelForDirective &S); 3583 /// Emit device code for the target parallel for simd directive. 3584 static void EmitOMPTargetParallelForSimdDeviceFunction( 3585 CodeGenModule &CGM, StringRef ParentName, 3586 const OMPTargetParallelForSimdDirective &S); 3587 /// Emit device code for the target teams directive. 3588 static void 3589 EmitOMPTargetTeamsDeviceFunction(CodeGenModule &CGM, StringRef ParentName, 3590 const OMPTargetTeamsDirective &S); 3591 /// Emit device code for the target teams distribute directive. 3592 static void EmitOMPTargetTeamsDistributeDeviceFunction( 3593 CodeGenModule &CGM, StringRef ParentName, 3594 const OMPTargetTeamsDistributeDirective &S); 3595 /// Emit device code for the target teams distribute simd directive. 3596 static void EmitOMPTargetTeamsDistributeSimdDeviceFunction( 3597 CodeGenModule &CGM, StringRef ParentName, 3598 const OMPTargetTeamsDistributeSimdDirective &S); 3599 /// Emit device code for the target simd directive. 3600 static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM, 3601 StringRef ParentName, 3602 const OMPTargetSimdDirective &S); 3603 /// Emit device code for the target teams distribute parallel for simd 3604 /// directive. 3605 static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 3606 CodeGenModule &CGM, StringRef ParentName, 3607 const OMPTargetTeamsDistributeParallelForSimdDirective &S); 3608 3609 static void EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 3610 CodeGenModule &CGM, StringRef ParentName, 3611 const OMPTargetTeamsDistributeParallelForDirective &S); 3612 3613 /// Emit the Stmt \p S and return its topmost canonical loop, if any. 3614 /// TODO: The \p Depth paramter is not yet implemented and must be 1. In the 3615 /// future it is meant to be the number of loops expected in the loop nests 3616 /// (usually specified by the "collapse" clause) that are collapsed to a 3617 /// single loop by this function. 3618 llvm::CanonicalLoopInfo *EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, 3619 int Depth); 3620 3621 /// Emit an OMPCanonicalLoop using the OpenMPIRBuilder. 3622 void EmitOMPCanonicalLoop(const OMPCanonicalLoop *S); 3623 3624 /// Emit inner loop of the worksharing/simd construct. 3625 /// 3626 /// \param S Directive, for which the inner loop must be emitted. 3627 /// \param RequiresCleanup true, if directive has some associated private 3628 /// variables. 3629 /// \param LoopCond Bollean condition for loop continuation. 3630 /// \param IncExpr Increment expression for loop control variable. 3631 /// \param BodyGen Generator for the inner body of the inner loop. 3632 /// \param PostIncGen Genrator for post-increment code (required for ordered 3633 /// loop directvies). 3634 void EmitOMPInnerLoop( 3635 const OMPExecutableDirective &S, bool RequiresCleanup, 3636 const Expr *LoopCond, const Expr *IncExpr, 3637 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 3638 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen); 3639 3640 JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind); 3641 /// Emit initial code for loop counters of loop-based directives. 3642 void EmitOMPPrivateLoopCounters(const OMPLoopDirective &S, 3643 OMPPrivateScope &LoopScope); 3644 3645 /// Helper for the OpenMP loop directives. 3646 void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit); 3647 3648 /// Emit code for the worksharing loop-based directive. 3649 /// \return true, if this construct has any lastprivate clause, false - 3650 /// otherwise. 3651 bool EmitOMPWorksharingLoop(const OMPLoopDirective &S, Expr *EUB, 3652 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 3653 const CodeGenDispatchBoundsTy &CGDispatchBounds); 3654 3655 /// Emit code for the distribute loop-based directive. 3656 void EmitOMPDistributeLoop(const OMPLoopDirective &S, 3657 const CodeGenLoopTy &CodeGenLoop, Expr *IncExpr); 3658 3659 /// Helpers for the OpenMP loop directives. 3660 void EmitOMPSimdInit(const OMPLoopDirective &D); 3661 void EmitOMPSimdFinal( 3662 const OMPLoopDirective &D, 3663 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen); 3664 3665 /// Emits the lvalue for the expression with possibly captured variable. 3666 LValue EmitOMPSharedLValue(const Expr *E); 3667 3668 private: 3669 /// Helpers for blocks. 3670 llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info); 3671 3672 /// struct with the values to be passed to the OpenMP loop-related functions 3673 struct OMPLoopArguments { 3674 /// loop lower bound 3675 Address LB = Address::invalid(); 3676 /// loop upper bound 3677 Address UB = Address::invalid(); 3678 /// loop stride 3679 Address ST = Address::invalid(); 3680 /// isLastIteration argument for runtime functions 3681 Address IL = Address::invalid(); 3682 /// Chunk value generated by sema 3683 llvm::Value *Chunk = nullptr; 3684 /// EnsureUpperBound 3685 Expr *EUB = nullptr; 3686 /// IncrementExpression 3687 Expr *IncExpr = nullptr; 3688 /// Loop initialization 3689 Expr *Init = nullptr; 3690 /// Loop exit condition 3691 Expr *Cond = nullptr; 3692 /// Update of LB after a whole chunk has been executed 3693 Expr *NextLB = nullptr; 3694 /// Update of UB after a whole chunk has been executed 3695 Expr *NextUB = nullptr; 3696 OMPLoopArguments() = default; 3697 OMPLoopArguments(Address LB, Address UB, Address ST, Address IL, 3698 llvm::Value *Chunk = nullptr, Expr *EUB = nullptr, 3699 Expr *IncExpr = nullptr, Expr *Init = nullptr, 3700 Expr *Cond = nullptr, Expr *NextLB = nullptr, 3701 Expr *NextUB = nullptr) 3702 : LB(LB), UB(UB), ST(ST), IL(IL), Chunk(Chunk), EUB(EUB), 3703 IncExpr(IncExpr), Init(Init), Cond(Cond), NextLB(NextLB), 3704 NextUB(NextUB) {} 3705 }; 3706 void EmitOMPOuterLoop(bool DynamicOrOrdered, bool IsMonotonic, 3707 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, 3708 const OMPLoopArguments &LoopArgs, 3709 const CodeGenLoopTy &CodeGenLoop, 3710 const CodeGenOrderedTy &CodeGenOrdered); 3711 void EmitOMPForOuterLoop(const OpenMPScheduleTy &ScheduleKind, 3712 bool IsMonotonic, const OMPLoopDirective &S, 3713 OMPPrivateScope &LoopScope, bool Ordered, 3714 const OMPLoopArguments &LoopArgs, 3715 const CodeGenDispatchBoundsTy &CGDispatchBounds); 3716 void EmitOMPDistributeOuterLoop(OpenMPDistScheduleClauseKind ScheduleKind, 3717 const OMPLoopDirective &S, 3718 OMPPrivateScope &LoopScope, 3719 const OMPLoopArguments &LoopArgs, 3720 const CodeGenLoopTy &CodeGenLoopContent); 3721 /// Emit code for sections directive. 3722 void EmitSections(const OMPExecutableDirective &S); 3723 3724 public: 3725 3726 //===--------------------------------------------------------------------===// 3727 // LValue Expression Emission 3728 //===--------------------------------------------------------------------===// 3729 3730 /// Create a check that a scalar RValue is non-null. 3731 llvm::Value *EmitNonNullRValueCheck(RValue RV, QualType T); 3732 3733 /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type. 3734 RValue GetUndefRValue(QualType Ty); 3735 3736 /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E 3737 /// and issue an ErrorUnsupported style diagnostic (using the 3738 /// provided Name). 3739 RValue EmitUnsupportedRValue(const Expr *E, 3740 const char *Name); 3741 3742 /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue 3743 /// an ErrorUnsupported style diagnostic (using the provided Name). 3744 LValue EmitUnsupportedLValue(const Expr *E, 3745 const char *Name); 3746 3747 /// EmitLValue - Emit code to compute a designator that specifies the location 3748 /// of the expression. 3749 /// 3750 /// This can return one of two things: a simple address or a bitfield 3751 /// reference. In either case, the LLVM Value* in the LValue structure is 3752 /// guaranteed to be an LLVM pointer type. 3753 /// 3754 /// If this returns a bitfield reference, nothing about the pointee type of 3755 /// the LLVM value is known: For example, it may not be a pointer to an 3756 /// integer. 3757 /// 3758 /// If this returns a normal address, and if the lvalue's C type is fixed 3759 /// size, this method guarantees that the returned pointer type will point to 3760 /// an LLVM type of the same size of the lvalue's type. If the lvalue has a 3761 /// variable length type, this is not possible. 3762 /// 3763 LValue EmitLValue(const Expr *E); 3764 3765 /// Same as EmitLValue but additionally we generate checking code to 3766 /// guard against undefined behavior. This is only suitable when we know 3767 /// that the address will be used to access the object. 3768 LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK); 3769 3770 RValue convertTempToRValue(Address addr, QualType type, 3771 SourceLocation Loc); 3772 3773 void EmitAtomicInit(Expr *E, LValue lvalue); 3774 3775 bool LValueIsSuitableForInlineAtomic(LValue Src); 3776 3777 RValue EmitAtomicLoad(LValue LV, SourceLocation SL, 3778 AggValueSlot Slot = AggValueSlot::ignored()); 3779 3780 RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc, 3781 llvm::AtomicOrdering AO, bool IsVolatile = false, 3782 AggValueSlot slot = AggValueSlot::ignored()); 3783 3784 void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit); 3785 3786 void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO, 3787 bool IsVolatile, bool isInit); 3788 3789 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange( 3790 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, 3791 llvm::AtomicOrdering Success = 3792 llvm::AtomicOrdering::SequentiallyConsistent, 3793 llvm::AtomicOrdering Failure = 3794 llvm::AtomicOrdering::SequentiallyConsistent, 3795 bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored()); 3796 3797 void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, 3798 const llvm::function_ref<RValue(RValue)> &UpdateOp, 3799 bool IsVolatile); 3800 3801 /// EmitToMemory - Change a scalar value from its value 3802 /// representation to its in-memory representation. 3803 llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty); 3804 3805 /// EmitFromMemory - Change a scalar value from its memory 3806 /// representation to its value representation. 3807 llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty); 3808 3809 /// Check if the scalar \p Value is within the valid range for the given 3810 /// type \p Ty. 3811 /// 3812 /// Returns true if a check is needed (even if the range is unknown). 3813 bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, 3814 SourceLocation Loc); 3815 3816 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3817 /// care to appropriately convert from the memory representation to 3818 /// the LLVM value representation. 3819 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3820 SourceLocation Loc, 3821 AlignmentSource Source = AlignmentSource::Type, 3822 bool isNontemporal = false) { 3823 return EmitLoadOfScalar(Addr, Volatile, Ty, Loc, LValueBaseInfo(Source), 3824 CGM.getTBAAAccessInfo(Ty), isNontemporal); 3825 } 3826 3827 llvm::Value *EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, 3828 SourceLocation Loc, LValueBaseInfo BaseInfo, 3829 TBAAAccessInfo TBAAInfo, 3830 bool isNontemporal = false); 3831 3832 /// EmitLoadOfScalar - Load a scalar value from an address, taking 3833 /// care to appropriately convert from the memory representation to 3834 /// the LLVM value representation. The l-value must be a simple 3835 /// l-value. 3836 llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc); 3837 3838 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3839 /// care to appropriately convert from the memory representation to 3840 /// the LLVM value representation. 3841 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3842 bool Volatile, QualType Ty, 3843 AlignmentSource Source = AlignmentSource::Type, 3844 bool isInit = false, bool isNontemporal = false) { 3845 EmitStoreOfScalar(Value, Addr, Volatile, Ty, LValueBaseInfo(Source), 3846 CGM.getTBAAAccessInfo(Ty), isInit, isNontemporal); 3847 } 3848 3849 void EmitStoreOfScalar(llvm::Value *Value, Address Addr, 3850 bool Volatile, QualType Ty, 3851 LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo, 3852 bool isInit = false, bool isNontemporal = false); 3853 3854 /// EmitStoreOfScalar - Store a scalar value to an address, taking 3855 /// care to appropriately convert from the memory representation to 3856 /// the LLVM value representation. The l-value must be a simple 3857 /// l-value. The isInit flag indicates whether this is an initialization. 3858 /// If so, atomic qualifiers are ignored and the store is always non-atomic. 3859 void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false); 3860 3861 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, 3862 /// this method emits the address of the lvalue, then loads the result as an 3863 /// rvalue, returning the rvalue. 3864 RValue EmitLoadOfLValue(LValue V, SourceLocation Loc); 3865 RValue EmitLoadOfExtVectorElementLValue(LValue V); 3866 RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc); 3867 RValue EmitLoadOfGlobalRegLValue(LValue LV); 3868 3869 /// EmitStoreThroughLValue - Store the specified rvalue into the specified 3870 /// lvalue, where both are guaranteed to the have the same type, and that type 3871 /// is 'Ty'. 3872 void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false); 3873 void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst); 3874 void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst); 3875 3876 /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints 3877 /// as EmitStoreThroughLValue. 3878 /// 3879 /// \param Result [out] - If non-null, this will be set to a Value* for the 3880 /// bit-field contents after the store, appropriate for use as the result of 3881 /// an assignment to the bit-field. 3882 void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, 3883 llvm::Value **Result=nullptr); 3884 3885 /// Emit an l-value for an assignment (simple or compound) of complex type. 3886 LValue EmitComplexAssignmentLValue(const BinaryOperator *E); 3887 LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E); 3888 LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, 3889 llvm::Value *&Result); 3890 3891 // Note: only available for agg return types 3892 LValue EmitBinaryOperatorLValue(const BinaryOperator *E); 3893 LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E); 3894 // Note: only available for agg return types 3895 LValue EmitCallExprLValue(const CallExpr *E); 3896 // Note: only available for agg return types 3897 LValue EmitVAArgExprLValue(const VAArgExpr *E); 3898 LValue EmitDeclRefLValue(const DeclRefExpr *E); 3899 LValue EmitStringLiteralLValue(const StringLiteral *E); 3900 LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E); 3901 LValue EmitPredefinedLValue(const PredefinedExpr *E); 3902 LValue EmitUnaryOpLValue(const UnaryOperator *E); 3903 LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, 3904 bool Accessed = false); 3905 LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E); 3906 LValue EmitOMPArraySectionExpr(const OMPArraySectionExpr *E, 3907 bool IsLowerBound = true); 3908 LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E); 3909 LValue EmitMemberExpr(const MemberExpr *E); 3910 LValue EmitObjCIsaExpr(const ObjCIsaExpr *E); 3911 LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E); 3912 LValue EmitInitListLValue(const InitListExpr *E); 3913 LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E); 3914 LValue EmitCastLValue(const CastExpr *E); 3915 LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); 3916 LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e); 3917 3918 Address EmitExtVectorElementLValue(LValue V); 3919 3920 RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc); 3921 3922 Address EmitArrayToPointerDecay(const Expr *Array, 3923 LValueBaseInfo *BaseInfo = nullptr, 3924 TBAAAccessInfo *TBAAInfo = nullptr); 3925 3926 class ConstantEmission { 3927 llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference; 3928 ConstantEmission(llvm::Constant *C, bool isReference) 3929 : ValueAndIsReference(C, isReference) {} 3930 public: 3931 ConstantEmission() {} 3932 static ConstantEmission forReference(llvm::Constant *C) { 3933 return ConstantEmission(C, true); 3934 } 3935 static ConstantEmission forValue(llvm::Constant *C) { 3936 return ConstantEmission(C, false); 3937 } 3938 3939 explicit operator bool() const { 3940 return ValueAndIsReference.getOpaqueValue() != nullptr; 3941 } 3942 3943 bool isReference() const { return ValueAndIsReference.getInt(); } 3944 LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const { 3945 assert(isReference()); 3946 return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(), 3947 refExpr->getType()); 3948 } 3949 3950 llvm::Constant *getValue() const { 3951 assert(!isReference()); 3952 return ValueAndIsReference.getPointer(); 3953 } 3954 }; 3955 3956 ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr); 3957 ConstantEmission tryEmitAsConstant(const MemberExpr *ME); 3958 llvm::Value *emitScalarConstant(const ConstantEmission &Constant, Expr *E); 3959 3960 RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, 3961 AggValueSlot slot = AggValueSlot::ignored()); 3962 LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e); 3963 3964 llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface, 3965 const ObjCIvarDecl *Ivar); 3966 LValue EmitLValueForField(LValue Base, const FieldDecl* Field); 3967 LValue EmitLValueForLambdaField(const FieldDecl *Field); 3968 3969 /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that 3970 /// if the Field is a reference, this will return the address of the reference 3971 /// and not the address of the value stored in the reference. 3972 LValue EmitLValueForFieldInitialization(LValue Base, 3973 const FieldDecl* Field); 3974 3975 LValue EmitLValueForIvar(QualType ObjectTy, 3976 llvm::Value* Base, const ObjCIvarDecl *Ivar, 3977 unsigned CVRQualifiers); 3978 3979 LValue EmitCXXConstructLValue(const CXXConstructExpr *E); 3980 LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E); 3981 LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E); 3982 LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E); 3983 3984 LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E); 3985 LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E); 3986 LValue EmitStmtExprLValue(const StmtExpr *E); 3987 LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E); 3988 LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E); 3989 void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init); 3990 3991 //===--------------------------------------------------------------------===// 3992 // Scalar Expression Emission 3993 //===--------------------------------------------------------------------===// 3994 3995 /// EmitCall - Generate a call of the given function, expecting the given 3996 /// result type, and using the given argument list which specifies both the 3997 /// LLVM arguments and the types they were derived from. 3998 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 3999 ReturnValueSlot ReturnValue, const CallArgList &Args, 4000 llvm::CallBase **callOrInvoke, bool IsMustTail, 4001 SourceLocation Loc); 4002 RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, 4003 ReturnValueSlot ReturnValue, const CallArgList &Args, 4004 llvm::CallBase **callOrInvoke = nullptr, 4005 bool IsMustTail = false) { 4006 return EmitCall(CallInfo, Callee, ReturnValue, Args, callOrInvoke, 4007 IsMustTail, SourceLocation()); 4008 } 4009 RValue EmitCall(QualType FnType, const CGCallee &Callee, const CallExpr *E, 4010 ReturnValueSlot ReturnValue, llvm::Value *Chain = nullptr); 4011 RValue EmitCallExpr(const CallExpr *E, 4012 ReturnValueSlot ReturnValue = ReturnValueSlot()); 4013 RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 4014 CGCallee EmitCallee(const Expr *E); 4015 4016 void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl); 4017 void checkTargetFeatures(SourceLocation Loc, const FunctionDecl *TargetDecl); 4018 4019 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee, 4020 const Twine &name = ""); 4021 llvm::CallInst *EmitRuntimeCall(llvm::FunctionCallee callee, 4022 ArrayRef<llvm::Value *> args, 4023 const Twine &name = ""); 4024 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 4025 const Twine &name = ""); 4026 llvm::CallInst *EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 4027 ArrayRef<llvm::Value *> args, 4028 const Twine &name = ""); 4029 4030 SmallVector<llvm::OperandBundleDef, 1> 4031 getBundlesForFunclet(llvm::Value *Callee); 4032 4033 llvm::CallBase *EmitCallOrInvoke(llvm::FunctionCallee Callee, 4034 ArrayRef<llvm::Value *> Args, 4035 const Twine &Name = ""); 4036 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4037 ArrayRef<llvm::Value *> args, 4038 const Twine &name = ""); 4039 llvm::CallBase *EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4040 const Twine &name = ""); 4041 void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4042 ArrayRef<llvm::Value *> args); 4043 4044 CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 4045 NestedNameSpecifier *Qual, 4046 llvm::Type *Ty); 4047 4048 CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, 4049 CXXDtorType Type, 4050 const CXXRecordDecl *RD); 4051 4052 // Return the copy constructor name with the prefix "__copy_constructor_" 4053 // removed. 4054 static std::string getNonTrivialCopyConstructorStr(QualType QT, 4055 CharUnits Alignment, 4056 bool IsVolatile, 4057 ASTContext &Ctx); 4058 4059 // Return the destructor name with the prefix "__destructor_" removed. 4060 static std::string getNonTrivialDestructorStr(QualType QT, 4061 CharUnits Alignment, 4062 bool IsVolatile, 4063 ASTContext &Ctx); 4064 4065 // These functions emit calls to the special functions of non-trivial C 4066 // structs. 4067 void defaultInitNonTrivialCStructVar(LValue Dst); 4068 void callCStructDefaultConstructor(LValue Dst); 4069 void callCStructDestructor(LValue Dst); 4070 void callCStructCopyConstructor(LValue Dst, LValue Src); 4071 void callCStructMoveConstructor(LValue Dst, LValue Src); 4072 void callCStructCopyAssignmentOperator(LValue Dst, LValue Src); 4073 void callCStructMoveAssignmentOperator(LValue Dst, LValue Src); 4074 4075 RValue 4076 EmitCXXMemberOrOperatorCall(const CXXMethodDecl *Method, 4077 const CGCallee &Callee, 4078 ReturnValueSlot ReturnValue, llvm::Value *This, 4079 llvm::Value *ImplicitParam, 4080 QualType ImplicitParamTy, const CallExpr *E, 4081 CallArgList *RtlArgs); 4082 RValue EmitCXXDestructorCall(GlobalDecl Dtor, const CGCallee &Callee, 4083 llvm::Value *This, QualType ThisTy, 4084 llvm::Value *ImplicitParam, 4085 QualType ImplicitParamTy, const CallExpr *E); 4086 RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, 4087 ReturnValueSlot ReturnValue); 4088 RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE, 4089 const CXXMethodDecl *MD, 4090 ReturnValueSlot ReturnValue, 4091 bool HasQualifier, 4092 NestedNameSpecifier *Qualifier, 4093 bool IsArrow, const Expr *Base); 4094 // Compute the object pointer. 4095 Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 4096 llvm::Value *memberPtr, 4097 const MemberPointerType *memberPtrType, 4098 LValueBaseInfo *BaseInfo = nullptr, 4099 TBAAAccessInfo *TBAAInfo = nullptr); 4100 RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 4101 ReturnValueSlot ReturnValue); 4102 4103 RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 4104 const CXXMethodDecl *MD, 4105 ReturnValueSlot ReturnValue); 4106 RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E); 4107 4108 RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 4109 ReturnValueSlot ReturnValue); 4110 4111 RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E); 4112 RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E); 4113 RValue EmitOpenMPDevicePrintfCallExpr(const CallExpr *E); 4114 4115 RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, 4116 const CallExpr *E, ReturnValueSlot ReturnValue); 4117 4118 RValue emitRotate(const CallExpr *E, bool IsRotateRight); 4119 4120 /// Emit IR for __builtin_os_log_format. 4121 RValue emitBuiltinOSLogFormat(const CallExpr &E); 4122 4123 /// Emit IR for __builtin_is_aligned. 4124 RValue EmitBuiltinIsAligned(const CallExpr *E); 4125 /// Emit IR for __builtin_align_up/__builtin_align_down. 4126 RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp); 4127 4128 llvm::Function *generateBuiltinOSLogHelperFunction( 4129 const analyze_os_log::OSLogBufferLayout &Layout, 4130 CharUnits BufferAlignment); 4131 4132 RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue); 4133 4134 /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call 4135 /// is unhandled by the current target. 4136 llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4137 ReturnValueSlot ReturnValue); 4138 4139 llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty, 4140 const llvm::CmpInst::Predicate Fp, 4141 const llvm::CmpInst::Predicate Ip, 4142 const llvm::Twine &Name = ""); 4143 llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4144 ReturnValueSlot ReturnValue, 4145 llvm::Triple::ArchType Arch); 4146 llvm::Value *EmitARMMVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4147 ReturnValueSlot ReturnValue, 4148 llvm::Triple::ArchType Arch); 4149 llvm::Value *EmitARMCDEBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4150 ReturnValueSlot ReturnValue, 4151 llvm::Triple::ArchType Arch); 4152 llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy, 4153 QualType RTy); 4154 llvm::Value *EmitCMSEClearRecord(llvm::Value *V, llvm::ArrayType *ATy, 4155 QualType RTy); 4156 4157 llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID, 4158 unsigned LLVMIntrinsic, 4159 unsigned AltLLVMIntrinsic, 4160 const char *NameHint, 4161 unsigned Modifier, 4162 const CallExpr *E, 4163 SmallVectorImpl<llvm::Value *> &Ops, 4164 Address PtrOp0, Address PtrOp1, 4165 llvm::Triple::ArchType Arch); 4166 4167 llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID, 4168 unsigned Modifier, llvm::Type *ArgTy, 4169 const CallExpr *E); 4170 llvm::Value *EmitNeonCall(llvm::Function *F, 4171 SmallVectorImpl<llvm::Value*> &O, 4172 const char *name, 4173 unsigned shift = 0, bool rightshift = false); 4174 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx, 4175 const llvm::ElementCount &Count); 4176 llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx); 4177 llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty, 4178 bool negateForRightShift); 4179 llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt, 4180 llvm::Type *Ty, bool usgn, const char *name); 4181 llvm::Value *vectorWrapScalar16(llvm::Value *Op); 4182 /// SVEBuiltinMemEltTy - Returns the memory element type for this memory 4183 /// access builtin. Only required if it can't be inferred from the base 4184 /// pointer operand. 4185 llvm::Type *SVEBuiltinMemEltTy(const SVETypeFlags &TypeFlags); 4186 4187 SmallVector<llvm::Type *, 2> 4188 getSVEOverloadTypes(const SVETypeFlags &TypeFlags, llvm::Type *ReturnType, 4189 ArrayRef<llvm::Value *> Ops); 4190 llvm::Type *getEltType(const SVETypeFlags &TypeFlags); 4191 llvm::ScalableVectorType *getSVEType(const SVETypeFlags &TypeFlags); 4192 llvm::ScalableVectorType *getSVEPredType(const SVETypeFlags &TypeFlags); 4193 llvm::Value *EmitSVEAllTruePred(const SVETypeFlags &TypeFlags); 4194 llvm::Value *EmitSVEDupX(llvm::Value *Scalar); 4195 llvm::Value *EmitSVEDupX(llvm::Value *Scalar, llvm::Type *Ty); 4196 llvm::Value *EmitSVEReinterpret(llvm::Value *Val, llvm::Type *Ty); 4197 llvm::Value *EmitSVEPMull(const SVETypeFlags &TypeFlags, 4198 llvm::SmallVectorImpl<llvm::Value *> &Ops, 4199 unsigned BuiltinID); 4200 llvm::Value *EmitSVEMovl(const SVETypeFlags &TypeFlags, 4201 llvm::ArrayRef<llvm::Value *> Ops, 4202 unsigned BuiltinID); 4203 llvm::Value *EmitSVEPredicateCast(llvm::Value *Pred, 4204 llvm::ScalableVectorType *VTy); 4205 llvm::Value *EmitSVEGatherLoad(const SVETypeFlags &TypeFlags, 4206 llvm::SmallVectorImpl<llvm::Value *> &Ops, 4207 unsigned IntID); 4208 llvm::Value *EmitSVEScatterStore(const SVETypeFlags &TypeFlags, 4209 llvm::SmallVectorImpl<llvm::Value *> &Ops, 4210 unsigned IntID); 4211 llvm::Value *EmitSVEMaskedLoad(const CallExpr *, llvm::Type *ReturnTy, 4212 SmallVectorImpl<llvm::Value *> &Ops, 4213 unsigned BuiltinID, bool IsZExtReturn); 4214 llvm::Value *EmitSVEMaskedStore(const CallExpr *, 4215 SmallVectorImpl<llvm::Value *> &Ops, 4216 unsigned BuiltinID); 4217 llvm::Value *EmitSVEPrefetchLoad(const SVETypeFlags &TypeFlags, 4218 SmallVectorImpl<llvm::Value *> &Ops, 4219 unsigned BuiltinID); 4220 llvm::Value *EmitSVEGatherPrefetch(const SVETypeFlags &TypeFlags, 4221 SmallVectorImpl<llvm::Value *> &Ops, 4222 unsigned IntID); 4223 llvm::Value *EmitSVEStructLoad(const SVETypeFlags &TypeFlags, 4224 SmallVectorImpl<llvm::Value *> &Ops, 4225 unsigned IntID); 4226 llvm::Value *EmitSVEStructStore(const SVETypeFlags &TypeFlags, 4227 SmallVectorImpl<llvm::Value *> &Ops, 4228 unsigned IntID); 4229 llvm::Value *EmitAArch64SVEBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4230 4231 llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4232 llvm::Triple::ArchType Arch); 4233 llvm::Value *EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4234 4235 llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops); 4236 llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4237 llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4238 llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4239 llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4240 llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4241 llvm::Value *EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, 4242 const CallExpr *E); 4243 llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E); 4244 llvm::Value *EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E, 4245 ReturnValueSlot ReturnValue); 4246 bool ProcessOrderScopeAMDGCN(llvm::Value *Order, llvm::Value *Scope, 4247 llvm::AtomicOrdering &AO, 4248 llvm::SyncScope::ID &SSID); 4249 4250 enum class MSVCIntrin; 4251 llvm::Value *EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E); 4252 4253 llvm::Value *EmitBuiltinAvailable(const VersionTuple &Version); 4254 4255 llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E); 4256 llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E); 4257 llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E); 4258 llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E); 4259 llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E); 4260 llvm::Value *EmitObjCCollectionLiteral(const Expr *E, 4261 const ObjCMethodDecl *MethodWithObjects); 4262 llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E); 4263 RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, 4264 ReturnValueSlot Return = ReturnValueSlot()); 4265 4266 /// Retrieves the default cleanup kind for an ARC cleanup. 4267 /// Except under -fobjc-arc-eh, ARC cleanups are normal-only. 4268 CleanupKind getARCCleanupKind() { 4269 return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions 4270 ? NormalAndEHCleanup : NormalCleanup; 4271 } 4272 4273 // ARC primitives. 4274 void EmitARCInitWeak(Address addr, llvm::Value *value); 4275 void EmitARCDestroyWeak(Address addr); 4276 llvm::Value *EmitARCLoadWeak(Address addr); 4277 llvm::Value *EmitARCLoadWeakRetained(Address addr); 4278 llvm::Value *EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored); 4279 void emitARCCopyAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr); 4280 void emitARCMoveAssignWeak(QualType Ty, Address DstAddr, Address SrcAddr); 4281 void EmitARCCopyWeak(Address dst, Address src); 4282 void EmitARCMoveWeak(Address dst, Address src); 4283 llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value); 4284 llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value); 4285 llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value, 4286 bool resultIgnored); 4287 llvm::Value *EmitARCStoreStrongCall(Address addr, llvm::Value *value, 4288 bool resultIgnored); 4289 llvm::Value *EmitARCRetain(QualType type, llvm::Value *value); 4290 llvm::Value *EmitARCRetainNonBlock(llvm::Value *value); 4291 llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory); 4292 void EmitARCDestroyStrong(Address addr, ARCPreciseLifetime_t precise); 4293 void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 4294 llvm::Value *EmitARCAutorelease(llvm::Value *value); 4295 llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value); 4296 llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value); 4297 llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value); 4298 llvm::Value *EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value); 4299 4300 llvm::Value *EmitObjCAutorelease(llvm::Value *value, llvm::Type *returnType); 4301 llvm::Value *EmitObjCRetainNonBlock(llvm::Value *value, 4302 llvm::Type *returnType); 4303 void EmitObjCRelease(llvm::Value *value, ARCPreciseLifetime_t precise); 4304 4305 std::pair<LValue,llvm::Value*> 4306 EmitARCStoreAutoreleasing(const BinaryOperator *e); 4307 std::pair<LValue,llvm::Value*> 4308 EmitARCStoreStrong(const BinaryOperator *e, bool ignored); 4309 std::pair<LValue,llvm::Value*> 4310 EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored); 4311 4312 llvm::Value *EmitObjCAlloc(llvm::Value *value, 4313 llvm::Type *returnType); 4314 llvm::Value *EmitObjCAllocWithZone(llvm::Value *value, 4315 llvm::Type *returnType); 4316 llvm::Value *EmitObjCAllocInit(llvm::Value *value, llvm::Type *resultType); 4317 4318 llvm::Value *EmitObjCThrowOperand(const Expr *expr); 4319 llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr); 4320 llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr); 4321 4322 llvm::Value *EmitARCExtendBlockObject(const Expr *expr); 4323 llvm::Value *EmitARCReclaimReturnedObject(const Expr *e, 4324 bool allowUnsafeClaim); 4325 llvm::Value *EmitARCRetainScalarExpr(const Expr *expr); 4326 llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr); 4327 llvm::Value *EmitARCUnsafeUnretainedScalarExpr(const Expr *expr); 4328 4329 void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values); 4330 4331 void EmitARCNoopIntrinsicUse(ArrayRef<llvm::Value *> values); 4332 4333 static Destroyer destroyARCStrongImprecise; 4334 static Destroyer destroyARCStrongPrecise; 4335 static Destroyer destroyARCWeak; 4336 static Destroyer emitARCIntrinsicUse; 4337 static Destroyer destroyNonTrivialCStruct; 4338 4339 void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr); 4340 llvm::Value *EmitObjCAutoreleasePoolPush(); 4341 llvm::Value *EmitObjCMRRAutoreleasePoolPush(); 4342 void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr); 4343 void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr); 4344 4345 /// Emits a reference binding to the passed in expression. 4346 RValue EmitReferenceBindingToExpr(const Expr *E); 4347 4348 //===--------------------------------------------------------------------===// 4349 // Expression Emission 4350 //===--------------------------------------------------------------------===// 4351 4352 // Expressions are broken into three classes: scalar, complex, aggregate. 4353 4354 /// EmitScalarExpr - Emit the computation of the specified expression of LLVM 4355 /// scalar type, returning the result. 4356 llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false); 4357 4358 /// Emit a conversion from the specified type to the specified destination 4359 /// type, both of which are LLVM scalar types. 4360 llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy, 4361 QualType DstTy, SourceLocation Loc); 4362 4363 /// Emit a conversion from the specified complex type to the specified 4364 /// destination type, where the destination type is an LLVM scalar type. 4365 llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, 4366 QualType DstTy, 4367 SourceLocation Loc); 4368 4369 /// EmitAggExpr - Emit the computation of the specified expression 4370 /// of aggregate type. The result is computed into the given slot, 4371 /// which may be null to indicate that the value is not needed. 4372 void EmitAggExpr(const Expr *E, AggValueSlot AS); 4373 4374 /// EmitAggExprToLValue - Emit the computation of the specified expression of 4375 /// aggregate type into a temporary LValue. 4376 LValue EmitAggExprToLValue(const Expr *E); 4377 4378 /// Build all the stores needed to initialize an aggregate at Dest with the 4379 /// value Val. 4380 void EmitAggregateStore(llvm::Value *Val, Address Dest, bool DestIsVolatile); 4381 4382 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object, 4383 /// make sure it survives garbage collection until this point. 4384 void EmitExtendGCLifetime(llvm::Value *object); 4385 4386 /// EmitComplexExpr - Emit the computation of the specified expression of 4387 /// complex type, returning the result. 4388 ComplexPairTy EmitComplexExpr(const Expr *E, 4389 bool IgnoreReal = false, 4390 bool IgnoreImag = false); 4391 4392 /// EmitComplexExprIntoLValue - Emit the given expression of complex 4393 /// type and place its result into the specified l-value. 4394 void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit); 4395 4396 /// EmitStoreOfComplex - Store a complex number into the specified l-value. 4397 void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit); 4398 4399 /// EmitLoadOfComplex - Load a complex number from the specified l-value. 4400 ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc); 4401 4402 Address emitAddrOfRealComponent(Address complex, QualType complexType); 4403 Address emitAddrOfImagComponent(Address complex, QualType complexType); 4404 4405 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 4406 /// global variable that has already been created for it. If the initializer 4407 /// has a different type than GV does, this may free GV and return a different 4408 /// one. Otherwise it just returns GV. 4409 llvm::GlobalVariable * 4410 AddInitializerToStaticVarDecl(const VarDecl &D, 4411 llvm::GlobalVariable *GV); 4412 4413 // Emit an @llvm.invariant.start call for the given memory region. 4414 void EmitInvariantStart(llvm::Constant *Addr, CharUnits Size); 4415 4416 /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++ 4417 /// variable with global storage. 4418 void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::GlobalVariable *GV, 4419 bool PerformInit); 4420 4421 llvm::Function *createAtExitStub(const VarDecl &VD, llvm::FunctionCallee Dtor, 4422 llvm::Constant *Addr); 4423 4424 llvm::Function *createTLSAtExitStub(const VarDecl &VD, 4425 llvm::FunctionCallee Dtor, 4426 llvm::Constant *Addr, 4427 llvm::FunctionCallee &AtExit); 4428 4429 /// Call atexit() with a function that passes the given argument to 4430 /// the given function. 4431 void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::FunctionCallee fn, 4432 llvm::Constant *addr); 4433 4434 /// Call atexit() with function dtorStub. 4435 void registerGlobalDtorWithAtExit(llvm::Constant *dtorStub); 4436 4437 /// Call unatexit() with function dtorStub. 4438 llvm::Value *unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub); 4439 4440 /// Emit code in this function to perform a guarded variable 4441 /// initialization. Guarded initializations are used when it's not 4442 /// possible to prove that an initialization will be done exactly 4443 /// once, e.g. with a static local variable or a static data member 4444 /// of a class template. 4445 void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, 4446 bool PerformInit); 4447 4448 enum class GuardKind { VariableGuard, TlsGuard }; 4449 4450 /// Emit a branch to select whether or not to perform guarded initialization. 4451 void EmitCXXGuardedInitBranch(llvm::Value *NeedsInit, 4452 llvm::BasicBlock *InitBlock, 4453 llvm::BasicBlock *NoInitBlock, 4454 GuardKind Kind, const VarDecl *D); 4455 4456 /// GenerateCXXGlobalInitFunc - Generates code for initializing global 4457 /// variables. 4458 void 4459 GenerateCXXGlobalInitFunc(llvm::Function *Fn, 4460 ArrayRef<llvm::Function *> CXXThreadLocals, 4461 ConstantAddress Guard = ConstantAddress::invalid()); 4462 4463 /// GenerateCXXGlobalCleanUpFunc - Generates code for cleaning up global 4464 /// variables. 4465 void GenerateCXXGlobalCleanUpFunc( 4466 llvm::Function *Fn, 4467 ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH, 4468 llvm::Constant *>> 4469 DtorsOrStermFinalizers); 4470 4471 void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 4472 const VarDecl *D, 4473 llvm::GlobalVariable *Addr, 4474 bool PerformInit); 4475 4476 void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest); 4477 4478 void EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, const Expr *Exp); 4479 4480 void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true); 4481 4482 RValue EmitAtomicExpr(AtomicExpr *E); 4483 4484 //===--------------------------------------------------------------------===// 4485 // Annotations Emission 4486 //===--------------------------------------------------------------------===// 4487 4488 /// Emit an annotation call (intrinsic). 4489 llvm::Value *EmitAnnotationCall(llvm::Function *AnnotationFn, 4490 llvm::Value *AnnotatedVal, 4491 StringRef AnnotationStr, 4492 SourceLocation Location, 4493 const AnnotateAttr *Attr); 4494 4495 /// Emit local annotations for the local variable V, declared by D. 4496 void EmitVarAnnotations(const VarDecl *D, llvm::Value *V); 4497 4498 /// Emit field annotations for the given field & value. Returns the 4499 /// annotation result. 4500 Address EmitFieldAnnotations(const FieldDecl *D, Address V); 4501 4502 //===--------------------------------------------------------------------===// 4503 // Internal Helpers 4504 //===--------------------------------------------------------------------===// 4505 4506 /// ContainsLabel - Return true if the statement contains a label in it. If 4507 /// this statement is not executed normally, it not containing a label means 4508 /// that we can just remove the code. 4509 static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false); 4510 4511 /// containsBreak - Return true if the statement contains a break out of it. 4512 /// If the statement (recursively) contains a switch or loop with a break 4513 /// inside of it, this is fine. 4514 static bool containsBreak(const Stmt *S); 4515 4516 /// Determine if the given statement might introduce a declaration into the 4517 /// current scope, by being a (possibly-labelled) DeclStmt. 4518 static bool mightAddDeclToScope(const Stmt *S); 4519 4520 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 4521 /// to a constant, or if it does but contains a label, return false. If it 4522 /// constant folds return true and set the boolean result in Result. 4523 bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, 4524 bool AllowLabels = false); 4525 4526 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 4527 /// to a constant, or if it does but contains a label, return false. If it 4528 /// constant folds return true and set the folded value. 4529 bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result, 4530 bool AllowLabels = false); 4531 4532 /// isInstrumentedCondition - Determine whether the given condition is an 4533 /// instrumentable condition (i.e. no "&&" or "||"). 4534 static bool isInstrumentedCondition(const Expr *C); 4535 4536 /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that 4537 /// increments a profile counter based on the semantics of the given logical 4538 /// operator opcode. This is used to instrument branch condition coverage 4539 /// for logical operators. 4540 void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp, 4541 llvm::BasicBlock *TrueBlock, 4542 llvm::BasicBlock *FalseBlock, 4543 uint64_t TrueCount = 0, 4544 Stmt::Likelihood LH = Stmt::LH_None, 4545 const Expr *CntrIdx = nullptr); 4546 4547 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an 4548 /// if statement) to the specified blocks. Based on the condition, this might 4549 /// try to simplify the codegen of the conditional based on the branch. 4550 /// TrueCount should be the number of times we expect the condition to 4551 /// evaluate to true based on PGO data. 4552 void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, 4553 llvm::BasicBlock *FalseBlock, uint64_t TrueCount, 4554 Stmt::Likelihood LH = Stmt::LH_None); 4555 4556 /// Given an assignment `*LHS = RHS`, emit a test that checks if \p RHS is 4557 /// nonnull, if \p LHS is marked _Nonnull. 4558 void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc); 4559 4560 /// An enumeration which makes it easier to specify whether or not an 4561 /// operation is a subtraction. 4562 enum { NotSubtraction = false, IsSubtraction = true }; 4563 4564 /// Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to 4565 /// detect undefined behavior when the pointer overflow sanitizer is enabled. 4566 /// \p SignedIndices indicates whether any of the GEP indices are signed. 4567 /// \p IsSubtraction indicates whether the expression used to form the GEP 4568 /// is a subtraction. 4569 llvm::Value *EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, 4570 ArrayRef<llvm::Value *> IdxList, 4571 bool SignedIndices, 4572 bool IsSubtraction, 4573 SourceLocation Loc, 4574 const Twine &Name = ""); 4575 4576 /// Specifies which type of sanitizer check to apply when handling a 4577 /// particular builtin. 4578 enum BuiltinCheckKind { 4579 BCK_CTZPassedZero, 4580 BCK_CLZPassedZero, 4581 }; 4582 4583 /// Emits an argument for a call to a builtin. If the builtin sanitizer is 4584 /// enabled, a runtime check specified by \p Kind is also emitted. 4585 llvm::Value *EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind); 4586 4587 /// Emit a description of a type in a format suitable for passing to 4588 /// a runtime sanitizer handler. 4589 llvm::Constant *EmitCheckTypeDescriptor(QualType T); 4590 4591 /// Convert a value into a format suitable for passing to a runtime 4592 /// sanitizer handler. 4593 llvm::Value *EmitCheckValue(llvm::Value *V); 4594 4595 /// Emit a description of a source location in a format suitable for 4596 /// passing to a runtime sanitizer handler. 4597 llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc); 4598 4599 /// Create a basic block that will either trap or call a handler function in 4600 /// the UBSan runtime with the provided arguments, and create a conditional 4601 /// branch to it. 4602 void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked, 4603 SanitizerHandler Check, ArrayRef<llvm::Constant *> StaticArgs, 4604 ArrayRef<llvm::Value *> DynamicArgs); 4605 4606 /// Emit a slow path cross-DSO CFI check which calls __cfi_slowpath 4607 /// if Cond if false. 4608 void EmitCfiSlowPathCheck(SanitizerMask Kind, llvm::Value *Cond, 4609 llvm::ConstantInt *TypeId, llvm::Value *Ptr, 4610 ArrayRef<llvm::Constant *> StaticArgs); 4611 4612 /// Emit a reached-unreachable diagnostic if \p Loc is valid and runtime 4613 /// checking is enabled. Otherwise, just emit an unreachable instruction. 4614 void EmitUnreachable(SourceLocation Loc); 4615 4616 /// Create a basic block that will call the trap intrinsic, and emit a 4617 /// conditional branch to it, for the -ftrapv checks. 4618 void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID); 4619 4620 /// Emit a call to trap or debugtrap and attach function attribute 4621 /// "trap-func-name" if specified. 4622 llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID); 4623 4624 /// Emit a stub for the cross-DSO CFI check function. 4625 void EmitCfiCheckStub(); 4626 4627 /// Emit a cross-DSO CFI failure handling function. 4628 void EmitCfiCheckFail(); 4629 4630 /// Create a check for a function parameter that may potentially be 4631 /// declared as non-null. 4632 void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, 4633 AbstractCallee AC, unsigned ParmNum); 4634 4635 /// EmitCallArg - Emit a single call argument. 4636 void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType); 4637 4638 /// EmitDelegateCallArg - We are performing a delegate call; that 4639 /// is, the current function is delegating to another one. Produce 4640 /// a r-value suitable for passing the given parameter. 4641 void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, 4642 SourceLocation loc); 4643 4644 /// SetFPAccuracy - Set the minimum required accuracy of the given floating 4645 /// point operation, expressed as the maximum relative error in ulp. 4646 void SetFPAccuracy(llvm::Value *Val, float Accuracy); 4647 4648 /// Set the codegen fast-math flags. 4649 void SetFastMathFlags(FPOptions FPFeatures); 4650 4651 private: 4652 llvm::MDNode *getRangeForLoadFromType(QualType Ty); 4653 void EmitReturnOfRValue(RValue RV, QualType Ty); 4654 4655 void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New); 4656 4657 llvm::SmallVector<std::pair<llvm::WeakTrackingVH, llvm::Value *>, 4> 4658 DeferredReplacements; 4659 4660 /// Set the address of a local variable. 4661 void setAddrOfLocalVar(const VarDecl *VD, Address Addr) { 4662 assert(!LocalDeclMap.count(VD) && "Decl already exists in LocalDeclMap!"); 4663 LocalDeclMap.insert({VD, Addr}); 4664 } 4665 4666 /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty 4667 /// from function arguments into \arg Dst. See ABIArgInfo::Expand. 4668 /// 4669 /// \param AI - The first function argument of the expansion. 4670 void ExpandTypeFromArgs(QualType Ty, LValue Dst, 4671 llvm::Function::arg_iterator &AI); 4672 4673 /// ExpandTypeToArgs - Expand an CallArg \arg Arg, with the LLVM type for \arg 4674 /// Ty, into individual arguments on the provided vector \arg IRCallArgs, 4675 /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand. 4676 void ExpandTypeToArgs(QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy, 4677 SmallVectorImpl<llvm::Value *> &IRCallArgs, 4678 unsigned &IRCallArgPos); 4679 4680 llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info, 4681 const Expr *InputExpr, std::string &ConstraintStr); 4682 4683 llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info, 4684 LValue InputValue, QualType InputType, 4685 std::string &ConstraintStr, 4686 SourceLocation Loc); 4687 4688 /// Attempts to statically evaluate the object size of E. If that 4689 /// fails, emits code to figure the size of E out for us. This is 4690 /// pass_object_size aware. 4691 /// 4692 /// If EmittedExpr is non-null, this will use that instead of re-emitting E. 4693 llvm::Value *evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, 4694 llvm::IntegerType *ResType, 4695 llvm::Value *EmittedE, 4696 bool IsDynamic); 4697 4698 /// Emits the size of E, as required by __builtin_object_size. This 4699 /// function is aware of pass_object_size parameters, and will act accordingly 4700 /// if E is a parameter with the pass_object_size attribute. 4701 llvm::Value *emitBuiltinObjectSize(const Expr *E, unsigned Type, 4702 llvm::IntegerType *ResType, 4703 llvm::Value *EmittedE, 4704 bool IsDynamic); 4705 4706 void emitZeroOrPatternForAutoVarInit(QualType type, const VarDecl &D, 4707 Address Loc); 4708 4709 public: 4710 enum class EvaluationOrder { 4711 ///! No language constraints on evaluation order. 4712 Default, 4713 ///! Language semantics require left-to-right evaluation. 4714 ForceLeftToRight, 4715 ///! Language semantics require right-to-left evaluation. 4716 ForceRightToLeft 4717 }; 4718 4719 // Wrapper for function prototype sources. Wraps either a FunctionProtoType or 4720 // an ObjCMethodDecl. 4721 struct PrototypeWrapper { 4722 llvm::PointerUnion<const FunctionProtoType *, const ObjCMethodDecl *> P; 4723 4724 PrototypeWrapper(const FunctionProtoType *FT) : P(FT) {} 4725 PrototypeWrapper(const ObjCMethodDecl *MD) : P(MD) {} 4726 }; 4727 4728 void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, 4729 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 4730 AbstractCallee AC = AbstractCallee(), 4731 unsigned ParamsToSkip = 0, 4732 EvaluationOrder Order = EvaluationOrder::Default); 4733 4734 /// EmitPointerWithAlignment - Given an expression with a pointer type, 4735 /// emit the value and compute our best estimate of the alignment of the 4736 /// pointee. 4737 /// 4738 /// \param BaseInfo - If non-null, this will be initialized with 4739 /// information about the source of the alignment and the may-alias 4740 /// attribute. Note that this function will conservatively fall back on 4741 /// the type when it doesn't recognize the expression and may-alias will 4742 /// be set to false. 4743 /// 4744 /// One reasonable way to use this information is when there's a language 4745 /// guarantee that the pointer must be aligned to some stricter value, and 4746 /// we're simply trying to ensure that sufficiently obvious uses of under- 4747 /// aligned objects don't get miscompiled; for example, a placement new 4748 /// into the address of a local variable. In such a case, it's quite 4749 /// reasonable to just ignore the returned alignment when it isn't from an 4750 /// explicit source. 4751 Address EmitPointerWithAlignment(const Expr *Addr, 4752 LValueBaseInfo *BaseInfo = nullptr, 4753 TBAAAccessInfo *TBAAInfo = nullptr); 4754 4755 /// If \p E references a parameter with pass_object_size info or a constant 4756 /// array size modifier, emit the object size divided by the size of \p EltTy. 4757 /// Otherwise return null. 4758 llvm::Value *LoadPassedObjectSize(const Expr *E, QualType EltTy); 4759 4760 void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK); 4761 4762 struct MultiVersionResolverOption { 4763 llvm::Function *Function; 4764 struct Conds { 4765 StringRef Architecture; 4766 llvm::SmallVector<StringRef, 8> Features; 4767 4768 Conds(StringRef Arch, ArrayRef<StringRef> Feats) 4769 : Architecture(Arch), Features(Feats.begin(), Feats.end()) {} 4770 } Conditions; 4771 4772 MultiVersionResolverOption(llvm::Function *F, StringRef Arch, 4773 ArrayRef<StringRef> Feats) 4774 : Function(F), Conditions(Arch, Feats) {} 4775 }; 4776 4777 // Emits the body of a multiversion function's resolver. Assumes that the 4778 // options are already sorted in the proper order, with the 'default' option 4779 // last (if it exists). 4780 void EmitMultiVersionResolver(llvm::Function *Resolver, 4781 ArrayRef<MultiVersionResolverOption> Options); 4782 4783 private: 4784 QualType getVarArgType(const Expr *Arg); 4785 4786 void EmitDeclMetadata(); 4787 4788 BlockByrefHelpers *buildByrefHelpers(llvm::StructType &byrefType, 4789 const AutoVarEmission &emission); 4790 4791 void AddObjCARCExceptionMetadata(llvm::Instruction *Inst); 4792 4793 llvm::Value *GetValueForARMHint(unsigned BuiltinID); 4794 llvm::Value *EmitX86CpuIs(const CallExpr *E); 4795 llvm::Value *EmitX86CpuIs(StringRef CPUStr); 4796 llvm::Value *EmitX86CpuSupports(const CallExpr *E); 4797 llvm::Value *EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs); 4798 llvm::Value *EmitX86CpuSupports(uint64_t Mask); 4799 llvm::Value *EmitX86CpuInit(); 4800 llvm::Value *FormResolverCondition(const MultiVersionResolverOption &RO); 4801 }; 4802 4803 /// TargetFeatures - This class is used to check whether the builtin function 4804 /// has the required tagert specific features. It is able to support the 4805 /// combination of ','(and), '|'(or), and '()'. By default, the priority of 4806 /// ',' is higher than that of '|' . 4807 /// E.g: 4808 /// A,B|C means the builtin function requires both A and B, or C. 4809 /// If we want the builtin function requires both A and B, or both A and C, 4810 /// there are two ways: A,B|A,C or A,(B|C). 4811 /// The FeaturesList should not contain spaces, and brackets must appear in 4812 /// pairs. 4813 class TargetFeatures { 4814 struct FeatureListStatus { 4815 bool HasFeatures; 4816 StringRef CurFeaturesList; 4817 }; 4818 4819 const llvm::StringMap<bool> &CallerFeatureMap; 4820 4821 FeatureListStatus getAndFeatures(StringRef FeatureList) { 4822 int InParentheses = 0; 4823 bool HasFeatures = true; 4824 size_t SubexpressionStart = 0; 4825 for (size_t i = 0, e = FeatureList.size(); i < e; ++i) { 4826 char CurrentToken = FeatureList[i]; 4827 switch (CurrentToken) { 4828 default: 4829 break; 4830 case '(': 4831 if (InParentheses == 0) 4832 SubexpressionStart = i + 1; 4833 ++InParentheses; 4834 break; 4835 case ')': 4836 --InParentheses; 4837 assert(InParentheses >= 0 && "Parentheses are not in pair"); 4838 LLVM_FALLTHROUGH; 4839 case '|': 4840 case ',': 4841 if (InParentheses == 0) { 4842 if (HasFeatures && i != SubexpressionStart) { 4843 StringRef F = FeatureList.slice(SubexpressionStart, i); 4844 HasFeatures = CurrentToken == ')' ? hasRequiredFeatures(F) 4845 : CallerFeatureMap.lookup(F); 4846 } 4847 SubexpressionStart = i + 1; 4848 if (CurrentToken == '|') { 4849 return {HasFeatures, FeatureList.substr(SubexpressionStart)}; 4850 } 4851 } 4852 break; 4853 } 4854 } 4855 assert(InParentheses == 0 && "Parentheses are not in pair"); 4856 if (HasFeatures && SubexpressionStart != FeatureList.size()) 4857 HasFeatures = 4858 CallerFeatureMap.lookup(FeatureList.substr(SubexpressionStart)); 4859 return {HasFeatures, StringRef()}; 4860 } 4861 4862 public: 4863 bool hasRequiredFeatures(StringRef FeatureList) { 4864 FeatureListStatus FS = {false, FeatureList}; 4865 while (!FS.HasFeatures && !FS.CurFeaturesList.empty()) 4866 FS = getAndFeatures(FS.CurFeaturesList); 4867 return FS.HasFeatures; 4868 } 4869 4870 TargetFeatures(const llvm::StringMap<bool> &CallerFeatureMap) 4871 : CallerFeatureMap(CallerFeatureMap) {} 4872 }; 4873 4874 inline DominatingLLVMValue::saved_type 4875 DominatingLLVMValue::save(CodeGenFunction &CGF, llvm::Value *value) { 4876 if (!needsSaving(value)) return saved_type(value, false); 4877 4878 // Otherwise, we need an alloca. 4879 auto align = CharUnits::fromQuantity( 4880 CGF.CGM.getDataLayout().getPrefTypeAlignment(value->getType())); 4881 Address alloca = 4882 CGF.CreateTempAlloca(value->getType(), align, "cond-cleanup.save"); 4883 CGF.Builder.CreateStore(value, alloca); 4884 4885 return saved_type(alloca.getPointer(), true); 4886 } 4887 4888 inline llvm::Value *DominatingLLVMValue::restore(CodeGenFunction &CGF, 4889 saved_type value) { 4890 // If the value says it wasn't saved, trust that it's still dominating. 4891 if (!value.getInt()) return value.getPointer(); 4892 4893 // Otherwise, it should be an alloca instruction, as set up in save(). 4894 auto alloca = cast<llvm::AllocaInst>(value.getPointer()); 4895 return CGF.Builder.CreateAlignedLoad(alloca->getAllocatedType(), alloca, 4896 alloca->getAlign()); 4897 } 4898 4899 } // end namespace CodeGen 4900 4901 // Map the LangOption for floating point exception behavior into 4902 // the corresponding enum in the IR. 4903 llvm::fp::ExceptionBehavior 4904 ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind); 4905 } // end namespace clang 4906 4907 #endif 4908