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