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