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