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