AsmPrinter.cpp revision 263763
1//===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===// 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 file implements the AsmPrinter class. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "asm-printer" 15#include "llvm/CodeGen/AsmPrinter.h" 16#include "DwarfDebug.h" 17#include "DwarfException.h" 18#include "llvm/ADT/SmallString.h" 19#include "llvm/ADT/Statistic.h" 20#include "llvm/Analysis/ConstantFolding.h" 21#include "llvm/Assembly/Writer.h" 22#include "llvm/CodeGen/GCMetadataPrinter.h" 23#include "llvm/CodeGen/MachineConstantPool.h" 24#include "llvm/CodeGen/MachineFrameInfo.h" 25#include "llvm/CodeGen/MachineFunction.h" 26#include "llvm/CodeGen/MachineInstrBundle.h" 27#include "llvm/CodeGen/MachineJumpTableInfo.h" 28#include "llvm/CodeGen/MachineLoopInfo.h" 29#include "llvm/CodeGen/MachineModuleInfo.h" 30#include "llvm/DebugInfo.h" 31#include "llvm/IR/DataLayout.h" 32#include "llvm/IR/Module.h" 33#include "llvm/IR/Operator.h" 34#include "llvm/MC/MCAsmInfo.h" 35#include "llvm/MC/MCContext.h" 36#include "llvm/MC/MCExpr.h" 37#include "llvm/MC/MCInst.h" 38#include "llvm/MC/MCSection.h" 39#include "llvm/MC/MCStreamer.h" 40#include "llvm/MC/MCSymbol.h" 41#include "llvm/Support/ErrorHandling.h" 42#include "llvm/Support/Format.h" 43#include "llvm/Support/MathExtras.h" 44#include "llvm/Support/Timer.h" 45#include "llvm/Target/Mangler.h" 46#include "llvm/Target/TargetFrameLowering.h" 47#include "llvm/Target/TargetInstrInfo.h" 48#include "llvm/Target/TargetLowering.h" 49#include "llvm/Target/TargetLoweringObjectFile.h" 50#include "llvm/Target/TargetOptions.h" 51#include "llvm/Target/TargetRegisterInfo.h" 52#include "llvm/Transforms/Utils/GlobalStatus.h" 53using namespace llvm; 54 55static const char *const DWARFGroupName = "DWARF Emission"; 56static const char *const DbgTimerName = "DWARF Debug Writer"; 57static const char *const EHTimerName = "DWARF Exception Writer"; 58 59STATISTIC(EmittedInsts, "Number of machine instrs printed"); 60 61char AsmPrinter::ID = 0; 62 63typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type; 64static gcp_map_type &getGCMap(void *&P) { 65 if (P == 0) 66 P = new gcp_map_type(); 67 return *(gcp_map_type*)P; 68} 69 70 71/// getGVAlignmentLog2 - Return the alignment to use for the specified global 72/// value in log2 form. This rounds up to the preferred alignment if possible 73/// and legal. 74static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD, 75 unsigned InBits = 0) { 76 unsigned NumBits = 0; 77 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 78 NumBits = TD.getPreferredAlignmentLog(GVar); 79 80 // If InBits is specified, round it to it. 81 if (InBits > NumBits) 82 NumBits = InBits; 83 84 // If the GV has a specified alignment, take it into account. 85 if (GV->getAlignment() == 0) 86 return NumBits; 87 88 unsigned GVAlign = Log2_32(GV->getAlignment()); 89 90 // If the GVAlign is larger than NumBits, or if we are required to obey 91 // NumBits because the GV has an assigned section, obey it. 92 if (GVAlign > NumBits || GV->hasSection()) 93 NumBits = GVAlign; 94 return NumBits; 95} 96 97AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer) 98 : MachineFunctionPass(ID), 99 TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()), 100 OutContext(Streamer.getContext()), 101 OutStreamer(Streamer), 102 LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) { 103 DD = 0; DE = 0; MMI = 0; LI = 0; MF = 0; 104 CurrentFnSym = CurrentFnSymForSize = 0; 105 GCMetadataPrinters = 0; 106 VerboseAsm = Streamer.isVerboseAsm(); 107} 108 109AsmPrinter::~AsmPrinter() { 110 assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized"); 111 112 if (GCMetadataPrinters != 0) { 113 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 114 115 for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I) 116 delete I->second; 117 delete &GCMap; 118 GCMetadataPrinters = 0; 119 } 120 121 delete &OutStreamer; 122} 123 124/// getFunctionNumber - Return a unique ID for the current function. 125/// 126unsigned AsmPrinter::getFunctionNumber() const { 127 return MF->getFunctionNumber(); 128} 129 130const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 131 return TM.getTargetLowering()->getObjFileLowering(); 132} 133 134/// getDataLayout - Return information about data layout. 135const DataLayout &AsmPrinter::getDataLayout() const { 136 return *TM.getDataLayout(); 137} 138 139StringRef AsmPrinter::getTargetTriple() const { 140 return TM.getTargetTriple(); 141} 142 143/// getCurrentSection() - Return the current section we are emitting to. 144const MCSection *AsmPrinter::getCurrentSection() const { 145 return OutStreamer.getCurrentSection().first; 146} 147 148 149 150void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 151 AU.setPreservesAll(); 152 MachineFunctionPass::getAnalysisUsage(AU); 153 AU.addRequired<MachineModuleInfo>(); 154 AU.addRequired<GCModuleInfo>(); 155 if (isVerbose()) 156 AU.addRequired<MachineLoopInfo>(); 157} 158 159bool AsmPrinter::doInitialization(Module &M) { 160 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 161 MMI->AnalyzeModule(M); 162 163 // Initialize TargetLoweringObjectFile. 164 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 165 .Initialize(OutContext, TM); 166 167 OutStreamer.InitStreamer(); 168 169 Mang = new Mangler(&TM); 170 171 // Allow the target to emit any magic that it wants at the start of the file. 172 EmitStartOfAsmFile(M); 173 174 // Very minimal debug info. It is ignored if we emit actual debug info. If we 175 // don't, this at least helps the user find where a global came from. 176 if (MAI->hasSingleParameterDotFile()) { 177 // .file "foo.c" 178 OutStreamer.EmitFileDirective(M.getModuleIdentifier()); 179 } 180 181 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 182 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 183 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I) 184 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 185 MP->beginAssembly(*this); 186 187 // Emit module-level inline asm if it exists. 188 if (!M.getModuleInlineAsm().empty()) { 189 OutStreamer.AddComment("Start of file scope inline assembly"); 190 OutStreamer.AddBlankLine(); 191 EmitInlineAsm(M.getModuleInlineAsm()+"\n"); 192 OutStreamer.AddComment("End of file scope inline assembly"); 193 OutStreamer.AddBlankLine(); 194 } 195 196 if (MAI->doesSupportDebugInformation()) 197 DD = new DwarfDebug(this, &M); 198 199 switch (MAI->getExceptionHandlingType()) { 200 case ExceptionHandling::None: 201 return false; 202 case ExceptionHandling::SjLj: 203 case ExceptionHandling::DwarfCFI: 204 DE = new DwarfCFIException(this); 205 return false; 206 case ExceptionHandling::ARM: 207 DE = new ARMException(this); 208 return false; 209 case ExceptionHandling::Win64: 210 DE = new Win64Exception(this); 211 return false; 212 } 213 214 llvm_unreachable("Unknown exception type."); 215} 216 217void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 218 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 219 switch (Linkage) { 220 case GlobalValue::CommonLinkage: 221 case GlobalValue::LinkOnceAnyLinkage: 222 case GlobalValue::LinkOnceODRLinkage: 223 case GlobalValue::WeakAnyLinkage: 224 case GlobalValue::WeakODRLinkage: 225 case GlobalValue::LinkerPrivateWeakLinkage: 226 if (MAI->getWeakDefDirective() != 0) { 227 // .globl _foo 228 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 229 230 bool CanBeHidden = false; 231 232 if (Linkage == GlobalValue::LinkOnceODRLinkage) { 233 if (GV->hasUnnamedAddr()) { 234 CanBeHidden = true; 235 } else { 236 GlobalStatus GS; 237 if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared) 238 CanBeHidden = true; 239 } 240 } 241 242 if (!CanBeHidden) 243 // .weak_definition _foo 244 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition); 245 else 246 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 247 } else if (MAI->getLinkOnceDirective() != 0) { 248 // .globl _foo 249 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 250 //NOTE: linkonce is handled by the section the symbol was assigned to. 251 } else { 252 // .weak _foo 253 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak); 254 } 255 return; 256 case GlobalValue::DLLExportLinkage: 257 case GlobalValue::AppendingLinkage: 258 // FIXME: appending linkage variables should go into a section of 259 // their name or something. For now, just emit them as external. 260 case GlobalValue::ExternalLinkage: 261 // If external or appending, declare as a global symbol. 262 // .globl _foo 263 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 264 return; 265 case GlobalValue::PrivateLinkage: 266 case GlobalValue::InternalLinkage: 267 case GlobalValue::LinkerPrivateLinkage: 268 return; 269 case GlobalValue::AvailableExternallyLinkage: 270 llvm_unreachable("Should never emit this"); 271 case GlobalValue::DLLImportLinkage: 272 case GlobalValue::ExternalWeakLinkage: 273 llvm_unreachable("Don't know how to emit these"); 274 } 275 llvm_unreachable("Unknown linkage type!"); 276} 277 278MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 279 return getObjFileLowering().getSymbol(*Mang, GV); 280} 281 282/// EmitGlobalVariable - Emit the specified global variable to the .s file. 283void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 284 if (GV->hasInitializer()) { 285 // Check to see if this is a special global used by LLVM, if so, emit it. 286 if (EmitSpecialLLVMGlobal(GV)) 287 return; 288 289 if (isVerbose()) { 290 WriteAsOperand(OutStreamer.GetCommentOS(), GV, 291 /*PrintType=*/false, GV->getParent()); 292 OutStreamer.GetCommentOS() << '\n'; 293 } 294 } 295 296 MCSymbol *GVSym = getSymbol(GV); 297 EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration()); 298 299 if (!GV->hasInitializer()) // External globals require no extra code. 300 return; 301 302 if (MAI->hasDotTypeDotSizeDirective()) 303 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject); 304 305 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 306 307 const DataLayout *DL = TM.getDataLayout(); 308 uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType()); 309 310 // If the alignment is specified, we *must* obey it. Overaligning a global 311 // with a specified alignment is a prompt way to break globals emitted to 312 // sections and expected to be contiguous (e.g. ObjC metadata). 313 unsigned AlignLog = getGVAlignmentLog2(GV, *DL); 314 315 if (DD) 316 DD->setSymbolSize(GVSym, Size); 317 318 // Handle common and BSS local symbols (.lcomm). 319 if (GVKind.isCommon() || GVKind.isBSSLocal()) { 320 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 321 unsigned Align = 1 << AlignLog; 322 323 // Handle common symbols. 324 if (GVKind.isCommon()) { 325 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 326 Align = 0; 327 328 // .comm _foo, 42, 4 329 OutStreamer.EmitCommonSymbol(GVSym, Size, Align); 330 return; 331 } 332 333 // Handle local BSS symbols. 334 if (MAI->hasMachoZeroFillDirective()) { 335 const MCSection *TheSection = 336 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM); 337 // .zerofill __DATA, __bss, _foo, 400, 5 338 OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align); 339 return; 340 } 341 342 // Use .lcomm only if it supports user-specified alignment. 343 // Otherwise, while it would still be correct to use .lcomm in some 344 // cases (e.g. when Align == 1), the external assembler might enfore 345 // some -unknown- default alignment behavior, which could cause 346 // spurious differences between external and integrated assembler. 347 // Prefer to simply fall back to .local / .comm in this case. 348 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 349 // .lcomm _foo, 42 350 OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align); 351 return; 352 } 353 354 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 355 Align = 0; 356 357 // .local _foo 358 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local); 359 // .comm _foo, 42, 4 360 OutStreamer.EmitCommonSymbol(GVSym, Size, Align); 361 return; 362 } 363 364 const MCSection *TheSection = 365 getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM); 366 367 // Handle the zerofill directive on darwin, which is a special form of BSS 368 // emission. 369 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) { 370 if (Size == 0) Size = 1; // zerofill of 0 bytes is undefined. 371 372 // .globl _foo 373 OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global); 374 // .zerofill __DATA, __common, _foo, 400, 5 375 OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog); 376 return; 377 } 378 379 // Handle thread local data for mach-o which requires us to output an 380 // additional structure of data and mangle the original symbol so that we 381 // can reference it later. 382 // 383 // TODO: This should become an "emit thread local global" method on TLOF. 384 // All of this macho specific stuff should be sunk down into TLOFMachO and 385 // stuff like "TLSExtraDataSection" should no longer be part of the parent 386 // TLOF class. This will also make it more obvious that stuff like 387 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 388 // specific code. 389 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 390 // Emit the .tbss symbol 391 MCSymbol *MangSym = 392 OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 393 394 if (GVKind.isThreadBSS()) { 395 TheSection = getObjFileLowering().getTLSBSSSection(); 396 OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog); 397 } else if (GVKind.isThreadData()) { 398 OutStreamer.SwitchSection(TheSection); 399 400 EmitAlignment(AlignLog, GV); 401 OutStreamer.EmitLabel(MangSym); 402 403 EmitGlobalConstant(GV->getInitializer()); 404 } 405 406 OutStreamer.AddBlankLine(); 407 408 // Emit the variable struct for the runtime. 409 const MCSection *TLVSect 410 = getObjFileLowering().getTLSExtraDataSection(); 411 412 OutStreamer.SwitchSection(TLVSect); 413 // Emit the linkage here. 414 EmitLinkage(GV, GVSym); 415 OutStreamer.EmitLabel(GVSym); 416 417 // Three pointers in size: 418 // - __tlv_bootstrap - used to make sure support exists 419 // - spare pointer, used when mapped by the runtime 420 // - pointer to mangled symbol above with initializer 421 unsigned PtrSize = DL->getPointerTypeSize(GV->getType()); 422 OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 423 PtrSize); 424 OutStreamer.EmitIntValue(0, PtrSize); 425 OutStreamer.EmitSymbolValue(MangSym, PtrSize); 426 427 OutStreamer.AddBlankLine(); 428 return; 429 } 430 431 OutStreamer.SwitchSection(TheSection); 432 433 EmitLinkage(GV, GVSym); 434 EmitAlignment(AlignLog, GV); 435 436 OutStreamer.EmitLabel(GVSym); 437 438 EmitGlobalConstant(GV->getInitializer()); 439 440 if (MAI->hasDotTypeDotSizeDirective()) 441 // .size foo, 42 442 OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext)); 443 444 OutStreamer.AddBlankLine(); 445} 446 447/// EmitFunctionHeader - This method emits the header for the current 448/// function. 449void AsmPrinter::EmitFunctionHeader() { 450 // Print out constants referenced by the function 451 EmitConstantPool(); 452 453 // Print the 'header' of function. 454 const Function *F = MF->getFunction(); 455 456 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM)); 457 EmitVisibility(CurrentFnSym, F->getVisibility()); 458 459 EmitLinkage(F, CurrentFnSym); 460 EmitAlignment(MF->getAlignment(), F); 461 462 if (MAI->hasDotTypeDotSizeDirective()) 463 OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 464 465 if (isVerbose()) { 466 WriteAsOperand(OutStreamer.GetCommentOS(), F, 467 /*PrintType=*/false, F->getParent()); 468 OutStreamer.GetCommentOS() << '\n'; 469 } 470 471 // Emit the CurrentFnSym. This is a virtual function to allow targets to 472 // do their wild and crazy things as required. 473 EmitFunctionEntryLabel(); 474 475 // If the function had address-taken blocks that got deleted, then we have 476 // references to the dangling symbols. Emit them at the start of the function 477 // so that we don't get references to undefined symbols. 478 std::vector<MCSymbol*> DeadBlockSyms; 479 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms); 480 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) { 481 OutStreamer.AddComment("Address taken block that was later removed"); 482 OutStreamer.EmitLabel(DeadBlockSyms[i]); 483 } 484 485 // Emit pre-function debug and/or EH information. 486 if (DE) { 487 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled); 488 DE->BeginFunction(MF); 489 } 490 if (DD) { 491 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 492 DD->beginFunction(MF); 493 } 494 495 // Emit the prefix data. 496 if (F->hasPrefixData()) 497 EmitGlobalConstant(F->getPrefixData()); 498} 499 500/// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 501/// function. This can be overridden by targets as required to do custom stuff. 502void AsmPrinter::EmitFunctionEntryLabel() { 503 // The function label could have already been emitted if two symbols end up 504 // conflicting due to asm renaming. Detect this and emit an error. 505 if (CurrentFnSym->isUndefined()) 506 return OutStreamer.EmitLabel(CurrentFnSym); 507 508 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 509 "' label emitted multiple times to assembly file"); 510} 511 512/// emitComments - Pretty-print comments for instructions. 513static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 514 const MachineFunction *MF = MI.getParent()->getParent(); 515 const TargetMachine &TM = MF->getTarget(); 516 517 // Check for spills and reloads 518 int FI; 519 520 const MachineFrameInfo *FrameInfo = MF->getFrameInfo(); 521 522 // We assume a single instruction only has a spill or reload, not 523 // both. 524 const MachineMemOperand *MMO; 525 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) { 526 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 527 MMO = *MI.memoperands_begin(); 528 CommentOS << MMO->getSize() << "-byte Reload\n"; 529 } 530 } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) { 531 if (FrameInfo->isSpillSlotObjectIndex(FI)) 532 CommentOS << MMO->getSize() << "-byte Folded Reload\n"; 533 } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) { 534 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 535 MMO = *MI.memoperands_begin(); 536 CommentOS << MMO->getSize() << "-byte Spill\n"; 537 } 538 } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) { 539 if (FrameInfo->isSpillSlotObjectIndex(FI)) 540 CommentOS << MMO->getSize() << "-byte Folded Spill\n"; 541 } 542 543 // Check for spill-induced copies 544 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 545 CommentOS << " Reload Reuse\n"; 546} 547 548/// emitImplicitDef - This method emits the specified machine instruction 549/// that is an implicit def. 550void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 551 unsigned RegNo = MI->getOperand(0).getReg(); 552 OutStreamer.AddComment(Twine("implicit-def: ") + 553 TM.getRegisterInfo()->getName(RegNo)); 554 OutStreamer.AddBlankLine(); 555} 556 557static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 558 std::string Str = "kill:"; 559 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 560 const MachineOperand &Op = MI->getOperand(i); 561 assert(Op.isReg() && "KILL instruction must have only register operands"); 562 Str += ' '; 563 Str += AP.TM.getRegisterInfo()->getName(Op.getReg()); 564 Str += (Op.isDef() ? "<def>" : "<kill>"); 565 } 566 AP.OutStreamer.AddComment(Str); 567 AP.OutStreamer.AddBlankLine(); 568} 569 570/// emitDebugValueComment - This method handles the target-independent form 571/// of DBG_VALUE, returning true if it was able to do so. A false return 572/// means the target will need to handle MI in EmitInstruction. 573static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 574 // This code handles only the 3-operand target-independent form. 575 if (MI->getNumOperands() != 3) 576 return false; 577 578 SmallString<128> Str; 579 raw_svector_ostream OS(Str); 580 OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: "; 581 582 // cast away const; DIetc do not take const operands for some reason. 583 DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata())); 584 if (V.getContext().isSubprogram()) { 585 StringRef Name = DISubprogram(V.getContext()).getDisplayName(); 586 if (!Name.empty()) 587 OS << Name << ":"; 588 } 589 OS << V.getName() << " <- "; 590 591 // The second operand is only an offset if it's an immediate. 592 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm(); 593 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0; 594 595 // Register or immediate value. Register 0 means undef. 596 if (MI->getOperand(0).isFPImm()) { 597 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 598 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 599 OS << (double)APF.convertToFloat(); 600 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 601 OS << APF.convertToDouble(); 602 } else { 603 // There is no good way to print long double. Convert a copy to 604 // double. Ah well, it's only a comment. 605 bool ignored; 606 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 607 &ignored); 608 OS << "(long double) " << APF.convertToDouble(); 609 } 610 } else if (MI->getOperand(0).isImm()) { 611 OS << MI->getOperand(0).getImm(); 612 } else if (MI->getOperand(0).isCImm()) { 613 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 614 } else { 615 unsigned Reg; 616 if (MI->getOperand(0).isReg()) { 617 Reg = MI->getOperand(0).getReg(); 618 } else { 619 assert(MI->getOperand(0).isFI() && "Unknown operand type"); 620 const TargetFrameLowering *TFI = AP.TM.getFrameLowering(); 621 Offset += TFI->getFrameIndexReference(*AP.MF, 622 MI->getOperand(0).getIndex(), Reg); 623 Deref = true; 624 } 625 if (Reg == 0) { 626 // Suppress offset, it is not meaningful here. 627 OS << "undef"; 628 // NOTE: Want this comment at start of line, don't emit with AddComment. 629 AP.OutStreamer.EmitRawText(OS.str()); 630 return true; 631 } 632 if (Deref) 633 OS << '['; 634 OS << AP.TM.getRegisterInfo()->getName(Reg); 635 } 636 637 if (Deref) 638 OS << '+' << Offset << ']'; 639 640 // NOTE: Want this comment at start of line, don't emit with AddComment. 641 AP.OutStreamer.EmitRawText(OS.str()); 642 return true; 643} 644 645AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() { 646 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 647 MF->getFunction()->needsUnwindTableEntry()) 648 return CFI_M_EH; 649 650 if (MMI->hasDebugInfo()) 651 return CFI_M_Debug; 652 653 return CFI_M_None; 654} 655 656bool AsmPrinter::needsSEHMoves() { 657 return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 && 658 MF->getFunction()->needsUnwindTableEntry(); 659} 660 661bool AsmPrinter::needsRelocationsForDwarfStringPool() const { 662 return MAI->doesDwarfUseRelocationsAcrossSections(); 663} 664 665void AsmPrinter::emitPrologLabel(const MachineInstr &MI) { 666 const MCSymbol *Label = MI.getOperand(0).getMCSymbol(); 667 668 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI) 669 return; 670 671 if (needsCFIMoves() == CFI_M_None) 672 return; 673 674 if (MMI->getCompactUnwindEncoding() != 0) 675 OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding()); 676 677 const MachineModuleInfo &MMI = MF->getMMI(); 678 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions(); 679 bool FoundOne = false; 680 (void)FoundOne; 681 for (std::vector<MCCFIInstruction>::const_iterator I = Instrs.begin(), 682 E = Instrs.end(); I != E; ++I) { 683 if (I->getLabel() == Label) { 684 emitCFIInstruction(*I); 685 FoundOne = true; 686 } 687 } 688 assert(FoundOne); 689} 690 691/// EmitFunctionBody - This method emits the body and trailer for a 692/// function. 693void AsmPrinter::EmitFunctionBody() { 694 // Emit target-specific gunk before the function body. 695 EmitFunctionBodyStart(); 696 697 bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo(); 698 699 // Print out code for the function. 700 bool HasAnyRealCode = false; 701 const MachineInstr *LastMI = 0; 702 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); 703 I != E; ++I) { 704 // Print a label for the basic block. 705 EmitBasicBlockStart(I); 706 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end(); 707 II != IE; ++II) { 708 LastMI = II; 709 710 // Print the assembly for the instruction. 711 if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() && 712 !II->isDebugValue()) { 713 HasAnyRealCode = true; 714 ++EmittedInsts; 715 } 716 717 if (ShouldPrintDebugScopes) { 718 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 719 DD->beginInstruction(II); 720 } 721 722 if (isVerbose()) 723 emitComments(*II, OutStreamer.GetCommentOS()); 724 725 switch (II->getOpcode()) { 726 case TargetOpcode::PROLOG_LABEL: 727 emitPrologLabel(*II); 728 break; 729 730 case TargetOpcode::EH_LABEL: 731 case TargetOpcode::GC_LABEL: 732 OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol()); 733 break; 734 case TargetOpcode::INLINEASM: 735 EmitInlineAsm(II); 736 break; 737 case TargetOpcode::DBG_VALUE: 738 if (isVerbose()) { 739 if (!emitDebugValueComment(II, *this)) 740 EmitInstruction(II); 741 } 742 break; 743 case TargetOpcode::IMPLICIT_DEF: 744 if (isVerbose()) emitImplicitDef(II); 745 break; 746 case TargetOpcode::KILL: 747 if (isVerbose()) emitKill(II, *this); 748 break; 749 default: 750 if (!TM.hasMCUseLoc()) 751 MCLineEntry::Make(&OutStreamer, getCurrentSection()); 752 753 EmitInstruction(II); 754 break; 755 } 756 757 if (ShouldPrintDebugScopes) { 758 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 759 DD->endInstruction(II); 760 } 761 } 762 } 763 764 // If the last instruction was a prolog label, then we have a situation where 765 // we emitted a prolog but no function body. This results in the ending prolog 766 // label equaling the end of function label and an invalid "row" in the 767 // FDE. We need to emit a noop in this situation so that the FDE's rows are 768 // valid. 769 bool RequiresNoop = LastMI && LastMI->isPrologLabel(); 770 771 // If the function is empty and the object file uses .subsections_via_symbols, 772 // then we need to emit *something* to the function body to prevent the 773 // labels from collapsing together. Just emit a noop. 774 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) { 775 MCInst Noop; 776 TM.getInstrInfo()->getNoopForMachoTarget(Noop); 777 if (Noop.getOpcode()) { 778 OutStreamer.AddComment("avoids zero-length function"); 779 OutStreamer.EmitInstruction(Noop); 780 } else // Target not mc-ized yet. 781 OutStreamer.EmitRawText(StringRef("\tnop\n")); 782 } 783 784 const Function *F = MF->getFunction(); 785 for (Function::const_iterator i = F->begin(), e = F->end(); i != e; ++i) { 786 const BasicBlock *BB = i; 787 if (!BB->hasAddressTaken()) 788 continue; 789 MCSymbol *Sym = GetBlockAddressSymbol(BB); 790 if (Sym->isDefined()) 791 continue; 792 OutStreamer.AddComment("Address of block that was removed by CodeGen"); 793 OutStreamer.EmitLabel(Sym); 794 } 795 796 // Emit target-specific gunk after the function body. 797 EmitFunctionBodyEnd(); 798 799 // If the target wants a .size directive for the size of the function, emit 800 // it. 801 if (MAI->hasDotTypeDotSizeDirective()) { 802 // Create a symbol for the end of function, so we can get the size as 803 // difference between the function label and the temp label. 804 MCSymbol *FnEndLabel = OutContext.CreateTempSymbol(); 805 OutStreamer.EmitLabel(FnEndLabel); 806 807 const MCExpr *SizeExp = 808 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext), 809 MCSymbolRefExpr::Create(CurrentFnSymForSize, 810 OutContext), 811 OutContext); 812 OutStreamer.EmitELFSize(CurrentFnSym, SizeExp); 813 } 814 815 // Emit post-function debug information. 816 if (DD) { 817 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 818 DD->endFunction(MF); 819 } 820 if (DE) { 821 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled); 822 DE->EndFunction(); 823 } 824 MMI->EndFunction(); 825 826 // Print out jump tables referenced by the function. 827 EmitJumpTableInfo(); 828 829 OutStreamer.AddBlankLine(); 830} 831 832/// EmitDwarfRegOp - Emit dwarf register operation. 833void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc, 834 bool Indirect) const { 835 const TargetRegisterInfo *TRI = TM.getRegisterInfo(); 836 int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false); 837 838 for (MCSuperRegIterator SR(MLoc.getReg(), TRI); SR.isValid() && Reg < 0; 839 ++SR) { 840 Reg = TRI->getDwarfRegNum(*SR, false); 841 // FIXME: Get the bit range this register uses of the superregister 842 // so that we can produce a DW_OP_bit_piece 843 } 844 845 // FIXME: Handle cases like a super register being encoded as 846 // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33 847 848 // FIXME: We have no reasonable way of handling errors in here. The 849 // caller might be in the middle of an dwarf expression. We should 850 // probably assert that Reg >= 0 once debug info generation is more mature. 851 852 if (MLoc.isIndirect() || Indirect) { 853 if (Reg < 32) { 854 OutStreamer.AddComment( 855 dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg)); 856 EmitInt8(dwarf::DW_OP_breg0 + Reg); 857 } else { 858 OutStreamer.AddComment("DW_OP_bregx"); 859 EmitInt8(dwarf::DW_OP_bregx); 860 OutStreamer.AddComment(Twine(Reg)); 861 EmitULEB128(Reg); 862 } 863 EmitSLEB128(!MLoc.isIndirect() ? 0 : MLoc.getOffset()); 864 if (MLoc.isIndirect() && Indirect) 865 EmitInt8(dwarf::DW_OP_deref); 866 } else { 867 if (Reg < 32) { 868 OutStreamer.AddComment( 869 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg)); 870 EmitInt8(dwarf::DW_OP_reg0 + Reg); 871 } else { 872 OutStreamer.AddComment("DW_OP_regx"); 873 EmitInt8(dwarf::DW_OP_regx); 874 OutStreamer.AddComment(Twine(Reg)); 875 EmitULEB128(Reg); 876 } 877 } 878 879 // FIXME: Produce a DW_OP_bit_piece if we used a superregister 880} 881 882bool AsmPrinter::doFinalization(Module &M) { 883 // Emit global variables. 884 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 885 I != E; ++I) 886 EmitGlobalVariable(I); 887 888 // Emit visibility info for declarations 889 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 890 const Function &F = *I; 891 if (!F.isDeclaration()) 892 continue; 893 GlobalValue::VisibilityTypes V = F.getVisibility(); 894 if (V == GlobalValue::DefaultVisibility) 895 continue; 896 897 MCSymbol *Name = getSymbol(&F); 898 EmitVisibility(Name, V, false); 899 } 900 901 // Emit module flags. 902 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 903 M.getModuleFlagsMetadata(ModuleFlags); 904 if (!ModuleFlags.empty()) 905 getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, Mang, TM); 906 907 // Make sure we wrote out everything we need. 908 OutStreamer.Flush(); 909 910 // Finalize debug and EH information. 911 if (DE) { 912 { 913 NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled); 914 DE->EndModule(); 915 } 916 delete DE; DE = 0; 917 } 918 if (DD) { 919 { 920 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled); 921 DD->endModule(); 922 } 923 delete DD; DD = 0; 924 } 925 926 // If the target wants to know about weak references, print them all. 927 if (MAI->getWeakRefDirective()) { 928 // FIXME: This is not lazy, it would be nice to only print weak references 929 // to stuff that is actually used. Note that doing so would require targets 930 // to notice uses in operands (due to constant exprs etc). This should 931 // happen with the MC stuff eventually. 932 933 // Print out module-level global variables here. 934 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 935 I != E; ++I) { 936 if (!I->hasExternalWeakLinkage()) continue; 937 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference); 938 } 939 940 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 941 if (!I->hasExternalWeakLinkage()) continue; 942 OutStreamer.EmitSymbolAttribute(getSymbol(I), MCSA_WeakReference); 943 } 944 } 945 946 if (MAI->hasSetDirective()) { 947 OutStreamer.AddBlankLine(); 948 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 949 I != E; ++I) { 950 MCSymbol *Name = getSymbol(I); 951 952 const GlobalValue *GV = I->getAliasedGlobal(); 953 if (GV->isDeclaration()) { 954 report_fatal_error(Name->getName() + 955 ": Target doesn't support aliases to declarations"); 956 } 957 958 MCSymbol *Target = getSymbol(GV); 959 960 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) 961 OutStreamer.EmitSymbolAttribute(Name, MCSA_Global); 962 else if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 963 OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference); 964 else 965 assert(I->hasLocalLinkage() && "Invalid alias linkage"); 966 967 EmitVisibility(Name, I->getVisibility()); 968 969 // Emit the directives as assignments aka .set: 970 OutStreamer.EmitAssignment(Name, 971 MCSymbolRefExpr::Create(Target, OutContext)); 972 } 973 } 974 975 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 976 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 977 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 978 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I)) 979 MP->finishAssembly(*this); 980 981 // Emit llvm.ident metadata in an '.ident' directive. 982 EmitModuleIdents(M); 983 984 // If we don't have any trampolines, then we don't require stack memory 985 // to be executable. Some targets have a directive to declare this. 986 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 987 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 988 if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 989 OutStreamer.SwitchSection(S); 990 991 // Allow the target to emit any magic that it wants at the end of the file, 992 // after everything else has gone out. 993 EmitEndOfAsmFile(M); 994 995 delete Mang; Mang = 0; 996 MMI = 0; 997 998 OutStreamer.Finish(); 999 OutStreamer.reset(); 1000 1001 return false; 1002} 1003 1004void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1005 this->MF = &MF; 1006 // Get the function symbol. 1007 CurrentFnSym = getSymbol(MF.getFunction()); 1008 CurrentFnSymForSize = CurrentFnSym; 1009 1010 if (isVerbose()) 1011 LI = &getAnalysis<MachineLoopInfo>(); 1012} 1013 1014namespace { 1015 // SectionCPs - Keep track the alignment, constpool entries per Section. 1016 struct SectionCPs { 1017 const MCSection *S; 1018 unsigned Alignment; 1019 SmallVector<unsigned, 4> CPEs; 1020 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {} 1021 }; 1022} 1023 1024/// EmitConstantPool - Print to the current output stream assembly 1025/// representations of the constants in the constant pool MCP. This is 1026/// used to print out constants which have been "spilled to memory" by 1027/// the code generator. 1028/// 1029void AsmPrinter::EmitConstantPool() { 1030 const MachineConstantPool *MCP = MF->getConstantPool(); 1031 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1032 if (CP.empty()) return; 1033 1034 // Calculate sections for constant pool entries. We collect entries to go into 1035 // the same section together to reduce amount of section switch statements. 1036 SmallVector<SectionCPs, 4> CPSections; 1037 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1038 const MachineConstantPoolEntry &CPE = CP[i]; 1039 unsigned Align = CPE.getAlignment(); 1040 1041 SectionKind Kind; 1042 switch (CPE.getRelocationInfo()) { 1043 default: llvm_unreachable("Unknown section kind"); 1044 case 2: Kind = SectionKind::getReadOnlyWithRel(); break; 1045 case 1: 1046 Kind = SectionKind::getReadOnlyWithRelLocal(); 1047 break; 1048 case 0: 1049 switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) { 1050 case 4: Kind = SectionKind::getMergeableConst4(); break; 1051 case 8: Kind = SectionKind::getMergeableConst8(); break; 1052 case 16: Kind = SectionKind::getMergeableConst16();break; 1053 default: Kind = SectionKind::getMergeableConst(); break; 1054 } 1055 } 1056 1057 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind); 1058 1059 // The number of sections are small, just do a linear search from the 1060 // last section to the first. 1061 bool Found = false; 1062 unsigned SecIdx = CPSections.size(); 1063 while (SecIdx != 0) { 1064 if (CPSections[--SecIdx].S == S) { 1065 Found = true; 1066 break; 1067 } 1068 } 1069 if (!Found) { 1070 SecIdx = CPSections.size(); 1071 CPSections.push_back(SectionCPs(S, Align)); 1072 } 1073 1074 if (Align > CPSections[SecIdx].Alignment) 1075 CPSections[SecIdx].Alignment = Align; 1076 CPSections[SecIdx].CPEs.push_back(i); 1077 } 1078 1079 // Now print stuff into the calculated sections. 1080 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1081 OutStreamer.SwitchSection(CPSections[i].S); 1082 EmitAlignment(Log2_32(CPSections[i].Alignment)); 1083 1084 unsigned Offset = 0; 1085 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1086 unsigned CPI = CPSections[i].CPEs[j]; 1087 MachineConstantPoolEntry CPE = CP[CPI]; 1088 1089 // Emit inter-object padding for alignment. 1090 unsigned AlignMask = CPE.getAlignment() - 1; 1091 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 1092 OutStreamer.EmitZeros(NewOffset - Offset); 1093 1094 Type *Ty = CPE.getType(); 1095 Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty); 1096 OutStreamer.EmitLabel(GetCPISymbol(CPI)); 1097 1098 if (CPE.isMachineConstantPoolEntry()) 1099 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1100 else 1101 EmitGlobalConstant(CPE.Val.ConstVal); 1102 } 1103 } 1104} 1105 1106/// EmitJumpTableInfo - Print assembly representations of the jump tables used 1107/// by the current function to the current output stream. 1108/// 1109void AsmPrinter::EmitJumpTableInfo() { 1110 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1111 if (MJTI == 0) return; 1112 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1113 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1114 if (JT.empty()) return; 1115 1116 // Pick the directive to use to print the jump table entries, and switch to 1117 // the appropriate section. 1118 const Function *F = MF->getFunction(); 1119 bool JTInDiffSection = false; 1120 if (// In PIC mode, we need to emit the jump table to the same section as the 1121 // function body itself, otherwise the label differences won't make sense. 1122 // FIXME: Need a better predicate for this: what about custom entries? 1123 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 || 1124 // We should also do if the section name is NULL or function is declared 1125 // in discardable section 1126 // FIXME: this isn't the right predicate, should be based on the MCSection 1127 // for the function. 1128 F->isWeakForLinker()) { 1129 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM)); 1130 } else { 1131 // Otherwise, drop it in the readonly section. 1132 const MCSection *ReadOnlySection = 1133 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly()); 1134 OutStreamer.SwitchSection(ReadOnlySection); 1135 JTInDiffSection = true; 1136 } 1137 1138 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout()))); 1139 1140 // Jump tables in code sections are marked with a data_region directive 1141 // where that's supported. 1142 if (!JTInDiffSection) 1143 OutStreamer.EmitDataRegion(MCDR_DataRegionJT32); 1144 1145 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1146 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1147 1148 // If this jump table was deleted, ignore it. 1149 if (JTBBs.empty()) continue; 1150 1151 // For the EK_LabelDifference32 entry, if the target supports .set, emit a 1152 // .set directive for each unique entry. This reduces the number of 1153 // relocations the assembler will generate for the jump table. 1154 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1155 MAI->hasSetDirective()) { 1156 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1157 const TargetLowering *TLI = TM.getTargetLowering(); 1158 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1159 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1160 const MachineBasicBlock *MBB = JTBBs[ii]; 1161 if (!EmittedSets.insert(MBB)) continue; 1162 1163 // .set LJTSet, LBB32-base 1164 const MCExpr *LHS = 1165 MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext); 1166 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1167 MCBinaryExpr::CreateSub(LHS, Base, OutContext)); 1168 } 1169 } 1170 1171 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1172 // before each jump table. The first label is never referenced, but tells 1173 // the assembler and linker the extents of the jump table object. The 1174 // second label is actually referenced by the code. 1175 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) 1176 // FIXME: This doesn't have to have any specific name, just any randomly 1177 // named and numbered 'l' label would work. Simplify GetJTISymbol. 1178 OutStreamer.EmitLabel(GetJTISymbol(JTI, true)); 1179 1180 OutStreamer.EmitLabel(GetJTISymbol(JTI)); 1181 1182 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1183 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1184 } 1185 if (!JTInDiffSection) 1186 OutStreamer.EmitDataRegion(MCDR_DataRegionEnd); 1187} 1188 1189/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1190/// current stream. 1191void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1192 const MachineBasicBlock *MBB, 1193 unsigned UID) const { 1194 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1195 const MCExpr *Value = 0; 1196 switch (MJTI->getEntryKind()) { 1197 case MachineJumpTableInfo::EK_Inline: 1198 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1199 case MachineJumpTableInfo::EK_Custom32: 1200 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID, 1201 OutContext); 1202 break; 1203 case MachineJumpTableInfo::EK_BlockAddress: 1204 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1205 // .word LBB123 1206 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext); 1207 break; 1208 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1209 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1210 // with a relocation as gp-relative, e.g.: 1211 // .gprel32 LBB123 1212 MCSymbol *MBBSym = MBB->getSymbol(); 1213 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext)); 1214 return; 1215 } 1216 1217 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 1218 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 1219 // with a relocation as gp-relative, e.g.: 1220 // .gpdword LBB123 1221 MCSymbol *MBBSym = MBB->getSymbol(); 1222 OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext)); 1223 return; 1224 } 1225 1226 case MachineJumpTableInfo::EK_LabelDifference32: { 1227 // EK_LabelDifference32 - Each entry is the address of the block minus 1228 // the address of the jump table. This is used for PIC jump tables where 1229 // gprel32 is not supported. e.g.: 1230 // .word LBB123 - LJTI1_2 1231 // If the .set directive is supported, this is emitted as: 1232 // .set L4_5_set_123, LBB123 - LJTI1_2 1233 // .word L4_5_set_123 1234 1235 // If we have emitted set directives for the jump table entries, print 1236 // them rather than the entries themselves. If we're emitting PIC, then 1237 // emit the table entries as differences between two text section labels. 1238 if (MAI->hasSetDirective()) { 1239 // If we used .set, reference the .set's symbol. 1240 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()), 1241 OutContext); 1242 break; 1243 } 1244 // Otherwise, use the difference as the jump table entry. 1245 Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext); 1246 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext); 1247 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext); 1248 break; 1249 } 1250 } 1251 1252 assert(Value && "Unknown entry kind!"); 1253 1254 unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout()); 1255 OutStreamer.EmitValue(Value, EntrySize); 1256} 1257 1258 1259/// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1260/// special global used by LLVM. If so, emit it and return true, otherwise 1261/// do nothing and return false. 1262bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1263 if (GV->getName() == "llvm.used") { 1264 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1265 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 1266 return true; 1267 } 1268 1269 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1270 if (GV->getSection() == "llvm.metadata" || 1271 GV->hasAvailableExternallyLinkage()) 1272 return true; 1273 1274 if (!GV->hasAppendingLinkage()) return false; 1275 1276 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1277 1278 if (GV->getName() == "llvm.global_ctors") { 1279 EmitXXStructorList(GV->getInitializer(), /* isCtor */ true); 1280 1281 if (TM.getRelocationModel() == Reloc::Static && 1282 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1283 StringRef Sym(".constructors_used"); 1284 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym), 1285 MCSA_Reference); 1286 } 1287 return true; 1288 } 1289 1290 if (GV->getName() == "llvm.global_dtors") { 1291 EmitXXStructorList(GV->getInitializer(), /* isCtor */ false); 1292 1293 if (TM.getRelocationModel() == Reloc::Static && 1294 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1295 StringRef Sym(".destructors_used"); 1296 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym), 1297 MCSA_Reference); 1298 } 1299 return true; 1300 } 1301 1302 return false; 1303} 1304 1305/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 1306/// global in the specified llvm.used list for which emitUsedDirectiveFor 1307/// is true, as being used with this directive. 1308void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) { 1309 // Should be an array of 'i8*'. 1310 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1311 const GlobalValue *GV = 1312 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 1313 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) 1314 OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 1315 } 1316} 1317 1318/// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 1319/// priority. 1320void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) { 1321 // Should be an array of '{ int, void ()* }' structs. The first value is the 1322 // init priority. 1323 if (!isa<ConstantArray>(List)) return; 1324 1325 // Sanity check the structors list. 1326 const ConstantArray *InitList = dyn_cast<ConstantArray>(List); 1327 if (!InitList) return; // Not an array! 1328 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType()); 1329 if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs! 1330 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) || 1331 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr). 1332 1333 // Gather the structors in a form that's convenient for sorting by priority. 1334 typedef std::pair<unsigned, Constant *> Structor; 1335 SmallVector<Structor, 8> Structors; 1336 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1337 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 1338 if (!CS) continue; // Malformed. 1339 if (CS->getOperand(1)->isNullValue()) 1340 break; // Found a null terminator, skip the rest. 1341 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 1342 if (!Priority) continue; // Malformed. 1343 Structors.push_back(std::make_pair(Priority->getLimitedValue(65535), 1344 CS->getOperand(1))); 1345 } 1346 1347 // Emit the function pointers in the target-specific order 1348 const DataLayout *DL = TM.getDataLayout(); 1349 unsigned Align = Log2_32(DL->getPointerPrefAlignment()); 1350 std::stable_sort(Structors.begin(), Structors.end(), less_first()); 1351 for (unsigned i = 0, e = Structors.size(); i != e; ++i) { 1352 const MCSection *OutputSection = 1353 (isCtor ? 1354 getObjFileLowering().getStaticCtorSection(Structors[i].first) : 1355 getObjFileLowering().getStaticDtorSection(Structors[i].first)); 1356 OutStreamer.SwitchSection(OutputSection); 1357 if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection()) 1358 EmitAlignment(Align); 1359 EmitXXStructor(Structors[i].second); 1360 } 1361} 1362 1363void AsmPrinter::EmitModuleIdents(Module &M) { 1364 if (!MAI->hasIdentDirective()) 1365 return; 1366 1367 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 1368 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1369 const MDNode *N = NMD->getOperand(i); 1370 assert(N->getNumOperands() == 1 && 1371 "llvm.ident metadata entry can have only one operand"); 1372 const MDString *S = cast<MDString>(N->getOperand(0)); 1373 OutStreamer.EmitIdent(S->getString()); 1374 } 1375 } 1376} 1377 1378//===--------------------------------------------------------------------===// 1379// Emission and print routines 1380// 1381 1382/// EmitInt8 - Emit a byte directive and value. 1383/// 1384void AsmPrinter::EmitInt8(int Value) const { 1385 OutStreamer.EmitIntValue(Value, 1); 1386} 1387 1388/// EmitInt16 - Emit a short directive and value. 1389/// 1390void AsmPrinter::EmitInt16(int Value) const { 1391 OutStreamer.EmitIntValue(Value, 2); 1392} 1393 1394/// EmitInt32 - Emit a long directive and value. 1395/// 1396void AsmPrinter::EmitInt32(int Value) const { 1397 OutStreamer.EmitIntValue(Value, 4); 1398} 1399 1400/// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size 1401/// in bytes of the directive is specified by Size and Hi/Lo specify the 1402/// labels. This implicitly uses .set if it is available. 1403void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 1404 unsigned Size) const { 1405 // Get the Hi-Lo expression. 1406 const MCExpr *Diff = 1407 MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext), 1408 MCSymbolRefExpr::Create(Lo, OutContext), 1409 OutContext); 1410 1411 if (!MAI->hasSetDirective()) { 1412 OutStreamer.EmitValue(Diff, Size); 1413 return; 1414 } 1415 1416 // Otherwise, emit with .set (aka assignment). 1417 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++); 1418 OutStreamer.EmitAssignment(SetLabel, Diff); 1419 OutStreamer.EmitSymbolValue(SetLabel, Size); 1420} 1421 1422/// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo" 1423/// where the size in bytes of the directive is specified by Size and Hi/Lo 1424/// specify the labels. This implicitly uses .set if it is available. 1425void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset, 1426 const MCSymbol *Lo, unsigned Size) 1427 const { 1428 1429 // Emit Hi+Offset - Lo 1430 // Get the Hi+Offset expression. 1431 const MCExpr *Plus = 1432 MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext), 1433 MCConstantExpr::Create(Offset, OutContext), 1434 OutContext); 1435 1436 // Get the Hi+Offset-Lo expression. 1437 const MCExpr *Diff = 1438 MCBinaryExpr::CreateSub(Plus, 1439 MCSymbolRefExpr::Create(Lo, OutContext), 1440 OutContext); 1441 1442 if (!MAI->hasSetDirective()) 1443 OutStreamer.EmitValue(Diff, Size); 1444 else { 1445 // Otherwise, emit with .set (aka assignment). 1446 MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++); 1447 OutStreamer.EmitAssignment(SetLabel, Diff); 1448 OutStreamer.EmitSymbolValue(SetLabel, Size); 1449 } 1450} 1451 1452/// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 1453/// where the size in bytes of the directive is specified by Size and Label 1454/// specifies the label. This implicitly uses .set if it is available. 1455void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 1456 unsigned Size, bool IsSectionRelative) 1457 const { 1458 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 1459 OutStreamer.EmitCOFFSecRel32(Label); 1460 return; 1461 } 1462 1463 // Emit Label+Offset (or just Label if Offset is zero) 1464 const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext); 1465 if (Offset) 1466 Expr = MCBinaryExpr::CreateAdd(Expr, 1467 MCConstantExpr::Create(Offset, OutContext), 1468 OutContext); 1469 1470 OutStreamer.EmitValue(Expr, Size); 1471} 1472 1473 1474//===----------------------------------------------------------------------===// 1475 1476// EmitAlignment - Emit an alignment directive to the specified power of 1477// two boundary. For example, if you pass in 3 here, you will get an 8 1478// byte alignment. If a global value is specified, and if that global has 1479// an explicit alignment requested, it will override the alignment request 1480// if required for correctness. 1481// 1482void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const { 1483 if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits); 1484 1485 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment. 1486 1487 if (getCurrentSection()->getKind().isText()) 1488 OutStreamer.EmitCodeAlignment(1 << NumBits); 1489 else 1490 OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0); 1491} 1492 1493//===----------------------------------------------------------------------===// 1494// Constant emission. 1495//===----------------------------------------------------------------------===// 1496 1497/// lowerConstant - Lower the specified LLVM Constant to an MCExpr. 1498/// 1499static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) { 1500 MCContext &Ctx = AP.OutContext; 1501 1502 if (CV->isNullValue() || isa<UndefValue>(CV)) 1503 return MCConstantExpr::Create(0, Ctx); 1504 1505 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 1506 return MCConstantExpr::Create(CI->getZExtValue(), Ctx); 1507 1508 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 1509 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx); 1510 1511 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 1512 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx); 1513 1514 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 1515 if (CE == 0) { 1516 llvm_unreachable("Unknown constant value to lower!"); 1517 } 1518 1519 switch (CE->getOpcode()) { 1520 default: 1521 // If the code isn't optimized, there may be outstanding folding 1522 // opportunities. Attempt to fold the expression using DataLayout as a 1523 // last resort before giving up. 1524 if (Constant *C = 1525 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout())) 1526 if (C != CE) 1527 return lowerConstant(C, AP); 1528 1529 // Otherwise report the problem to the user. 1530 { 1531 std::string S; 1532 raw_string_ostream OS(S); 1533 OS << "Unsupported expression in static initializer: "; 1534 WriteAsOperand(OS, CE, /*PrintType=*/false, 1535 !AP.MF ? 0 : AP.MF->getFunction()->getParent()); 1536 report_fatal_error(OS.str()); 1537 } 1538 case Instruction::GetElementPtr: { 1539 const DataLayout &DL = *AP.TM.getDataLayout(); 1540 // Generate a symbolic expression for the byte address 1541 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0); 1542 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI); 1543 1544 const MCExpr *Base = lowerConstant(CE->getOperand(0), AP); 1545 if (!OffsetAI) 1546 return Base; 1547 1548 int64_t Offset = OffsetAI.getSExtValue(); 1549 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx), 1550 Ctx); 1551 } 1552 1553 case Instruction::Trunc: 1554 // We emit the value and depend on the assembler to truncate the generated 1555 // expression properly. This is important for differences between 1556 // blockaddress labels. Since the two labels are in the same function, it 1557 // is reasonable to treat their delta as a 32-bit value. 1558 // FALL THROUGH. 1559 case Instruction::BitCast: 1560 return lowerConstant(CE->getOperand(0), AP); 1561 1562 case Instruction::IntToPtr: { 1563 const DataLayout &DL = *AP.TM.getDataLayout(); 1564 // Handle casts to pointers by changing them into casts to the appropriate 1565 // integer type. This promotes constant folding and simplifies this code. 1566 Constant *Op = CE->getOperand(0); 1567 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 1568 false/*ZExt*/); 1569 return lowerConstant(Op, AP); 1570 } 1571 1572 case Instruction::PtrToInt: { 1573 const DataLayout &DL = *AP.TM.getDataLayout(); 1574 // Support only foldable casts to/from pointers that can be eliminated by 1575 // changing the pointer to the appropriately sized integer type. 1576 Constant *Op = CE->getOperand(0); 1577 Type *Ty = CE->getType(); 1578 1579 const MCExpr *OpExpr = lowerConstant(Op, AP); 1580 1581 // We can emit the pointer value into this slot if the slot is an 1582 // integer slot equal to the size of the pointer. 1583 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType())) 1584 return OpExpr; 1585 1586 // Otherwise the pointer is smaller than the resultant integer, mask off 1587 // the high bits so we are sure to get a proper truncation if the input is 1588 // a constant expr. 1589 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 1590 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx); 1591 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx); 1592 } 1593 1594 // The MC library also has a right-shift operator, but it isn't consistently 1595 // signed or unsigned between different targets. 1596 case Instruction::Add: 1597 case Instruction::Sub: 1598 case Instruction::Mul: 1599 case Instruction::SDiv: 1600 case Instruction::SRem: 1601 case Instruction::Shl: 1602 case Instruction::And: 1603 case Instruction::Or: 1604 case Instruction::Xor: { 1605 const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP); 1606 const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP); 1607 switch (CE->getOpcode()) { 1608 default: llvm_unreachable("Unknown binary operator constant cast expr"); 1609 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx); 1610 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx); 1611 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx); 1612 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx); 1613 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx); 1614 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx); 1615 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx); 1616 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx); 1617 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx); 1618 } 1619 } 1620 } 1621} 1622 1623static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP); 1624 1625/// isRepeatedByteSequence - Determine whether the given value is 1626/// composed of a repeated sequence of identical bytes and return the 1627/// byte value. If it is not a repeated sequence, return -1. 1628static int isRepeatedByteSequence(const ConstantDataSequential *V) { 1629 StringRef Data = V->getRawDataValues(); 1630 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 1631 char C = Data[0]; 1632 for (unsigned i = 1, e = Data.size(); i != e; ++i) 1633 if (Data[i] != C) return -1; 1634 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 1635} 1636 1637 1638/// isRepeatedByteSequence - Determine whether the given value is 1639/// composed of a repeated sequence of identical bytes and return the 1640/// byte value. If it is not a repeated sequence, return -1. 1641static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) { 1642 1643 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 1644 if (CI->getBitWidth() > 64) return -1; 1645 1646 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType()); 1647 uint64_t Value = CI->getZExtValue(); 1648 1649 // Make sure the constant is at least 8 bits long and has a power 1650 // of 2 bit width. This guarantees the constant bit width is 1651 // always a multiple of 8 bits, avoiding issues with padding out 1652 // to Size and other such corner cases. 1653 if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1; 1654 1655 uint8_t Byte = static_cast<uint8_t>(Value); 1656 1657 for (unsigned i = 1; i < Size; ++i) { 1658 Value >>= 8; 1659 if (static_cast<uint8_t>(Value) != Byte) return -1; 1660 } 1661 return Byte; 1662 } 1663 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 1664 // Make sure all array elements are sequences of the same repeated 1665 // byte. 1666 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 1667 int Byte = isRepeatedByteSequence(CA->getOperand(0), TM); 1668 if (Byte == -1) return -1; 1669 1670 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) { 1671 int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM); 1672 if (ThisByte == -1) return -1; 1673 if (Byte != ThisByte) return -1; 1674 } 1675 return Byte; 1676 } 1677 1678 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 1679 return isRepeatedByteSequence(CDS); 1680 1681 return -1; 1682} 1683 1684static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS, 1685 AsmPrinter &AP){ 1686 1687 // See if we can aggregate this into a .fill, if so, emit it as such. 1688 int Value = isRepeatedByteSequence(CDS, AP.TM); 1689 if (Value != -1) { 1690 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType()); 1691 // Don't emit a 1-byte object as a .fill. 1692 if (Bytes > 1) 1693 return AP.OutStreamer.EmitFill(Bytes, Value); 1694 } 1695 1696 // If this can be emitted with .ascii/.asciz, emit it as such. 1697 if (CDS->isString()) 1698 return AP.OutStreamer.EmitBytes(CDS->getAsString()); 1699 1700 // Otherwise, emit the values in successive locations. 1701 unsigned ElementByteSize = CDS->getElementByteSize(); 1702 if (isa<IntegerType>(CDS->getElementType())) { 1703 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1704 if (AP.isVerbose()) 1705 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n", 1706 CDS->getElementAsInteger(i)); 1707 AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i), 1708 ElementByteSize); 1709 } 1710 } else if (ElementByteSize == 4) { 1711 // FP Constants are printed as integer constants to avoid losing 1712 // precision. 1713 assert(CDS->getElementType()->isFloatTy()); 1714 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1715 union { 1716 float F; 1717 uint32_t I; 1718 }; 1719 1720 F = CDS->getElementAsFloat(i); 1721 if (AP.isVerbose()) 1722 AP.OutStreamer.GetCommentOS() << "float " << F << '\n'; 1723 AP.OutStreamer.EmitIntValue(I, 4); 1724 } 1725 } else { 1726 assert(CDS->getElementType()->isDoubleTy()); 1727 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1728 union { 1729 double F; 1730 uint64_t I; 1731 }; 1732 1733 F = CDS->getElementAsDouble(i); 1734 if (AP.isVerbose()) 1735 AP.OutStreamer.GetCommentOS() << "double " << F << '\n'; 1736 AP.OutStreamer.EmitIntValue(I, 8); 1737 } 1738 } 1739 1740 const DataLayout &DL = *AP.TM.getDataLayout(); 1741 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 1742 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) * 1743 CDS->getNumElements(); 1744 if (unsigned Padding = Size - EmittedSize) 1745 AP.OutStreamer.EmitZeros(Padding); 1746 1747} 1748 1749static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) { 1750 // See if we can aggregate some values. Make sure it can be 1751 // represented as a series of bytes of the constant value. 1752 int Value = isRepeatedByteSequence(CA, AP.TM); 1753 1754 if (Value != -1) { 1755 uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType()); 1756 AP.OutStreamer.EmitFill(Bytes, Value); 1757 } 1758 else { 1759 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) 1760 emitGlobalConstantImpl(CA->getOperand(i), AP); 1761 } 1762} 1763 1764static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) { 1765 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 1766 emitGlobalConstantImpl(CV->getOperand(i), AP); 1767 1768 const DataLayout &DL = *AP.TM.getDataLayout(); 1769 unsigned Size = DL.getTypeAllocSize(CV->getType()); 1770 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 1771 CV->getType()->getNumElements(); 1772 if (unsigned Padding = Size - EmittedSize) 1773 AP.OutStreamer.EmitZeros(Padding); 1774} 1775 1776static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) { 1777 // Print the fields in successive locations. Pad to align if needed! 1778 const DataLayout *DL = AP.TM.getDataLayout(); 1779 unsigned Size = DL->getTypeAllocSize(CS->getType()); 1780 const StructLayout *Layout = DL->getStructLayout(CS->getType()); 1781 uint64_t SizeSoFar = 0; 1782 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 1783 const Constant *Field = CS->getOperand(i); 1784 1785 // Check if padding is needed and insert one or more 0s. 1786 uint64_t FieldSize = DL->getTypeAllocSize(Field->getType()); 1787 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 1788 - Layout->getElementOffset(i)) - FieldSize; 1789 SizeSoFar += FieldSize + PadSize; 1790 1791 // Now print the actual field value. 1792 emitGlobalConstantImpl(Field, AP); 1793 1794 // Insert padding - this may include padding to increase the size of the 1795 // current field up to the ABI size (if the struct is not packed) as well 1796 // as padding to ensure that the next field starts at the right offset. 1797 AP.OutStreamer.EmitZeros(PadSize); 1798 } 1799 assert(SizeSoFar == Layout->getSizeInBytes() && 1800 "Layout of constant struct may be incorrect!"); 1801} 1802 1803static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 1804 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1805 1806 // First print a comment with what we think the original floating-point value 1807 // should have been. 1808 if (AP.isVerbose()) { 1809 SmallString<8> StrVal; 1810 CFP->getValueAPF().toString(StrVal); 1811 1812 CFP->getType()->print(AP.OutStreamer.GetCommentOS()); 1813 AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n'; 1814 } 1815 1816 // Now iterate through the APInt chunks, emitting them in endian-correct 1817 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 1818 // floats). 1819 unsigned NumBytes = API.getBitWidth() / 8; 1820 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 1821 const uint64_t *p = API.getRawData(); 1822 1823 // PPC's long double has odd notions of endianness compared to how LLVM 1824 // handles it: p[0] goes first for *big* endian on PPC. 1825 if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) { 1826 int Chunk = API.getNumWords() - 1; 1827 1828 if (TrailingBytes) 1829 AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes); 1830 1831 for (; Chunk >= 0; --Chunk) 1832 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t)); 1833 } else { 1834 unsigned Chunk; 1835 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 1836 AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t)); 1837 1838 if (TrailingBytes) 1839 AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes); 1840 } 1841 1842 // Emit the tail padding for the long double. 1843 const DataLayout &DL = *AP.TM.getDataLayout(); 1844 AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) - 1845 DL.getTypeStoreSize(CFP->getType())); 1846} 1847 1848static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 1849 const DataLayout *DL = AP.TM.getDataLayout(); 1850 unsigned BitWidth = CI->getBitWidth(); 1851 1852 // Copy the value as we may massage the layout for constants whose bit width 1853 // is not a multiple of 64-bits. 1854 APInt Realigned(CI->getValue()); 1855 uint64_t ExtraBits = 0; 1856 unsigned ExtraBitsSize = BitWidth & 63; 1857 1858 if (ExtraBitsSize) { 1859 // The bit width of the data is not a multiple of 64-bits. 1860 // The extra bits are expected to be at the end of the chunk of the memory. 1861 // Little endian: 1862 // * Nothing to be done, just record the extra bits to emit. 1863 // Big endian: 1864 // * Record the extra bits to emit. 1865 // * Realign the raw data to emit the chunks of 64-bits. 1866 if (DL->isBigEndian()) { 1867 // Basically the structure of the raw data is a chunk of 64-bits cells: 1868 // 0 1 BitWidth / 64 1869 // [chunk1][chunk2] ... [chunkN]. 1870 // The most significant chunk is chunkN and it should be emitted first. 1871 // However, due to the alignment issue chunkN contains useless bits. 1872 // Realign the chunks so that they contain only useless information: 1873 // ExtraBits 0 1 (BitWidth / 64) - 1 1874 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 1875 ExtraBits = Realigned.getRawData()[0] & 1876 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 1877 Realigned = Realigned.lshr(ExtraBitsSize); 1878 } else 1879 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 1880 } 1881 1882 // We don't expect assemblers to support integer data directives 1883 // for more than 64 bits, so we emit the data in at most 64-bit 1884 // quantities at a time. 1885 const uint64_t *RawData = Realigned.getRawData(); 1886 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1887 uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i]; 1888 AP.OutStreamer.EmitIntValue(Val, 8); 1889 } 1890 1891 if (ExtraBitsSize) { 1892 // Emit the extra bits after the 64-bits chunks. 1893 1894 // Emit a directive that fills the expected size. 1895 uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType()); 1896 Size -= (BitWidth / 64) * 8; 1897 assert(Size && Size * 8 >= ExtraBitsSize && 1898 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 1899 == ExtraBits && "Directive too small for extra bits."); 1900 AP.OutStreamer.EmitIntValue(ExtraBits, Size); 1901 } 1902} 1903 1904static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) { 1905 const DataLayout *DL = AP.TM.getDataLayout(); 1906 uint64_t Size = DL->getTypeAllocSize(CV->getType()); 1907 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 1908 return AP.OutStreamer.EmitZeros(Size); 1909 1910 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1911 switch (Size) { 1912 case 1: 1913 case 2: 1914 case 4: 1915 case 8: 1916 if (AP.isVerbose()) 1917 AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n", 1918 CI->getZExtValue()); 1919 AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size); 1920 return; 1921 default: 1922 emitGlobalConstantLargeInt(CI, AP); 1923 return; 1924 } 1925 } 1926 1927 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 1928 return emitGlobalConstantFP(CFP, AP); 1929 1930 if (isa<ConstantPointerNull>(CV)) { 1931 AP.OutStreamer.EmitIntValue(0, Size); 1932 return; 1933 } 1934 1935 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 1936 return emitGlobalConstantDataSequential(CDS, AP); 1937 1938 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 1939 return emitGlobalConstantArray(CVA, AP); 1940 1941 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 1942 return emitGlobalConstantStruct(CVS, AP); 1943 1944 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 1945 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 1946 // vectors). 1947 if (CE->getOpcode() == Instruction::BitCast) 1948 return emitGlobalConstantImpl(CE->getOperand(0), AP); 1949 1950 if (Size > 8) { 1951 // If the constant expression's size is greater than 64-bits, then we have 1952 // to emit the value in chunks. Try to constant fold the value and emit it 1953 // that way. 1954 Constant *New = ConstantFoldConstantExpression(CE, DL); 1955 if (New && New != CE) 1956 return emitGlobalConstantImpl(New, AP); 1957 } 1958 } 1959 1960 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 1961 return emitGlobalConstantVector(V, AP); 1962 1963 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 1964 // thread the streamer with EmitValue. 1965 AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size); 1966} 1967 1968/// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1969void AsmPrinter::EmitGlobalConstant(const Constant *CV) { 1970 uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType()); 1971 if (Size) 1972 emitGlobalConstantImpl(CV, *this); 1973 else if (MAI->hasSubsectionsViaSymbols()) { 1974 // If the global has zero size, emit a single byte so that two labels don't 1975 // look like they are at the same location. 1976 OutStreamer.EmitIntValue(0, 1); 1977 } 1978} 1979 1980void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1981 // Target doesn't support this yet! 1982 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1983} 1984 1985void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 1986 if (Offset > 0) 1987 OS << '+' << Offset; 1988 else if (Offset < 0) 1989 OS << Offset; 1990} 1991 1992//===----------------------------------------------------------------------===// 1993// Symbol Lowering Routines. 1994//===----------------------------------------------------------------------===// 1995 1996/// GetTempSymbol - Return the MCSymbol corresponding to the assembler 1997/// temporary label with the specified stem and unique ID. 1998MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const { 1999 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) + 2000 Name + Twine(ID)); 2001} 2002 2003/// GetTempSymbol - Return an assembler temporary label with the specified 2004/// stem. 2005MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const { 2006 return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+ 2007 Name); 2008} 2009 2010 2011MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2012 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2013} 2014 2015MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2016 return MMI->getAddrLabelSymbol(BB); 2017} 2018 2019/// GetCPISymbol - Return the symbol for the specified constant pool entry. 2020MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2021 return OutContext.GetOrCreateSymbol 2022 (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber()) 2023 + "_" + Twine(CPID)); 2024} 2025 2026/// GetJTISymbol - Return the symbol for the specified jump table entry. 2027MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2028 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2029} 2030 2031/// GetJTSetSymbol - Return the symbol for the specified jump table .set 2032/// FIXME: privatize to AsmPrinter. 2033MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2034 return OutContext.GetOrCreateSymbol 2035 (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" + 2036 Twine(UID) + "_set_" + Twine(MBBID)); 2037} 2038 2039/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with 2040/// global value name as its base, with the specified suffix, and where the 2041/// symbol is forced to have private linkage if ForcePrivate is true. 2042MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV, 2043 StringRef Suffix, 2044 bool ForcePrivate) const { 2045 SmallString<60> NameStr; 2046 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate); 2047 NameStr.append(Suffix.begin(), Suffix.end()); 2048 return OutContext.GetOrCreateSymbol(NameStr.str()); 2049} 2050 2051/// GetExternalSymbolSymbol - Return the MCSymbol for the specified 2052/// ExternalSymbol. 2053MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2054 SmallString<60> NameStr; 2055 Mang->getNameWithPrefix(NameStr, Sym); 2056 return OutContext.GetOrCreateSymbol(NameStr.str()); 2057} 2058 2059 2060 2061/// PrintParentLoopComment - Print comments about parent loops of this one. 2062static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2063 unsigned FunctionNumber) { 2064 if (Loop == 0) return; 2065 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2066 OS.indent(Loop->getLoopDepth()*2) 2067 << "Parent Loop BB" << FunctionNumber << "_" 2068 << Loop->getHeader()->getNumber() 2069 << " Depth=" << Loop->getLoopDepth() << '\n'; 2070} 2071 2072 2073/// PrintChildLoopComment - Print comments about child loops within 2074/// the loop for this basic block, with nesting. 2075static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2076 unsigned FunctionNumber) { 2077 // Add child loop information 2078 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){ 2079 OS.indent((*CL)->getLoopDepth()*2) 2080 << "Child Loop BB" << FunctionNumber << "_" 2081 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth() 2082 << '\n'; 2083 PrintChildLoopComment(OS, *CL, FunctionNumber); 2084 } 2085} 2086 2087/// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2088static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2089 const MachineLoopInfo *LI, 2090 const AsmPrinter &AP) { 2091 // Add loop depth information 2092 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2093 if (Loop == 0) return; 2094 2095 MachineBasicBlock *Header = Loop->getHeader(); 2096 assert(Header && "No header for loop"); 2097 2098 // If this block is not a loop header, just print out what is the loop header 2099 // and return. 2100 if (Header != &MBB) { 2101 AP.OutStreamer.AddComment(" in Loop: Header=BB" + 2102 Twine(AP.getFunctionNumber())+"_" + 2103 Twine(Loop->getHeader()->getNumber())+ 2104 " Depth="+Twine(Loop->getLoopDepth())); 2105 return; 2106 } 2107 2108 // Otherwise, it is a loop header. Print out information about child and 2109 // parent loops. 2110 raw_ostream &OS = AP.OutStreamer.GetCommentOS(); 2111 2112 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 2113 2114 OS << "=>"; 2115 OS.indent(Loop->getLoopDepth()*2-2); 2116 2117 OS << "This "; 2118 if (Loop->empty()) 2119 OS << "Inner "; 2120 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 2121 2122 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 2123} 2124 2125 2126/// EmitBasicBlockStart - This method prints the label for the specified 2127/// MachineBasicBlock, an alignment (if present) and a comment describing 2128/// it if appropriate. 2129void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const { 2130 // Emit an alignment directive for this block, if needed. 2131 if (unsigned Align = MBB->getAlignment()) 2132 EmitAlignment(Align); 2133 2134 // If the block has its address taken, emit any labels that were used to 2135 // reference the block. It is possible that there is more than one label 2136 // here, because multiple LLVM BB's may have been RAUW'd to this block after 2137 // the references were generated. 2138 if (MBB->hasAddressTaken()) { 2139 const BasicBlock *BB = MBB->getBasicBlock(); 2140 if (isVerbose()) 2141 OutStreamer.AddComment("Block address taken"); 2142 2143 std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB); 2144 2145 for (unsigned i = 0, e = Syms.size(); i != e; ++i) 2146 OutStreamer.EmitLabel(Syms[i]); 2147 } 2148 2149 // Print some verbose block comments. 2150 if (isVerbose()) { 2151 if (const BasicBlock *BB = MBB->getBasicBlock()) 2152 if (BB->hasName()) 2153 OutStreamer.AddComment("%" + BB->getName()); 2154 emitBasicBlockLoopComments(*MBB, LI, *this); 2155 } 2156 2157 // Print the main label for the block. 2158 if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) { 2159 if (isVerbose() && OutStreamer.hasRawTextSupport()) { 2160 // NOTE: Want this comment at start of line, don't emit with AddComment. 2161 OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" + 2162 Twine(MBB->getNumber()) + ":"); 2163 } 2164 } else { 2165 OutStreamer.EmitLabel(MBB->getSymbol()); 2166 } 2167} 2168 2169void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility, 2170 bool IsDefinition) const { 2171 MCSymbolAttr Attr = MCSA_Invalid; 2172 2173 switch (Visibility) { 2174 default: break; 2175 case GlobalValue::HiddenVisibility: 2176 if (IsDefinition) 2177 Attr = MAI->getHiddenVisibilityAttr(); 2178 else 2179 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 2180 break; 2181 case GlobalValue::ProtectedVisibility: 2182 Attr = MAI->getProtectedVisibilityAttr(); 2183 break; 2184 } 2185 2186 if (Attr != MCSA_Invalid) 2187 OutStreamer.EmitSymbolAttribute(Sym, Attr); 2188} 2189 2190/// isBlockOnlyReachableByFallthough - Return true if the basic block has 2191/// exactly one predecessor and the control transfer mechanism between 2192/// the predecessor and this block is a fall-through. 2193bool AsmPrinter:: 2194isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 2195 // If this is a landing pad, it isn't a fall through. If it has no preds, 2196 // then nothing falls through to it. 2197 if (MBB->isLandingPad() || MBB->pred_empty()) 2198 return false; 2199 2200 // If there isn't exactly one predecessor, it can't be a fall through. 2201 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI; 2202 ++PI2; 2203 if (PI2 != MBB->pred_end()) 2204 return false; 2205 2206 // The predecessor has to be immediately before this block. 2207 MachineBasicBlock *Pred = *PI; 2208 2209 if (!Pred->isLayoutSuccessor(MBB)) 2210 return false; 2211 2212 // If the block is completely empty, then it definitely does fall through. 2213 if (Pred->empty()) 2214 return true; 2215 2216 // Check the terminators in the previous blocks 2217 for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(), 2218 IE = Pred->end(); II != IE; ++II) { 2219 MachineInstr &MI = *II; 2220 2221 // If it is not a simple branch, we are in a table somewhere. 2222 if (!MI.isBranch() || MI.isIndirectBranch()) 2223 return false; 2224 2225 // If we are the operands of one of the branches, this is not a fall 2226 // through. Note that targets with delay slots will usually bundle 2227 // terminators with the delay slot instruction. 2228 for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) { 2229 if (OP->isJTI()) 2230 return false; 2231 if (OP->isMBB() && OP->getMBB() == MBB) 2232 return false; 2233 } 2234 } 2235 2236 return true; 2237} 2238 2239 2240 2241GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) { 2242 if (!S->usesMetadata()) 2243 return 0; 2244 2245 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 2246 gcp_map_type::iterator GCPI = GCMap.find(S); 2247 if (GCPI != GCMap.end()) 2248 return GCPI->second; 2249 2250 const char *Name = S->getName().c_str(); 2251 2252 for (GCMetadataPrinterRegistry::iterator 2253 I = GCMetadataPrinterRegistry::begin(), 2254 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 2255 if (strcmp(Name, I->getName()) == 0) { 2256 GCMetadataPrinter *GMP = I->instantiate(); 2257 GMP->S = S; 2258 GCMap.insert(std::make_pair(S, GMP)); 2259 return GMP; 2260 } 2261 2262 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 2263} 2264