1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Constant Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCXXABI.h" 16 #include "CGObjCRuntime.h" 17 #include "CGRecordLayout.h" 18 #include "CodeGenModule.h" 19 #include "TargetInfo.h" 20 #include "clang/AST/APValue.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/Basic/Builtins.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DataLayout.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/GlobalVariable.h" 29 using namespace clang; 30 using namespace CodeGen; 31 32 //===----------------------------------------------------------------------===// 33 // ConstStructBuilder 34 //===----------------------------------------------------------------------===// 35 36 namespace { 37 class ConstExprEmitter; 38 class ConstStructBuilder { 39 CodeGenModule &CGM; 40 CodeGenFunction *CGF; 41 42 bool Packed; 43 CharUnits NextFieldOffsetInChars; 44 CharUnits LLVMStructAlignment; 45 SmallVector<llvm::Constant *, 32> Elements; 46 public: 47 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CFG, 48 ConstExprEmitter *Emitter, 49 llvm::ConstantStruct *Base, 50 InitListExpr *Updater); 51 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, 52 InitListExpr *ILE); 53 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, 54 const APValue &Value, QualType ValTy); 55 56 private: 57 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF) 58 : CGM(CGM), CGF(CGF), Packed(false), 59 NextFieldOffsetInChars(CharUnits::Zero()), 60 LLVMStructAlignment(CharUnits::One()) { } 61 62 void AppendField(const FieldDecl *Field, uint64_t FieldOffset, 63 llvm::Constant *InitExpr); 64 65 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst); 66 67 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, 68 llvm::ConstantInt *InitExpr); 69 70 void AppendPadding(CharUnits PadSize); 71 72 void AppendTailPadding(CharUnits RecordSize); 73 74 void ConvertStructToPacked(); 75 76 bool Build(InitListExpr *ILE); 77 bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base, 78 InitListExpr *Updater); 79 void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase, 80 const CXXRecordDecl *VTableClass, CharUnits BaseOffset); 81 llvm::Constant *Finalize(QualType Ty); 82 83 CharUnits getAlignment(const llvm::Constant *C) const { 84 if (Packed) return CharUnits::One(); 85 return CharUnits::fromQuantity( 86 CGM.getDataLayout().getABITypeAlignment(C->getType())); 87 } 88 89 CharUnits getSizeInChars(const llvm::Constant *C) const { 90 return CharUnits::fromQuantity( 91 CGM.getDataLayout().getTypeAllocSize(C->getType())); 92 } 93 }; 94 95 void ConstStructBuilder:: 96 AppendField(const FieldDecl *Field, uint64_t FieldOffset, 97 llvm::Constant *InitCst) { 98 const ASTContext &Context = CGM.getContext(); 99 100 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset); 101 102 AppendBytes(FieldOffsetInChars, InitCst); 103 } 104 105 void ConstStructBuilder:: 106 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) { 107 108 assert(NextFieldOffsetInChars <= FieldOffsetInChars 109 && "Field offset mismatch!"); 110 111 CharUnits FieldAlignment = getAlignment(InitCst); 112 113 // Round up the field offset to the alignment of the field type. 114 CharUnits AlignedNextFieldOffsetInChars = 115 NextFieldOffsetInChars.alignTo(FieldAlignment); 116 117 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) { 118 // We need to append padding. 119 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars); 120 121 assert(NextFieldOffsetInChars == FieldOffsetInChars && 122 "Did not add enough padding!"); 123 124 AlignedNextFieldOffsetInChars = 125 NextFieldOffsetInChars.alignTo(FieldAlignment); 126 } 127 128 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) { 129 assert(!Packed && "Alignment is wrong even with a packed struct!"); 130 131 // Convert the struct to a packed struct. 132 ConvertStructToPacked(); 133 134 // After we pack the struct, we may need to insert padding. 135 if (NextFieldOffsetInChars < FieldOffsetInChars) { 136 // We need to append padding. 137 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars); 138 139 assert(NextFieldOffsetInChars == FieldOffsetInChars && 140 "Did not add enough padding!"); 141 } 142 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars; 143 } 144 145 // Add the field. 146 Elements.push_back(InitCst); 147 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars + 148 getSizeInChars(InitCst); 149 150 if (Packed) 151 assert(LLVMStructAlignment == CharUnits::One() && 152 "Packed struct not byte-aligned!"); 153 else 154 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment); 155 } 156 157 void ConstStructBuilder::AppendBitField(const FieldDecl *Field, 158 uint64_t FieldOffset, 159 llvm::ConstantInt *CI) { 160 const ASTContext &Context = CGM.getContext(); 161 const uint64_t CharWidth = Context.getCharWidth(); 162 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars); 163 if (FieldOffset > NextFieldOffsetInBits) { 164 // We need to add padding. 165 CharUnits PadSize = Context.toCharUnitsFromBits( 166 llvm::alignTo(FieldOffset - NextFieldOffsetInBits, 167 Context.getTargetInfo().getCharAlign())); 168 169 AppendPadding(PadSize); 170 } 171 172 uint64_t FieldSize = Field->getBitWidthValue(Context); 173 174 llvm::APInt FieldValue = CI->getValue(); 175 176 // Promote the size of FieldValue if necessary 177 // FIXME: This should never occur, but currently it can because initializer 178 // constants are cast to bool, and because clang is not enforcing bitfield 179 // width limits. 180 if (FieldSize > FieldValue.getBitWidth()) 181 FieldValue = FieldValue.zext(FieldSize); 182 183 // Truncate the size of FieldValue to the bit field size. 184 if (FieldSize < FieldValue.getBitWidth()) 185 FieldValue = FieldValue.trunc(FieldSize); 186 187 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars); 188 if (FieldOffset < NextFieldOffsetInBits) { 189 // Either part of the field or the entire field can go into the previous 190 // byte. 191 assert(!Elements.empty() && "Elements can't be empty!"); 192 193 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset; 194 195 bool FitsCompletelyInPreviousByte = 196 BitsInPreviousByte >= FieldValue.getBitWidth(); 197 198 llvm::APInt Tmp = FieldValue; 199 200 if (!FitsCompletelyInPreviousByte) { 201 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte; 202 203 if (CGM.getDataLayout().isBigEndian()) { 204 Tmp = Tmp.lshr(NewFieldWidth); 205 Tmp = Tmp.trunc(BitsInPreviousByte); 206 207 // We want the remaining high bits. 208 FieldValue = FieldValue.trunc(NewFieldWidth); 209 } else { 210 Tmp = Tmp.trunc(BitsInPreviousByte); 211 212 // We want the remaining low bits. 213 FieldValue = FieldValue.lshr(BitsInPreviousByte); 214 FieldValue = FieldValue.trunc(NewFieldWidth); 215 } 216 } 217 218 Tmp = Tmp.zext(CharWidth); 219 if (CGM.getDataLayout().isBigEndian()) { 220 if (FitsCompletelyInPreviousByte) 221 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth()); 222 } else { 223 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte); 224 } 225 226 // 'or' in the bits that go into the previous byte. 227 llvm::Value *LastElt = Elements.back(); 228 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt)) 229 Tmp |= Val->getValue(); 230 else { 231 assert(isa<llvm::UndefValue>(LastElt)); 232 // If there is an undef field that we're adding to, it can either be a 233 // scalar undef (in which case, we just replace it with our field) or it 234 // is an array. If it is an array, we have to pull one byte off the 235 // array so that the other undef bytes stay around. 236 if (!isa<llvm::IntegerType>(LastElt->getType())) { 237 // The undef padding will be a multibyte array, create a new smaller 238 // padding and then an hole for our i8 to get plopped into. 239 assert(isa<llvm::ArrayType>(LastElt->getType()) && 240 "Expected array padding of undefs"); 241 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType()); 242 assert(AT->getElementType()->isIntegerTy(CharWidth) && 243 AT->getNumElements() != 0 && 244 "Expected non-empty array padding of undefs"); 245 246 // Remove the padding array. 247 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements()); 248 Elements.pop_back(); 249 250 // Add the padding back in two chunks. 251 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1)); 252 AppendPadding(CharUnits::One()); 253 assert(isa<llvm::UndefValue>(Elements.back()) && 254 Elements.back()->getType()->isIntegerTy(CharWidth) && 255 "Padding addition didn't work right"); 256 } 257 } 258 259 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp); 260 261 if (FitsCompletelyInPreviousByte) 262 return; 263 } 264 265 while (FieldValue.getBitWidth() > CharWidth) { 266 llvm::APInt Tmp; 267 268 if (CGM.getDataLayout().isBigEndian()) { 269 // We want the high bits. 270 Tmp = 271 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth); 272 } else { 273 // We want the low bits. 274 Tmp = FieldValue.trunc(CharWidth); 275 276 FieldValue = FieldValue.lshr(CharWidth); 277 } 278 279 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp)); 280 ++NextFieldOffsetInChars; 281 282 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth); 283 } 284 285 assert(FieldValue.getBitWidth() > 0 && 286 "Should have at least one bit left!"); 287 assert(FieldValue.getBitWidth() <= CharWidth && 288 "Should not have more than a byte left!"); 289 290 if (FieldValue.getBitWidth() < CharWidth) { 291 if (CGM.getDataLayout().isBigEndian()) { 292 unsigned BitWidth = FieldValue.getBitWidth(); 293 294 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth); 295 } else 296 FieldValue = FieldValue.zext(CharWidth); 297 } 298 299 // Append the last element. 300 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), 301 FieldValue)); 302 ++NextFieldOffsetInChars; 303 } 304 305 void ConstStructBuilder::AppendPadding(CharUnits PadSize) { 306 if (PadSize.isZero()) 307 return; 308 309 llvm::Type *Ty = CGM.Int8Ty; 310 if (PadSize > CharUnits::One()) 311 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity()); 312 313 llvm::Constant *C = llvm::UndefValue::get(Ty); 314 Elements.push_back(C); 315 assert(getAlignment(C) == CharUnits::One() && 316 "Padding must have 1 byte alignment!"); 317 318 NextFieldOffsetInChars += getSizeInChars(C); 319 } 320 321 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) { 322 assert(NextFieldOffsetInChars <= RecordSize && 323 "Size mismatch!"); 324 325 AppendPadding(RecordSize - NextFieldOffsetInChars); 326 } 327 328 void ConstStructBuilder::ConvertStructToPacked() { 329 SmallVector<llvm::Constant *, 16> PackedElements; 330 CharUnits ElementOffsetInChars = CharUnits::Zero(); 331 332 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 333 llvm::Constant *C = Elements[i]; 334 335 CharUnits ElementAlign = CharUnits::fromQuantity( 336 CGM.getDataLayout().getABITypeAlignment(C->getType())); 337 CharUnits AlignedElementOffsetInChars = 338 ElementOffsetInChars.alignTo(ElementAlign); 339 340 if (AlignedElementOffsetInChars > ElementOffsetInChars) { 341 // We need some padding. 342 CharUnits NumChars = 343 AlignedElementOffsetInChars - ElementOffsetInChars; 344 345 llvm::Type *Ty = CGM.Int8Ty; 346 if (NumChars > CharUnits::One()) 347 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity()); 348 349 llvm::Constant *Padding = llvm::UndefValue::get(Ty); 350 PackedElements.push_back(Padding); 351 ElementOffsetInChars += getSizeInChars(Padding); 352 } 353 354 PackedElements.push_back(C); 355 ElementOffsetInChars += getSizeInChars(C); 356 } 357 358 assert(ElementOffsetInChars == NextFieldOffsetInChars && 359 "Packing the struct changed its size!"); 360 361 Elements.swap(PackedElements); 362 LLVMStructAlignment = CharUnits::One(); 363 Packed = true; 364 } 365 366 bool ConstStructBuilder::Build(InitListExpr *ILE) { 367 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl(); 368 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 369 370 unsigned FieldNo = 0; 371 unsigned ElementNo = 0; 372 373 // Bail out if we have base classes. We could support these, but they only 374 // arise in C++1z where we will have already constant folded most interesting 375 // cases. FIXME: There are still a few more cases we can handle this way. 376 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 377 if (CXXRD->getNumBases()) 378 return false; 379 380 for (RecordDecl::field_iterator Field = RD->field_begin(), 381 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { 382 // If this is a union, skip all the fields that aren't being initialized. 383 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field) 384 continue; 385 386 // Don't emit anonymous bitfields, they just affect layout. 387 if (Field->isUnnamedBitfield()) 388 continue; 389 390 // Get the initializer. A struct can include fields without initializers, 391 // we just use explicit null values for them. 392 llvm::Constant *EltInit; 393 if (ElementNo < ILE->getNumInits()) 394 EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++), 395 Field->getType(), CGF); 396 else 397 EltInit = CGM.EmitNullConstant(Field->getType()); 398 399 if (!EltInit) 400 return false; 401 402 if (!Field->isBitField()) { 403 // Handle non-bitfield members. 404 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit); 405 } else { 406 // Otherwise we have a bitfield. 407 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) { 408 AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI); 409 } else { 410 // We are trying to initialize a bitfield with a non-trivial constant, 411 // this must require run-time code. 412 return false; 413 } 414 } 415 } 416 417 return true; 418 } 419 420 namespace { 421 struct BaseInfo { 422 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index) 423 : Decl(Decl), Offset(Offset), Index(Index) { 424 } 425 426 const CXXRecordDecl *Decl; 427 CharUnits Offset; 428 unsigned Index; 429 430 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; } 431 }; 432 } 433 434 void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD, 435 bool IsPrimaryBase, 436 const CXXRecordDecl *VTableClass, 437 CharUnits Offset) { 438 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 439 440 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 441 // Add a vtable pointer, if we need one and it hasn't already been added. 442 if (CD->isDynamicClass() && !IsPrimaryBase) { 443 llvm::Constant *VTableAddressPoint = 444 CGM.getCXXABI().getVTableAddressPointForConstExpr( 445 BaseSubobject(CD, Offset), VTableClass); 446 AppendBytes(Offset, VTableAddressPoint); 447 } 448 449 // Accumulate and sort bases, in order to visit them in address order, which 450 // may not be the same as declaration order. 451 SmallVector<BaseInfo, 8> Bases; 452 Bases.reserve(CD->getNumBases()); 453 unsigned BaseNo = 0; 454 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(), 455 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) { 456 assert(!Base->isVirtual() && "should not have virtual bases here"); 457 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl(); 458 CharUnits BaseOffset = Layout.getBaseClassOffset(BD); 459 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo)); 460 } 461 std::stable_sort(Bases.begin(), Bases.end()); 462 463 for (unsigned I = 0, N = Bases.size(); I != N; ++I) { 464 BaseInfo &Base = Bases[I]; 465 466 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl; 467 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase, 468 VTableClass, Offset + Base.Offset); 469 } 470 } 471 472 unsigned FieldNo = 0; 473 uint64_t OffsetBits = CGM.getContext().toBits(Offset); 474 475 for (RecordDecl::field_iterator Field = RD->field_begin(), 476 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { 477 // If this is a union, skip all the fields that aren't being initialized. 478 if (RD->isUnion() && Val.getUnionField() != *Field) 479 continue; 480 481 // Don't emit anonymous bitfields, they just affect layout. 482 if (Field->isUnnamedBitfield()) 483 continue; 484 485 // Emit the value of the initializer. 486 const APValue &FieldValue = 487 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo); 488 llvm::Constant *EltInit = 489 CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF); 490 assert(EltInit && "EmitConstantValue can't fail"); 491 492 if (!Field->isBitField()) { 493 // Handle non-bitfield members. 494 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit); 495 } else { 496 // Otherwise we have a bitfield. 497 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, 498 cast<llvm::ConstantInt>(EltInit)); 499 } 500 } 501 } 502 503 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) { 504 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl(); 505 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 506 507 CharUnits LayoutSizeInChars = Layout.getSize(); 508 509 if (NextFieldOffsetInChars > LayoutSizeInChars) { 510 // If the struct is bigger than the size of the record type, 511 // we must have a flexible array member at the end. 512 assert(RD->hasFlexibleArrayMember() && 513 "Must have flexible array member if struct is bigger than type!"); 514 515 // No tail padding is necessary. 516 } else { 517 // Append tail padding if necessary. 518 CharUnits LLVMSizeInChars = 519 NextFieldOffsetInChars.alignTo(LLVMStructAlignment); 520 521 if (LLVMSizeInChars != LayoutSizeInChars) 522 AppendTailPadding(LayoutSizeInChars); 523 524 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment); 525 526 // Check if we need to convert the struct to a packed struct. 527 if (NextFieldOffsetInChars <= LayoutSizeInChars && 528 LLVMSizeInChars > LayoutSizeInChars) { 529 assert(!Packed && "Size mismatch!"); 530 531 ConvertStructToPacked(); 532 assert(NextFieldOffsetInChars <= LayoutSizeInChars && 533 "Converting to packed did not help!"); 534 } 535 536 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment); 537 538 assert(LayoutSizeInChars == LLVMSizeInChars && 539 "Tail padding mismatch!"); 540 } 541 542 // Pick the type to use. If the type is layout identical to the ConvertType 543 // type then use it, otherwise use whatever the builder produced for us. 544 llvm::StructType *STy = 545 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(), 546 Elements, Packed); 547 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty); 548 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) { 549 if (ValSTy->isLayoutIdentical(STy)) 550 STy = ValSTy; 551 } 552 553 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements); 554 555 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) == 556 getSizeInChars(Result) && 557 "Size mismatch!"); 558 559 return Result; 560 } 561 562 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM, 563 CodeGenFunction *CGF, 564 ConstExprEmitter *Emitter, 565 llvm::ConstantStruct *Base, 566 InitListExpr *Updater) { 567 ConstStructBuilder Builder(CGM, CGF); 568 if (!Builder.Build(Emitter, Base, Updater)) 569 return nullptr; 570 return Builder.Finalize(Updater->getType()); 571 } 572 573 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM, 574 CodeGenFunction *CGF, 575 InitListExpr *ILE) { 576 ConstStructBuilder Builder(CGM, CGF); 577 578 if (!Builder.Build(ILE)) 579 return nullptr; 580 581 return Builder.Finalize(ILE->getType()); 582 } 583 584 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM, 585 CodeGenFunction *CGF, 586 const APValue &Val, 587 QualType ValTy) { 588 ConstStructBuilder Builder(CGM, CGF); 589 590 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl(); 591 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 592 Builder.Build(Val, RD, false, CD, CharUnits::Zero()); 593 594 return Builder.Finalize(ValTy); 595 } 596 597 598 //===----------------------------------------------------------------------===// 599 // ConstExprEmitter 600 //===----------------------------------------------------------------------===// 601 602 /// This class only needs to handle two cases: 603 /// 1) Literals (this is used by APValue emission to emit literals). 604 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently 605 /// constant fold these types). 606 class ConstExprEmitter : 607 public StmtVisitor<ConstExprEmitter, llvm::Constant*> { 608 CodeGenModule &CGM; 609 CodeGenFunction *CGF; 610 llvm::LLVMContext &VMContext; 611 public: 612 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf) 613 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) { 614 } 615 616 //===--------------------------------------------------------------------===// 617 // Visitor Methods 618 //===--------------------------------------------------------------------===// 619 620 llvm::Constant *VisitStmt(Stmt *S) { 621 return nullptr; 622 } 623 624 llvm::Constant *VisitParenExpr(ParenExpr *PE) { 625 return Visit(PE->getSubExpr()); 626 } 627 628 llvm::Constant * 629 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) { 630 return Visit(PE->getReplacement()); 631 } 632 633 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) { 634 return Visit(GE->getResultExpr()); 635 } 636 637 llvm::Constant *VisitChooseExpr(ChooseExpr *CE) { 638 return Visit(CE->getChosenSubExpr()); 639 } 640 641 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 642 return Visit(E->getInitializer()); 643 } 644 645 llvm::Constant *VisitCastExpr(CastExpr* E) { 646 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E)) 647 CGM.EmitExplicitCastExprType(ECE, CGF); 648 Expr *subExpr = E->getSubExpr(); 649 llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF); 650 if (!C) return nullptr; 651 652 llvm::Type *destType = ConvertType(E->getType()); 653 654 switch (E->getCastKind()) { 655 case CK_ToUnion: { 656 // GCC cast to union extension 657 assert(E->getType()->isUnionType() && 658 "Destination type is not union type!"); 659 660 // Build a struct with the union sub-element as the first member, 661 // and padded to the appropriate size 662 SmallVector<llvm::Constant*, 2> Elts; 663 SmallVector<llvm::Type*, 2> Types; 664 Elts.push_back(C); 665 Types.push_back(C->getType()); 666 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType()); 667 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType); 668 669 assert(CurSize <= TotalSize && "Union size mismatch!"); 670 if (unsigned NumPadBytes = TotalSize - CurSize) { 671 llvm::Type *Ty = CGM.Int8Ty; 672 if (NumPadBytes > 1) 673 Ty = llvm::ArrayType::get(Ty, NumPadBytes); 674 675 Elts.push_back(llvm::UndefValue::get(Ty)); 676 Types.push_back(Ty); 677 } 678 679 llvm::StructType* STy = 680 llvm::StructType::get(C->getType()->getContext(), Types, false); 681 return llvm::ConstantStruct::get(STy, Elts); 682 } 683 684 case CK_AddressSpaceConversion: 685 return llvm::ConstantExpr::getAddrSpaceCast(C, destType); 686 687 case CK_LValueToRValue: 688 case CK_AtomicToNonAtomic: 689 case CK_NonAtomicToAtomic: 690 case CK_NoOp: 691 case CK_ConstructorConversion: 692 return C; 693 694 case CK_IntToOCLSampler: 695 llvm_unreachable("global sampler variables are not generated"); 696 697 case CK_Dependent: llvm_unreachable("saw dependent cast!"); 698 699 case CK_BuiltinFnToFnPtr: 700 llvm_unreachable("builtin functions are handled elsewhere"); 701 702 case CK_ReinterpretMemberPointer: 703 case CK_DerivedToBaseMemberPointer: 704 case CK_BaseToDerivedMemberPointer: 705 return CGM.getCXXABI().EmitMemberPointerConversion(E, C); 706 707 // These will never be supported. 708 case CK_ObjCObjectLValueCast: 709 case CK_ARCProduceObject: 710 case CK_ARCConsumeObject: 711 case CK_ARCReclaimReturnedObject: 712 case CK_ARCExtendBlockObject: 713 case CK_CopyAndAutoreleaseBlockObject: 714 return nullptr; 715 716 // These don't need to be handled here because Evaluate knows how to 717 // evaluate them in the cases where they can be folded. 718 case CK_BitCast: 719 case CK_ToVoid: 720 case CK_Dynamic: 721 case CK_LValueBitCast: 722 case CK_NullToMemberPointer: 723 case CK_UserDefinedConversion: 724 case CK_CPointerToObjCPointerCast: 725 case CK_BlockPointerToObjCPointerCast: 726 case CK_AnyPointerToBlockPointerCast: 727 case CK_ArrayToPointerDecay: 728 case CK_FunctionToPointerDecay: 729 case CK_BaseToDerived: 730 case CK_DerivedToBase: 731 case CK_UncheckedDerivedToBase: 732 case CK_MemberPointerToBoolean: 733 case CK_VectorSplat: 734 case CK_FloatingRealToComplex: 735 case CK_FloatingComplexToReal: 736 case CK_FloatingComplexToBoolean: 737 case CK_FloatingComplexCast: 738 case CK_FloatingComplexToIntegralComplex: 739 case CK_IntegralRealToComplex: 740 case CK_IntegralComplexToReal: 741 case CK_IntegralComplexToBoolean: 742 case CK_IntegralComplexCast: 743 case CK_IntegralComplexToFloatingComplex: 744 case CK_PointerToIntegral: 745 case CK_PointerToBoolean: 746 case CK_NullToPointer: 747 case CK_IntegralCast: 748 case CK_BooleanToSignedIntegral: 749 case CK_IntegralToPointer: 750 case CK_IntegralToBoolean: 751 case CK_IntegralToFloating: 752 case CK_FloatingToIntegral: 753 case CK_FloatingToBoolean: 754 case CK_FloatingCast: 755 case CK_ZeroToOCLEvent: 756 case CK_ZeroToOCLQueue: 757 return nullptr; 758 } 759 llvm_unreachable("Invalid CastKind"); 760 } 761 762 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 763 return Visit(DAE->getExpr()); 764 } 765 766 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) { 767 // No need for a DefaultInitExprScope: we don't handle 'this' in a 768 // constant expression. 769 return Visit(DIE->getExpr()); 770 } 771 772 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E) { 773 if (!E->cleanupsHaveSideEffects()) 774 return Visit(E->getSubExpr()); 775 return nullptr; 776 } 777 778 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { 779 return Visit(E->GetTemporaryExpr()); 780 } 781 782 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) { 783 llvm::ArrayType *AType = 784 cast<llvm::ArrayType>(ConvertType(ILE->getType())); 785 llvm::Type *ElemTy = AType->getElementType(); 786 unsigned NumInitElements = ILE->getNumInits(); 787 unsigned NumElements = AType->getNumElements(); 788 789 // Initialising an array requires us to automatically 790 // initialise any elements that have not been initialised explicitly 791 unsigned NumInitableElts = std::min(NumInitElements, NumElements); 792 793 // Initialize remaining array elements. 794 // FIXME: This doesn't handle member pointers correctly! 795 llvm::Constant *fillC; 796 if (Expr *filler = ILE->getArrayFiller()) 797 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF); 798 else 799 fillC = llvm::Constant::getNullValue(ElemTy); 800 if (!fillC) 801 return nullptr; 802 803 // Try to use a ConstantAggregateZero if we can. 804 if (fillC->isNullValue() && !NumInitableElts) 805 return llvm::ConstantAggregateZero::get(AType); 806 807 // Copy initializer elements. 808 std::vector<llvm::Constant*> Elts; 809 Elts.reserve(NumInitableElts + NumElements); 810 811 bool RewriteType = false; 812 for (unsigned i = 0; i < NumInitableElts; ++i) { 813 Expr *Init = ILE->getInit(i); 814 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF); 815 if (!C) 816 return nullptr; 817 RewriteType |= (C->getType() != ElemTy); 818 Elts.push_back(C); 819 } 820 821 RewriteType |= (fillC->getType() != ElemTy); 822 Elts.resize(NumElements, fillC); 823 824 if (RewriteType) { 825 // FIXME: Try to avoid packing the array 826 std::vector<llvm::Type*> Types; 827 Types.reserve(NumInitableElts + NumElements); 828 for (unsigned i = 0, e = Elts.size(); i < e; ++i) 829 Types.push_back(Elts[i]->getType()); 830 llvm::StructType *SType = llvm::StructType::get(AType->getContext(), 831 Types, true); 832 return llvm::ConstantStruct::get(SType, Elts); 833 } 834 835 return llvm::ConstantArray::get(AType, Elts); 836 } 837 838 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) { 839 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE); 840 } 841 842 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) { 843 return CGM.EmitNullConstant(E->getType()); 844 } 845 846 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) { 847 if (ILE->isTransparent()) 848 return Visit(ILE->getInit(0)); 849 850 if (ILE->getType()->isArrayType()) 851 return EmitArrayInitialization(ILE); 852 853 if (ILE->getType()->isRecordType()) 854 return EmitRecordInitialization(ILE); 855 856 return nullptr; 857 } 858 859 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base, 860 InitListExpr *Updater) { 861 QualType ExprType = Updater->getType(); 862 863 if (ExprType->isArrayType()) { 864 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ExprType)); 865 llvm::Type *ElemType = AType->getElementType(); 866 867 unsigned NumInitElements = Updater->getNumInits(); 868 unsigned NumElements = AType->getNumElements(); 869 870 std::vector<llvm::Constant *> Elts; 871 Elts.reserve(NumElements); 872 873 if (llvm::ConstantDataArray *DataArray = 874 dyn_cast<llvm::ConstantDataArray>(Base)) 875 for (unsigned i = 0; i != NumElements; ++i) 876 Elts.push_back(DataArray->getElementAsConstant(i)); 877 else if (llvm::ConstantArray *Array = 878 dyn_cast<llvm::ConstantArray>(Base)) 879 for (unsigned i = 0; i != NumElements; ++i) 880 Elts.push_back(Array->getOperand(i)); 881 else 882 return nullptr; // FIXME: other array types not implemented 883 884 llvm::Constant *fillC = nullptr; 885 if (Expr *filler = Updater->getArrayFiller()) 886 if (!isa<NoInitExpr>(filler)) 887 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF); 888 bool RewriteType = (fillC && fillC->getType() != ElemType); 889 890 for (unsigned i = 0; i != NumElements; ++i) { 891 Expr *Init = nullptr; 892 if (i < NumInitElements) 893 Init = Updater->getInit(i); 894 895 if (!Init && fillC) 896 Elts[i] = fillC; 897 else if (!Init || isa<NoInitExpr>(Init)) 898 ; // Do nothing. 899 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) 900 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE); 901 else 902 Elts[i] = CGM.EmitConstantExpr(Init, Init->getType(), CGF); 903 904 if (!Elts[i]) 905 return nullptr; 906 RewriteType |= (Elts[i]->getType() != ElemType); 907 } 908 909 if (RewriteType) { 910 std::vector<llvm::Type *> Types; 911 Types.reserve(NumElements); 912 for (unsigned i = 0; i != NumElements; ++i) 913 Types.push_back(Elts[i]->getType()); 914 llvm::StructType *SType = llvm::StructType::get(AType->getContext(), 915 Types, true); 916 return llvm::ConstantStruct::get(SType, Elts); 917 } 918 919 return llvm::ConstantArray::get(AType, Elts); 920 } 921 922 if (ExprType->isRecordType()) 923 return ConstStructBuilder::BuildStruct(CGM, CGF, this, 924 dyn_cast<llvm::ConstantStruct>(Base), Updater); 925 926 return nullptr; 927 } 928 929 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) { 930 return EmitDesignatedInitUpdater( 931 CGM.EmitConstantExpr(E->getBase(), E->getType(), CGF), 932 E->getUpdater()); 933 } 934 935 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) { 936 if (!E->getConstructor()->isTrivial()) 937 return nullptr; 938 939 QualType Ty = E->getType(); 940 941 // FIXME: We should not have to call getBaseElementType here. 942 const RecordType *RT = 943 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>(); 944 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 945 946 // If the class doesn't have a trivial destructor, we can't emit it as a 947 // constant expr. 948 if (!RD->hasTrivialDestructor()) 949 return nullptr; 950 951 // Only copy and default constructors can be trivial. 952 953 954 if (E->getNumArgs()) { 955 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument"); 956 assert(E->getConstructor()->isCopyOrMoveConstructor() && 957 "trivial ctor has argument but isn't a copy/move ctor"); 958 959 Expr *Arg = E->getArg(0); 960 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && 961 "argument to copy ctor is of wrong type"); 962 963 return Visit(Arg); 964 } 965 966 return CGM.EmitNullConstant(Ty); 967 } 968 969 llvm::Constant *VisitStringLiteral(StringLiteral *E) { 970 return CGM.GetConstantArrayFromStringLiteral(E); 971 } 972 973 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) { 974 // This must be an @encode initializing an array in a static initializer. 975 // Don't emit it as the address of the string, emit the string data itself 976 // as an inline array. 977 std::string Str; 978 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); 979 QualType T = E->getType(); 980 if (T->getTypeClass() == Type::TypeOfExpr) 981 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType(); 982 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 983 984 // Resize the string to the right size, adding zeros at the end, or 985 // truncating as needed. 986 Str.resize(CAT->getSize().getZExtValue(), '\0'); 987 return llvm::ConstantDataArray::getString(VMContext, Str, false); 988 } 989 990 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) { 991 return Visit(E->getSubExpr()); 992 } 993 994 // Utility methods 995 llvm::Type *ConvertType(QualType T) { 996 return CGM.getTypes().ConvertType(T); 997 } 998 999 public: 1000 ConstantAddress EmitLValue(APValue::LValueBase LVBase) { 1001 if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) { 1002 if (Decl->hasAttr<WeakRefAttr>()) 1003 return CGM.GetWeakRefReference(Decl); 1004 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl)) 1005 return ConstantAddress(CGM.GetAddrOfFunction(FD), CharUnits::One()); 1006 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) { 1007 // We can never refer to a variable with local storage. 1008 if (!VD->hasLocalStorage()) { 1009 CharUnits Align = CGM.getContext().getDeclAlign(VD); 1010 if (VD->isFileVarDecl() || VD->hasExternalStorage()) 1011 return ConstantAddress(CGM.GetAddrOfGlobalVar(VD), Align); 1012 else if (VD->isLocalVarDecl()) { 1013 auto Ptr = CGM.getOrCreateStaticVarDecl( 1014 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)); 1015 return ConstantAddress(Ptr, Align); 1016 } 1017 } 1018 } 1019 return ConstantAddress::invalid(); 1020 } 1021 1022 Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>()); 1023 switch (E->getStmtClass()) { 1024 default: break; 1025 case Expr::CompoundLiteralExprClass: { 1026 // Note that due to the nature of compound literals, this is guaranteed 1027 // to be the only use of the variable, so we just generate it here. 1028 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E); 1029 llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(), 1030 CLE->getType(), CGF); 1031 // FIXME: "Leaked" on failure. 1032 if (!C) return ConstantAddress::invalid(); 1033 1034 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType()); 1035 1036 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), 1037 E->getType().isConstant(CGM.getContext()), 1038 llvm::GlobalValue::InternalLinkage, 1039 C, ".compoundliteral", nullptr, 1040 llvm::GlobalVariable::NotThreadLocal, 1041 CGM.getContext().getTargetAddressSpace(E->getType())); 1042 GV->setAlignment(Align.getQuantity()); 1043 return ConstantAddress(GV, Align); 1044 } 1045 case Expr::StringLiteralClass: 1046 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E)); 1047 case Expr::ObjCEncodeExprClass: 1048 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E)); 1049 case Expr::ObjCStringLiteralClass: { 1050 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E); 1051 ConstantAddress C = 1052 CGM.getObjCRuntime().GenerateConstantString(SL->getString()); 1053 return C.getElementBitCast(ConvertType(E->getType())); 1054 } 1055 case Expr::PredefinedExprClass: { 1056 unsigned Type = cast<PredefinedExpr>(E)->getIdentType(); 1057 if (CGF) { 1058 LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E)); 1059 return cast<ConstantAddress>(Res.getAddress()); 1060 } else if (Type == PredefinedExpr::PrettyFunction) { 1061 return CGM.GetAddrOfConstantCString("top level", ".tmp"); 1062 } 1063 1064 return CGM.GetAddrOfConstantCString("", ".tmp"); 1065 } 1066 case Expr::AddrLabelExprClass: { 1067 assert(CGF && "Invalid address of label expression outside function."); 1068 llvm::Constant *Ptr = 1069 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel()); 1070 Ptr = llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType())); 1071 return ConstantAddress(Ptr, CharUnits::One()); 1072 } 1073 case Expr::CallExprClass: { 1074 CallExpr* CE = cast<CallExpr>(E); 1075 unsigned builtin = CE->getBuiltinCallee(); 1076 if (builtin != 1077 Builtin::BI__builtin___CFStringMakeConstantString && 1078 builtin != 1079 Builtin::BI__builtin___NSStringMakeConstantString) 1080 break; 1081 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts(); 1082 const StringLiteral *Literal = cast<StringLiteral>(Arg); 1083 if (builtin == 1084 Builtin::BI__builtin___NSStringMakeConstantString) { 1085 return CGM.getObjCRuntime().GenerateConstantString(Literal); 1086 } 1087 // FIXME: need to deal with UCN conversion issues. 1088 return CGM.GetAddrOfConstantCFString(Literal); 1089 } 1090 case Expr::BlockExprClass: { 1091 StringRef FunctionName; 1092 if (CGF) 1093 FunctionName = CGF->CurFn->getName(); 1094 else 1095 FunctionName = "global"; 1096 1097 // This is not really an l-value. 1098 llvm::Constant *Ptr = 1099 CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName); 1100 return ConstantAddress(Ptr, CGM.getPointerAlign()); 1101 } 1102 case Expr::CXXTypeidExprClass: { 1103 CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E); 1104 QualType T; 1105 if (Typeid->isTypeOperand()) 1106 T = Typeid->getTypeOperand(CGM.getContext()); 1107 else 1108 T = Typeid->getExprOperand()->getType(); 1109 return ConstantAddress(CGM.GetAddrOfRTTIDescriptor(T), 1110 CGM.getPointerAlign()); 1111 } 1112 case Expr::CXXUuidofExprClass: { 1113 return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E)); 1114 } 1115 case Expr::MaterializeTemporaryExprClass: { 1116 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E); 1117 assert(MTE->getStorageDuration() == SD_Static); 1118 SmallVector<const Expr *, 2> CommaLHSs; 1119 SmallVector<SubobjectAdjustment, 2> Adjustments; 1120 const Expr *Inner = MTE->GetTemporaryExpr() 1121 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 1122 return CGM.GetAddrOfGlobalTemporary(MTE, Inner); 1123 } 1124 } 1125 1126 return ConstantAddress::invalid(); 1127 } 1128 }; 1129 1130 } // end anonymous namespace. 1131 1132 bool ConstStructBuilder::Build(ConstExprEmitter *Emitter, 1133 llvm::ConstantStruct *Base, 1134 InitListExpr *Updater) { 1135 assert(Base && "base expression should not be empty"); 1136 1137 QualType ExprType = Updater->getType(); 1138 RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl(); 1139 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 1140 const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout( 1141 Base->getType()); 1142 unsigned FieldNo = -1; 1143 unsigned ElementNo = 0; 1144 1145 // Bail out if we have base classes. We could support these, but they only 1146 // arise in C++1z where we will have already constant folded most interesting 1147 // cases. FIXME: There are still a few more cases we can handle this way. 1148 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1149 if (CXXRD->getNumBases()) 1150 return false; 1151 1152 for (FieldDecl *Field : RD->fields()) { 1153 ++FieldNo; 1154 1155 if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field) 1156 continue; 1157 1158 // Skip anonymous bitfields. 1159 if (Field->isUnnamedBitfield()) 1160 continue; 1161 1162 llvm::Constant *EltInit = Base->getOperand(ElementNo); 1163 1164 // Bail out if the type of the ConstantStruct does not have the same layout 1165 // as the type of the InitListExpr. 1166 if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() || 1167 Layout.getFieldOffset(ElementNo) != 1168 BaseLayout->getElementOffsetInBits(ElementNo)) 1169 return false; 1170 1171 // Get the initializer. If we encounter an empty field or a NoInitExpr, 1172 // we use values from the base expression. 1173 Expr *Init = nullptr; 1174 if (ElementNo < Updater->getNumInits()) 1175 Init = Updater->getInit(ElementNo); 1176 1177 if (!Init || isa<NoInitExpr>(Init)) 1178 ; // Do nothing. 1179 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) 1180 EltInit = Emitter->EmitDesignatedInitUpdater(EltInit, ChildILE); 1181 else 1182 EltInit = CGM.EmitConstantExpr(Init, Field->getType(), CGF); 1183 1184 ++ElementNo; 1185 1186 if (!EltInit) 1187 return false; 1188 1189 if (!Field->isBitField()) 1190 AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit); 1191 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit)) 1192 AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI); 1193 else 1194 // Initializing a bitfield with a non-trivial constant? 1195 return false; 1196 } 1197 1198 return true; 1199 } 1200 1201 llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D, 1202 CodeGenFunction *CGF) { 1203 // Make a quick check if variable can be default NULL initialized 1204 // and avoid going through rest of code which may do, for c++11, 1205 // initialization of memory to all NULLs. 1206 if (!D.hasLocalStorage()) { 1207 QualType Ty = D.getType(); 1208 if (Ty->isArrayType()) 1209 Ty = Context.getBaseElementType(Ty); 1210 if (Ty->isRecordType()) 1211 if (const CXXConstructExpr *E = 1212 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) { 1213 const CXXConstructorDecl *CD = E->getConstructor(); 1214 if (CD->isTrivial() && CD->isDefaultConstructor()) 1215 return EmitNullConstant(D.getType()); 1216 } 1217 } 1218 1219 if (const APValue *Value = D.evaluateValue()) 1220 return EmitConstantValueForMemory(*Value, D.getType(), CGF); 1221 1222 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a 1223 // reference is a constant expression, and the reference binds to a temporary, 1224 // then constant initialization is performed. ConstExprEmitter will 1225 // incorrectly emit a prvalue constant in this case, and the calling code 1226 // interprets that as the (pointer) value of the reference, rather than the 1227 // desired value of the referee. 1228 if (D.getType()->isReferenceType()) 1229 return nullptr; 1230 1231 const Expr *E = D.getInit(); 1232 assert(E && "No initializer to emit"); 1233 1234 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E)); 1235 if (C && C->getType()->isIntegerTy(1)) { 1236 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); 1237 C = llvm::ConstantExpr::getZExt(C, BoolTy); 1238 } 1239 return C; 1240 } 1241 1242 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E, 1243 QualType DestType, 1244 CodeGenFunction *CGF) { 1245 Expr::EvalResult Result; 1246 1247 bool Success = false; 1248 1249 if (DestType->isReferenceType()) 1250 Success = E->EvaluateAsLValue(Result, Context); 1251 else 1252 Success = E->EvaluateAsRValue(Result, Context); 1253 1254 llvm::Constant *C = nullptr; 1255 if (Success && !Result.HasSideEffects) 1256 C = EmitConstantValue(Result.Val, DestType, CGF); 1257 else 1258 C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E)); 1259 1260 if (C && C->getType()->isIntegerTy(1)) { 1261 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType()); 1262 C = llvm::ConstantExpr::getZExt(C, BoolTy); 1263 } 1264 return C; 1265 } 1266 1267 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) { 1268 return getTargetCodeGenInfo().getNullPointer(*this, T, QT); 1269 } 1270 1271 llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value, 1272 QualType DestType, 1273 CodeGenFunction *CGF) { 1274 // For an _Atomic-qualified constant, we may need to add tail padding. 1275 if (auto *AT = DestType->getAs<AtomicType>()) { 1276 QualType InnerType = AT->getValueType(); 1277 auto *Inner = EmitConstantValue(Value, InnerType, CGF); 1278 1279 uint64_t InnerSize = Context.getTypeSize(InnerType); 1280 uint64_t OuterSize = Context.getTypeSize(DestType); 1281 if (InnerSize == OuterSize) 1282 return Inner; 1283 1284 assert(InnerSize < OuterSize && "emitted over-large constant for atomic"); 1285 llvm::Constant *Elts[] = { 1286 Inner, 1287 llvm::ConstantAggregateZero::get( 1288 llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8)) 1289 }; 1290 return llvm::ConstantStruct::getAnon(Elts); 1291 } 1292 1293 switch (Value.getKind()) { 1294 case APValue::Uninitialized: 1295 llvm_unreachable("Constant expressions should be initialized."); 1296 case APValue::LValue: { 1297 llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType); 1298 llvm::Constant *Offset = 1299 llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity()); 1300 1301 llvm::Constant *C = nullptr; 1302 1303 if (APValue::LValueBase LVBase = Value.getLValueBase()) { 1304 // An array can be represented as an lvalue referring to the base. 1305 if (isa<llvm::ArrayType>(DestTy)) { 1306 assert(Offset->isNullValue() && "offset on array initializer"); 1307 return ConstExprEmitter(*this, CGF).Visit( 1308 const_cast<Expr*>(LVBase.get<const Expr*>())); 1309 } 1310 1311 C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase).getPointer(); 1312 1313 // Apply offset if necessary. 1314 if (!Offset->isNullValue()) { 1315 unsigned AS = C->getType()->getPointerAddressSpace(); 1316 llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS); 1317 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy); 1318 Casted = llvm::ConstantExpr::getGetElementPtr(Int8Ty, Casted, Offset); 1319 C = llvm::ConstantExpr::getPointerCast(Casted, C->getType()); 1320 } 1321 1322 // Convert to the appropriate type; this could be an lvalue for 1323 // an integer. 1324 if (isa<llvm::PointerType>(DestTy)) 1325 return llvm::ConstantExpr::getPointerCast(C, DestTy); 1326 1327 return llvm::ConstantExpr::getPtrToInt(C, DestTy); 1328 } else { 1329 C = Offset; 1330 1331 // Convert to the appropriate type; this could be an lvalue for 1332 // an integer. 1333 if (auto PT = dyn_cast<llvm::PointerType>(DestTy)) { 1334 if (Value.isNullPointer()) 1335 return getNullPointer(PT, DestType); 1336 // Convert the integer to a pointer-sized integer before converting it 1337 // to a pointer. 1338 C = llvm::ConstantExpr::getIntegerCast( 1339 C, getDataLayout().getIntPtrType(DestTy), 1340 /*isSigned=*/false); 1341 return llvm::ConstantExpr::getIntToPtr(C, DestTy); 1342 } 1343 1344 // If the types don't match this should only be a truncate. 1345 if (C->getType() != DestTy) 1346 return llvm::ConstantExpr::getTrunc(C, DestTy); 1347 1348 return C; 1349 } 1350 } 1351 case APValue::Int: 1352 return llvm::ConstantInt::get(VMContext, Value.getInt()); 1353 case APValue::ComplexInt: { 1354 llvm::Constant *Complex[2]; 1355 1356 Complex[0] = llvm::ConstantInt::get(VMContext, 1357 Value.getComplexIntReal()); 1358 Complex[1] = llvm::ConstantInt::get(VMContext, 1359 Value.getComplexIntImag()); 1360 1361 // FIXME: the target may want to specify that this is packed. 1362 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(), 1363 Complex[1]->getType(), 1364 nullptr); 1365 return llvm::ConstantStruct::get(STy, Complex); 1366 } 1367 case APValue::Float: { 1368 const llvm::APFloat &Init = Value.getFloat(); 1369 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() && 1370 !Context.getLangOpts().NativeHalfType && 1371 !Context.getLangOpts().HalfArgsAndReturns) 1372 return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt()); 1373 else 1374 return llvm::ConstantFP::get(VMContext, Init); 1375 } 1376 case APValue::ComplexFloat: { 1377 llvm::Constant *Complex[2]; 1378 1379 Complex[0] = llvm::ConstantFP::get(VMContext, 1380 Value.getComplexFloatReal()); 1381 Complex[1] = llvm::ConstantFP::get(VMContext, 1382 Value.getComplexFloatImag()); 1383 1384 // FIXME: the target may want to specify that this is packed. 1385 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(), 1386 Complex[1]->getType(), 1387 nullptr); 1388 return llvm::ConstantStruct::get(STy, Complex); 1389 } 1390 case APValue::Vector: { 1391 unsigned NumElts = Value.getVectorLength(); 1392 SmallVector<llvm::Constant *, 4> Inits(NumElts); 1393 1394 for (unsigned I = 0; I != NumElts; ++I) { 1395 const APValue &Elt = Value.getVectorElt(I); 1396 if (Elt.isInt()) 1397 Inits[I] = llvm::ConstantInt::get(VMContext, Elt.getInt()); 1398 else if (Elt.isFloat()) 1399 Inits[I] = llvm::ConstantFP::get(VMContext, Elt.getFloat()); 1400 else 1401 llvm_unreachable("unsupported vector element type"); 1402 } 1403 return llvm::ConstantVector::get(Inits); 1404 } 1405 case APValue::AddrLabelDiff: { 1406 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS(); 1407 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS(); 1408 llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF); 1409 llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF); 1410 1411 // Compute difference 1412 llvm::Type *ResultType = getTypes().ConvertType(DestType); 1413 LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy); 1414 RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy); 1415 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS); 1416 1417 // LLVM is a bit sensitive about the exact format of the 1418 // address-of-label difference; make sure to truncate after 1419 // the subtraction. 1420 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType); 1421 } 1422 case APValue::Struct: 1423 case APValue::Union: 1424 return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType); 1425 case APValue::Array: { 1426 const ArrayType *CAT = Context.getAsArrayType(DestType); 1427 unsigned NumElements = Value.getArraySize(); 1428 unsigned NumInitElts = Value.getArrayInitializedElts(); 1429 1430 // Emit array filler, if there is one. 1431 llvm::Constant *Filler = nullptr; 1432 if (Value.hasArrayFiller()) 1433 Filler = EmitConstantValueForMemory(Value.getArrayFiller(), 1434 CAT->getElementType(), CGF); 1435 1436 // Emit initializer elements. 1437 llvm::Type *CommonElementType = 1438 getTypes().ConvertType(CAT->getElementType()); 1439 1440 // Try to use a ConstantAggregateZero if we can. 1441 if (Filler && Filler->isNullValue() && !NumInitElts) { 1442 llvm::ArrayType *AType = 1443 llvm::ArrayType::get(CommonElementType, NumElements); 1444 return llvm::ConstantAggregateZero::get(AType); 1445 } 1446 1447 std::vector<llvm::Constant*> Elts; 1448 Elts.reserve(NumElements); 1449 for (unsigned I = 0; I < NumElements; ++I) { 1450 llvm::Constant *C = Filler; 1451 if (I < NumInitElts) 1452 C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I), 1453 CAT->getElementType(), CGF); 1454 else 1455 assert(Filler && "Missing filler for implicit elements of initializer"); 1456 if (I == 0) 1457 CommonElementType = C->getType(); 1458 else if (C->getType() != CommonElementType) 1459 CommonElementType = nullptr; 1460 Elts.push_back(C); 1461 } 1462 1463 if (!CommonElementType) { 1464 // FIXME: Try to avoid packing the array 1465 std::vector<llvm::Type*> Types; 1466 Types.reserve(NumElements); 1467 for (unsigned i = 0, e = Elts.size(); i < e; ++i) 1468 Types.push_back(Elts[i]->getType()); 1469 llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true); 1470 return llvm::ConstantStruct::get(SType, Elts); 1471 } 1472 1473 llvm::ArrayType *AType = 1474 llvm::ArrayType::get(CommonElementType, NumElements); 1475 return llvm::ConstantArray::get(AType, Elts); 1476 } 1477 case APValue::MemberPointer: 1478 return getCXXABI().EmitMemberPointer(Value, DestType); 1479 } 1480 llvm_unreachable("Unknown APValue kind"); 1481 } 1482 1483 llvm::Constant * 1484 CodeGenModule::EmitConstantValueForMemory(const APValue &Value, 1485 QualType DestType, 1486 CodeGenFunction *CGF) { 1487 llvm::Constant *C = EmitConstantValue(Value, DestType, CGF); 1488 if (C->getType()->isIntegerTy(1)) { 1489 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType); 1490 C = llvm::ConstantExpr::getZExt(C, BoolTy); 1491 } 1492 return C; 1493 } 1494 1495 ConstantAddress 1496 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) { 1497 assert(E->isFileScope() && "not a file-scope compound literal expr"); 1498 return ConstExprEmitter(*this, nullptr).EmitLValue(E); 1499 } 1500 1501 llvm::Constant * 1502 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) { 1503 // Member pointer constants always have a very particular form. 1504 const MemberPointerType *type = cast<MemberPointerType>(uo->getType()); 1505 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl(); 1506 1507 // A member function pointer. 1508 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl)) 1509 return getCXXABI().EmitMemberFunctionPointer(method); 1510 1511 // Otherwise, a member data pointer. 1512 uint64_t fieldOffset = getContext().getFieldOffset(decl); 1513 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset); 1514 return getCXXABI().EmitMemberDataPointer(type, chars); 1515 } 1516 1517 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 1518 llvm::Type *baseType, 1519 const CXXRecordDecl *base); 1520 1521 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, 1522 const RecordDecl *record, 1523 bool asCompleteObject) { 1524 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record); 1525 llvm::StructType *structure = 1526 (asCompleteObject ? layout.getLLVMType() 1527 : layout.getBaseSubobjectLLVMType()); 1528 1529 unsigned numElements = structure->getNumElements(); 1530 std::vector<llvm::Constant *> elements(numElements); 1531 1532 auto CXXR = dyn_cast<CXXRecordDecl>(record); 1533 // Fill in all the bases. 1534 if (CXXR) { 1535 for (const auto &I : CXXR->bases()) { 1536 if (I.isVirtual()) { 1537 // Ignore virtual bases; if we're laying out for a complete 1538 // object, we'll lay these out later. 1539 continue; 1540 } 1541 1542 const CXXRecordDecl *base = 1543 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1544 1545 // Ignore empty bases. 1546 if (base->isEmpty() || 1547 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize() 1548 .isZero()) 1549 continue; 1550 1551 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base); 1552 llvm::Type *baseType = structure->getElementType(fieldIndex); 1553 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 1554 } 1555 } 1556 1557 // Fill in all the fields. 1558 for (const auto *Field : record->fields()) { 1559 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we 1560 // will fill in later.) 1561 if (!Field->isBitField()) { 1562 unsigned fieldIndex = layout.getLLVMFieldNo(Field); 1563 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType()); 1564 } 1565 1566 // For unions, stop after the first named field. 1567 if (record->isUnion()) { 1568 if (Field->getIdentifier()) 1569 break; 1570 if (const auto *FieldRD = 1571 dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl())) 1572 if (FieldRD->findFirstNamedDataMember()) 1573 break; 1574 } 1575 } 1576 1577 // Fill in the virtual bases, if we're working with the complete object. 1578 if (CXXR && asCompleteObject) { 1579 for (const auto &I : CXXR->vbases()) { 1580 const CXXRecordDecl *base = 1581 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1582 1583 // Ignore empty bases. 1584 if (base->isEmpty()) 1585 continue; 1586 1587 unsigned fieldIndex = layout.getVirtualBaseIndex(base); 1588 1589 // We might have already laid this field out. 1590 if (elements[fieldIndex]) continue; 1591 1592 llvm::Type *baseType = structure->getElementType(fieldIndex); 1593 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 1594 } 1595 } 1596 1597 // Now go through all other fields and zero them out. 1598 for (unsigned i = 0; i != numElements; ++i) { 1599 if (!elements[i]) 1600 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i)); 1601 } 1602 1603 return llvm::ConstantStruct::get(structure, elements); 1604 } 1605 1606 /// Emit the null constant for a base subobject. 1607 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 1608 llvm::Type *baseType, 1609 const CXXRecordDecl *base) { 1610 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base); 1611 1612 // Just zero out bases that don't have any pointer to data members. 1613 if (baseLayout.isZeroInitializableAsBase()) 1614 return llvm::Constant::getNullValue(baseType); 1615 1616 // Otherwise, we can just use its null constant. 1617 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false); 1618 } 1619 1620 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { 1621 if (T->getAs<PointerType>()) 1622 return getNullPointer( 1623 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T); 1624 1625 if (getTypes().isZeroInitializable(T)) 1626 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); 1627 1628 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { 1629 llvm::ArrayType *ATy = 1630 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); 1631 1632 QualType ElementTy = CAT->getElementType(); 1633 1634 llvm::Constant *Element = EmitNullConstant(ElementTy); 1635 unsigned NumElements = CAT->getSize().getZExtValue(); 1636 SmallVector<llvm::Constant *, 8> Array(NumElements, Element); 1637 return llvm::ConstantArray::get(ATy, Array); 1638 } 1639 1640 if (const RecordType *RT = T->getAs<RecordType>()) 1641 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true); 1642 1643 assert(T->isMemberDataPointerType() && 1644 "Should only see pointers to data members here!"); 1645 1646 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>()); 1647 } 1648 1649 llvm::Constant * 1650 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) { 1651 return ::EmitNullConstant(*this, Record, false); 1652 } 1653