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