AsmPrinter.cpp 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174
  1. //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the AsmPrinter class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/AsmPrinter.h"
  13. #include "CodeViewDebug.h"
  14. #include "DwarfDebug.h"
  15. #include "DwarfException.h"
  16. #include "WasmException.h"
  17. #include "WinCFGuard.h"
  18. #include "WinException.h"
  19. #include "llvm/ADT/APFloat.h"
  20. #include "llvm/ADT/APInt.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/ADT/Statistic.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/ADT/Triple.h"
  29. #include "llvm/ADT/Twine.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  33. #include "llvm/BinaryFormat/COFF.h"
  34. #include "llvm/BinaryFormat/Dwarf.h"
  35. #include "llvm/BinaryFormat/ELF.h"
  36. #include "llvm/CodeGen/GCMetadata.h"
  37. #include "llvm/CodeGen/GCMetadataPrinter.h"
  38. #include "llvm/CodeGen/GCStrategy.h"
  39. #include "llvm/CodeGen/MachineBasicBlock.h"
  40. #include "llvm/CodeGen/MachineConstantPool.h"
  41. #include "llvm/CodeGen/MachineDominators.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineFunctionPass.h"
  45. #include "llvm/CodeGen/MachineInstr.h"
  46. #include "llvm/CodeGen/MachineInstrBundle.h"
  47. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  48. #include "llvm/CodeGen/MachineLoopInfo.h"
  49. #include "llvm/CodeGen/MachineMemOperand.h"
  50. #include "llvm/CodeGen/MachineModuleInfo.h"
  51. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  52. #include "llvm/CodeGen/MachineOperand.h"
  53. #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
  54. #include "llvm/CodeGen/StackMaps.h"
  55. #include "llvm/CodeGen/TargetFrameLowering.h"
  56. #include "llvm/CodeGen/TargetInstrInfo.h"
  57. #include "llvm/CodeGen/TargetLowering.h"
  58. #include "llvm/CodeGen/TargetOpcodes.h"
  59. #include "llvm/CodeGen/TargetRegisterInfo.h"
  60. #include "llvm/IR/BasicBlock.h"
  61. #include "llvm/IR/Comdat.h"
  62. #include "llvm/IR/Constant.h"
  63. #include "llvm/IR/Constants.h"
  64. #include "llvm/IR/DataLayout.h"
  65. #include "llvm/IR/DebugInfoMetadata.h"
  66. #include "llvm/IR/DerivedTypes.h"
  67. #include "llvm/IR/Function.h"
  68. #include "llvm/IR/GlobalAlias.h"
  69. #include "llvm/IR/GlobalIFunc.h"
  70. #include "llvm/IR/GlobalIndirectSymbol.h"
  71. #include "llvm/IR/GlobalObject.h"
  72. #include "llvm/IR/GlobalValue.h"
  73. #include "llvm/IR/GlobalVariable.h"
  74. #include "llvm/IR/Instruction.h"
  75. #include "llvm/IR/Mangler.h"
  76. #include "llvm/IR/Metadata.h"
  77. #include "llvm/IR/Module.h"
  78. #include "llvm/IR/Operator.h"
  79. #include "llvm/IR/RemarkStreamer.h"
  80. #include "llvm/IR/Type.h"
  81. #include "llvm/IR/Value.h"
  82. #include "llvm/MC/MCAsmInfo.h"
  83. #include "llvm/MC/MCCodePadder.h"
  84. #include "llvm/MC/MCContext.h"
  85. #include "llvm/MC/MCDirectives.h"
  86. #include "llvm/MC/MCDwarf.h"
  87. #include "llvm/MC/MCExpr.h"
  88. #include "llvm/MC/MCInst.h"
  89. #include "llvm/MC/MCSection.h"
  90. #include "llvm/MC/MCSectionCOFF.h"
  91. #include "llvm/MC/MCSectionELF.h"
  92. #include "llvm/MC/MCSectionMachO.h"
  93. #include "llvm/MC/MCStreamer.h"
  94. #include "llvm/MC/MCSubtargetInfo.h"
  95. #include "llvm/MC/MCSymbol.h"
  96. #include "llvm/MC/MCSymbolELF.h"
  97. #include "llvm/MC/MCTargetOptions.h"
  98. #include "llvm/MC/MCValue.h"
  99. #include "llvm/MC/SectionKind.h"
  100. #include "llvm/Pass.h"
  101. #include "llvm/Remarks/Remark.h"
  102. #include "llvm/Remarks/RemarkFormat.h"
  103. #include "llvm/Remarks/RemarkStringTable.h"
  104. #include "llvm/Support/Casting.h"
  105. #include "llvm/Support/CommandLine.h"
  106. #include "llvm/Support/Compiler.h"
  107. #include "llvm/Support/ErrorHandling.h"
  108. #include "llvm/Support/Format.h"
  109. #include "llvm/Support/MathExtras.h"
  110. #include "llvm/Support/Path.h"
  111. #include "llvm/Support/TargetRegistry.h"
  112. #include "llvm/Support/Timer.h"
  113. #include "llvm/Support/raw_ostream.h"
  114. #include "llvm/Target/TargetLoweringObjectFile.h"
  115. #include "llvm/Target/TargetMachine.h"
  116. #include "llvm/Target/TargetOptions.h"
  117. #include <algorithm>
  118. #include <cassert>
  119. #include <cinttypes>
  120. #include <cstdint>
  121. #include <iterator>
  122. #include <limits>
  123. #include <memory>
  124. #include <string>
  125. #include <utility>
  126. #include <vector>
  127. using namespace llvm;
  128. #define DEBUG_TYPE "asm-printer"
  129. static const char *const DWARFGroupName = "dwarf";
  130. static const char *const DWARFGroupDescription = "DWARF Emission";
  131. static const char *const DbgTimerName = "emit";
  132. static const char *const DbgTimerDescription = "Debug Info Emission";
  133. static const char *const EHTimerName = "write_exception";
  134. static const char *const EHTimerDescription = "DWARF Exception Writer";
  135. static const char *const CFGuardName = "Control Flow Guard";
  136. static const char *const CFGuardDescription = "Control Flow Guard Tables";
  137. static const char *const CodeViewLineTablesGroupName = "linetables";
  138. static const char *const CodeViewLineTablesGroupDescription =
  139. "CodeView Line Tables";
  140. STATISTIC(EmittedInsts, "Number of machine instrs printed");
  141. static cl::opt<bool> EnableRemarksSection(
  142. "remarks-section",
  143. cl::desc("Emit a section containing remark diagnostics metadata"),
  144. cl::init(false));
  145. char AsmPrinter::ID = 0;
  146. using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>;
  147. static gcp_map_type &getGCMap(void *&P) {
  148. if (!P)
  149. P = new gcp_map_type();
  150. return *(gcp_map_type*)P;
  151. }
  152. /// getGVAlignment - Return the alignment to use for the specified global
  153. /// value. This rounds up to the preferred alignment if possible and legal.
  154. llvm::Align AsmPrinter::getGVAlignment(const GlobalValue *GV,
  155. const DataLayout &DL,
  156. llvm::Align InAlign) {
  157. llvm::Align Align;
  158. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  159. Align = llvm::Align(DL.getPreferredAlignment(GVar));
  160. // If InAlign is specified, round it to it.
  161. if (InAlign > Align)
  162. Align = InAlign;
  163. // If the GV has a specified alignment, take it into account.
  164. const llvm::MaybeAlign GVAlign(GV->getAlignment());
  165. if (!GVAlign)
  166. return Align;
  167. assert(GVAlign && "GVAlign must be set");
  168. // If the GVAlign is larger than NumBits, or if we are required to obey
  169. // NumBits because the GV has an assigned section, obey it.
  170. if (*GVAlign > Align || GV->hasSection())
  171. Align = *GVAlign;
  172. return Align;
  173. }
  174. AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
  175. : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
  176. OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
  177. VerboseAsm = OutStreamer->isVerboseAsm();
  178. }
  179. AsmPrinter::~AsmPrinter() {
  180. assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
  181. if (GCMetadataPrinters) {
  182. gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
  183. delete &GCMap;
  184. GCMetadataPrinters = nullptr;
  185. }
  186. }
  187. bool AsmPrinter::isPositionIndependent() const {
  188. return TM.isPositionIndependent();
  189. }
  190. /// getFunctionNumber - Return a unique ID for the current function.
  191. unsigned AsmPrinter::getFunctionNumber() const {
  192. return MF->getFunctionNumber();
  193. }
  194. const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
  195. return *TM.getObjFileLowering();
  196. }
  197. const DataLayout &AsmPrinter::getDataLayout() const {
  198. return MMI->getModule()->getDataLayout();
  199. }
  200. // Do not use the cached DataLayout because some client use it without a Module
  201. // (dsymutil, llvm-dwarfdump).
  202. unsigned AsmPrinter::getPointerSize() const {
  203. return TM.getPointerSize(0); // FIXME: Default address space
  204. }
  205. const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
  206. assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
  207. return MF->getSubtarget<MCSubtargetInfo>();
  208. }
  209. void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
  210. S.EmitInstruction(Inst, getSubtargetInfo());
  211. }
  212. void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) {
  213. assert(DD && "Dwarf debug file is not defined.");
  214. assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode.");
  215. (void)DD->emitInitialLocDirective(MF, /*CUID=*/0);
  216. }
  217. /// getCurrentSection() - Return the current section we are emitting to.
  218. const MCSection *AsmPrinter::getCurrentSection() const {
  219. return OutStreamer->getCurrentSectionOnly();
  220. }
  221. void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
  222. AU.setPreservesAll();
  223. MachineFunctionPass::getAnalysisUsage(AU);
  224. AU.addRequired<MachineModuleInfo>();
  225. AU.addRequired<MachineOptimizationRemarkEmitterPass>();
  226. AU.addRequired<GCModuleInfo>();
  227. }
  228. bool AsmPrinter::doInitialization(Module &M) {
  229. MMI = getAnalysisIfAvailable<MachineModuleInfo>();
  230. // Initialize TargetLoweringObjectFile.
  231. const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
  232. .Initialize(OutContext, TM);
  233. const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
  234. .getModuleMetadata(M);
  235. OutStreamer->InitSections(false);
  236. // Emit the version-min deployment target directive if needed.
  237. //
  238. // FIXME: If we end up with a collection of these sorts of Darwin-specific
  239. // or ELF-specific things, it may make sense to have a platform helper class
  240. // that will work with the target helper class. For now keep it here, as the
  241. // alternative is duplicated code in each of the target asm printers that
  242. // use the directive, where it would need the same conditionalization
  243. // anyway.
  244. const Triple &Target = TM.getTargetTriple();
  245. OutStreamer->EmitVersionForTarget(Target, M.getSDKVersion());
  246. // Allow the target to emit any magic that it wants at the start of the file.
  247. EmitStartOfAsmFile(M);
  248. // Very minimal debug info. It is ignored if we emit actual debug info. If we
  249. // don't, this at least helps the user find where a global came from.
  250. if (MAI->hasSingleParameterDotFile()) {
  251. // .file "foo.c"
  252. OutStreamer->EmitFileDirective(
  253. llvm::sys::path::filename(M.getSourceFileName()));
  254. }
  255. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  256. assert(MI && "AsmPrinter didn't require GCModuleInfo?");
  257. for (auto &I : *MI)
  258. if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
  259. MP->beginAssembly(M, *MI, *this);
  260. // Emit module-level inline asm if it exists.
  261. if (!M.getModuleInlineAsm().empty()) {
  262. // We're at the module level. Construct MCSubtarget from the default CPU
  263. // and target triple.
  264. std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
  265. TM.getTargetTriple().str(), TM.getTargetCPU(),
  266. TM.getTargetFeatureString()));
  267. OutStreamer->AddComment("Start of file scope inline assembly");
  268. OutStreamer->AddBlankLine();
  269. EmitInlineAsm(M.getModuleInlineAsm()+"\n",
  270. OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
  271. OutStreamer->AddComment("End of file scope inline assembly");
  272. OutStreamer->AddBlankLine();
  273. }
  274. if (MAI->doesSupportDebugInformation()) {
  275. bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
  276. if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
  277. Handlers.emplace_back(std::make_unique<CodeViewDebug>(this),
  278. DbgTimerName, DbgTimerDescription,
  279. CodeViewLineTablesGroupName,
  280. CodeViewLineTablesGroupDescription);
  281. }
  282. if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
  283. DD = new DwarfDebug(this, &M);
  284. DD->beginModule();
  285. Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName,
  286. DbgTimerDescription, DWARFGroupName,
  287. DWARFGroupDescription);
  288. }
  289. }
  290. switch (MAI->getExceptionHandlingType()) {
  291. case ExceptionHandling::SjLj:
  292. case ExceptionHandling::DwarfCFI:
  293. case ExceptionHandling::ARM:
  294. isCFIMoveForDebugging = true;
  295. if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
  296. break;
  297. for (auto &F: M.getFunctionList()) {
  298. // If the module contains any function with unwind data,
  299. // .eh_frame has to be emitted.
  300. // Ignore functions that won't get emitted.
  301. if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) {
  302. isCFIMoveForDebugging = false;
  303. break;
  304. }
  305. }
  306. break;
  307. default:
  308. isCFIMoveForDebugging = false;
  309. break;
  310. }
  311. EHStreamer *ES = nullptr;
  312. switch (MAI->getExceptionHandlingType()) {
  313. case ExceptionHandling::None:
  314. break;
  315. case ExceptionHandling::SjLj:
  316. case ExceptionHandling::DwarfCFI:
  317. ES = new DwarfCFIException(this);
  318. break;
  319. case ExceptionHandling::ARM:
  320. ES = new ARMException(this);
  321. break;
  322. case ExceptionHandling::WinEH:
  323. switch (MAI->getWinEHEncodingType()) {
  324. default: llvm_unreachable("unsupported unwinding information encoding");
  325. case WinEH::EncodingType::Invalid:
  326. break;
  327. case WinEH::EncodingType::X86:
  328. case WinEH::EncodingType::Itanium:
  329. ES = new WinException(this);
  330. break;
  331. }
  332. break;
  333. case ExceptionHandling::Wasm:
  334. ES = new WasmException(this);
  335. break;
  336. }
  337. if (ES)
  338. Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName,
  339. EHTimerDescription, DWARFGroupName,
  340. DWARFGroupDescription);
  341. if (mdconst::extract_or_null<ConstantInt>(
  342. MMI->getModule()->getModuleFlag("cfguardtable")))
  343. Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName,
  344. CFGuardDescription, DWARFGroupName,
  345. DWARFGroupDescription);
  346. return false;
  347. }
  348. static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
  349. if (!MAI.hasWeakDefCanBeHiddenDirective())
  350. return false;
  351. return GV->canBeOmittedFromSymbolTable();
  352. }
  353. void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
  354. GlobalValue::LinkageTypes Linkage = GV->getLinkage();
  355. switch (Linkage) {
  356. case GlobalValue::CommonLinkage:
  357. case GlobalValue::LinkOnceAnyLinkage:
  358. case GlobalValue::LinkOnceODRLinkage:
  359. case GlobalValue::WeakAnyLinkage:
  360. case GlobalValue::WeakODRLinkage:
  361. if (MAI->hasWeakDefDirective()) {
  362. // .globl _foo
  363. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
  364. if (!canBeHidden(GV, *MAI))
  365. // .weak_definition _foo
  366. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
  367. else
  368. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
  369. } else if (MAI->hasLinkOnceDirective()) {
  370. // .globl _foo
  371. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
  372. //NOTE: linkonce is handled by the section the symbol was assigned to.
  373. } else {
  374. // .weak _foo
  375. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
  376. }
  377. return;
  378. case GlobalValue::ExternalLinkage:
  379. // If external, declare as a global symbol: .globl _foo
  380. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
  381. return;
  382. case GlobalValue::PrivateLinkage:
  383. case GlobalValue::InternalLinkage:
  384. return;
  385. case GlobalValue::AppendingLinkage:
  386. case GlobalValue::AvailableExternallyLinkage:
  387. case GlobalValue::ExternalWeakLinkage:
  388. llvm_unreachable("Should never emit this");
  389. }
  390. llvm_unreachable("Unknown linkage type!");
  391. }
  392. void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
  393. const GlobalValue *GV) const {
  394. TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
  395. }
  396. MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
  397. return TM.getSymbol(GV);
  398. }
  399. /// EmitGlobalVariable - Emit the specified global variable to the .s file.
  400. void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
  401. bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
  402. assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
  403. "No emulated TLS variables in the common section");
  404. // Never emit TLS variable xyz in emulated TLS model.
  405. // The initialization value is in __emutls_t.xyz instead of xyz.
  406. if (IsEmuTLSVar)
  407. return;
  408. if (GV->hasInitializer()) {
  409. // Check to see if this is a special global used by LLVM, if so, emit it.
  410. if (EmitSpecialLLVMGlobal(GV))
  411. return;
  412. // Skip the emission of global equivalents. The symbol can be emitted later
  413. // on by emitGlobalGOTEquivs in case it turns out to be needed.
  414. if (GlobalGOTEquivs.count(getSymbol(GV)))
  415. return;
  416. if (isVerbose()) {
  417. // When printing the control variable __emutls_v.*,
  418. // we don't need to print the original TLS variable name.
  419. GV->printAsOperand(OutStreamer->GetCommentOS(),
  420. /*PrintType=*/false, GV->getParent());
  421. OutStreamer->GetCommentOS() << '\n';
  422. }
  423. }
  424. MCSymbol *GVSym = getSymbol(GV);
  425. MCSymbol *EmittedSym = GVSym;
  426. // getOrCreateEmuTLSControlSym only creates the symbol with name and default
  427. // attributes.
  428. // GV's or GVSym's attributes will be used for the EmittedSym.
  429. EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
  430. if (!GV->hasInitializer()) // External globals require no extra code.
  431. return;
  432. GVSym->redefineIfPossible();
  433. if (GVSym->isDefined() || GVSym->isVariable())
  434. report_fatal_error("symbol '" + Twine(GVSym->getName()) +
  435. "' is already defined");
  436. if (MAI->hasDotTypeDotSizeDirective())
  437. OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
  438. SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
  439. const DataLayout &DL = GV->getParent()->getDataLayout();
  440. uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
  441. // If the alignment is specified, we *must* obey it. Overaligning a global
  442. // with a specified alignment is a prompt way to break globals emitted to
  443. // sections and expected to be contiguous (e.g. ObjC metadata).
  444. const llvm::Align Align = getGVAlignment(GV, DL);
  445. for (const HandlerInfo &HI : Handlers) {
  446. NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
  447. HI.TimerGroupName, HI.TimerGroupDescription,
  448. TimePassesIsEnabled);
  449. HI.Handler->setSymbolSize(GVSym, Size);
  450. }
  451. // Handle common symbols
  452. if (GVKind.isCommon()) {
  453. if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
  454. // .comm _foo, 42, 4
  455. const bool SupportsAlignment =
  456. getObjFileLowering().getCommDirectiveSupportsAlignment();
  457. OutStreamer->EmitCommonSymbol(GVSym, Size,
  458. SupportsAlignment ? Align.value() : 0);
  459. return;
  460. }
  461. // Determine to which section this global should be emitted.
  462. MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
  463. // If we have a bss global going to a section that supports the
  464. // zerofill directive, do so here.
  465. if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
  466. TheSection->isVirtualSection()) {
  467. if (Size == 0)
  468. Size = 1; // zerofill of 0 bytes is undefined.
  469. EmitLinkage(GV, GVSym);
  470. // .zerofill __DATA, __bss, _foo, 400, 5
  471. OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align.value());
  472. return;
  473. }
  474. // If this is a BSS local symbol and we are emitting in the BSS
  475. // section use .lcomm/.comm directive.
  476. if (GVKind.isBSSLocal() &&
  477. getObjFileLowering().getBSSSection() == TheSection) {
  478. if (Size == 0)
  479. Size = 1; // .comm Foo, 0 is undefined, avoid it.
  480. // Use .lcomm only if it supports user-specified alignment.
  481. // Otherwise, while it would still be correct to use .lcomm in some
  482. // cases (e.g. when Align == 1), the external assembler might enfore
  483. // some -unknown- default alignment behavior, which could cause
  484. // spurious differences between external and integrated assembler.
  485. // Prefer to simply fall back to .local / .comm in this case.
  486. if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
  487. // .lcomm _foo, 42
  488. OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align.value());
  489. return;
  490. }
  491. // .local _foo
  492. OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
  493. // .comm _foo, 42, 4
  494. const bool SupportsAlignment =
  495. getObjFileLowering().getCommDirectiveSupportsAlignment();
  496. OutStreamer->EmitCommonSymbol(GVSym, Size,
  497. SupportsAlignment ? Align.value() : 0);
  498. return;
  499. }
  500. // Handle thread local data for mach-o which requires us to output an
  501. // additional structure of data and mangle the original symbol so that we
  502. // can reference it later.
  503. //
  504. // TODO: This should become an "emit thread local global" method on TLOF.
  505. // All of this macho specific stuff should be sunk down into TLOFMachO and
  506. // stuff like "TLSExtraDataSection" should no longer be part of the parent
  507. // TLOF class. This will also make it more obvious that stuff like
  508. // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
  509. // specific code.
  510. if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
  511. // Emit the .tbss symbol
  512. MCSymbol *MangSym =
  513. OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
  514. if (GVKind.isThreadBSS()) {
  515. TheSection = getObjFileLowering().getTLSBSSSection();
  516. OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, Align.value());
  517. } else if (GVKind.isThreadData()) {
  518. OutStreamer->SwitchSection(TheSection);
  519. EmitAlignment(Align, GV);
  520. OutStreamer->EmitLabel(MangSym);
  521. EmitGlobalConstant(GV->getParent()->getDataLayout(),
  522. GV->getInitializer());
  523. }
  524. OutStreamer->AddBlankLine();
  525. // Emit the variable struct for the runtime.
  526. MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
  527. OutStreamer->SwitchSection(TLVSect);
  528. // Emit the linkage here.
  529. EmitLinkage(GV, GVSym);
  530. OutStreamer->EmitLabel(GVSym);
  531. // Three pointers in size:
  532. // - __tlv_bootstrap - used to make sure support exists
  533. // - spare pointer, used when mapped by the runtime
  534. // - pointer to mangled symbol above with initializer
  535. unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
  536. OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
  537. PtrSize);
  538. OutStreamer->EmitIntValue(0, PtrSize);
  539. OutStreamer->EmitSymbolValue(MangSym, PtrSize);
  540. OutStreamer->AddBlankLine();
  541. return;
  542. }
  543. MCSymbol *EmittedInitSym = GVSym;
  544. OutStreamer->SwitchSection(TheSection);
  545. EmitLinkage(GV, EmittedInitSym);
  546. EmitAlignment(Align, GV);
  547. OutStreamer->EmitLabel(EmittedInitSym);
  548. EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
  549. if (MAI->hasDotTypeDotSizeDirective())
  550. // .size foo, 42
  551. OutStreamer->emitELFSize(EmittedInitSym,
  552. MCConstantExpr::create(Size, OutContext));
  553. OutStreamer->AddBlankLine();
  554. }
  555. /// Emit the directive and value for debug thread local expression
  556. ///
  557. /// \p Value - The value to emit.
  558. /// \p Size - The size of the integer (in bytes) to emit.
  559. void AsmPrinter::EmitDebugValue(const MCExpr *Value, unsigned Size) const {
  560. OutStreamer->EmitValue(Value, Size);
  561. }
  562. /// EmitFunctionHeader - This method emits the header for the current
  563. /// function.
  564. void AsmPrinter::EmitFunctionHeader() {
  565. const Function &F = MF->getFunction();
  566. if (isVerbose())
  567. OutStreamer->GetCommentOS()
  568. << "-- Begin function "
  569. << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
  570. // Print out constants referenced by the function
  571. EmitConstantPool();
  572. // Print the 'header' of function.
  573. OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(&F, TM));
  574. EmitVisibility(CurrentFnSym, F.getVisibility());
  575. EmitLinkage(&F, CurrentFnSym);
  576. if (MAI->hasFunctionAlignment())
  577. EmitAlignment(MF->getAlignment(), &F);
  578. if (MAI->hasDotTypeDotSizeDirective())
  579. OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
  580. if (F.hasFnAttribute(Attribute::Cold))
  581. OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_Cold);
  582. if (isVerbose()) {
  583. F.printAsOperand(OutStreamer->GetCommentOS(),
  584. /*PrintType=*/false, F.getParent());
  585. OutStreamer->GetCommentOS() << '\n';
  586. }
  587. // Emit the prefix data.
  588. if (F.hasPrefixData()) {
  589. if (MAI->hasSubsectionsViaSymbols()) {
  590. // Preserving prefix data on platforms which use subsections-via-symbols
  591. // is a bit tricky. Here we introduce a symbol for the prefix data
  592. // and use the .alt_entry attribute to mark the function's real entry point
  593. // as an alternative entry point to the prefix-data symbol.
  594. MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
  595. OutStreamer->EmitLabel(PrefixSym);
  596. EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
  597. // Emit an .alt_entry directive for the actual function symbol.
  598. OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
  599. } else {
  600. EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
  601. }
  602. }
  603. // Emit the CurrentFnSym. This is a virtual function to allow targets to
  604. // do their wild and crazy things as required.
  605. EmitFunctionEntryLabel();
  606. // If the function had address-taken blocks that got deleted, then we have
  607. // references to the dangling symbols. Emit them at the start of the function
  608. // so that we don't get references to undefined symbols.
  609. std::vector<MCSymbol*> DeadBlockSyms;
  610. MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
  611. for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
  612. OutStreamer->AddComment("Address taken block that was later removed");
  613. OutStreamer->EmitLabel(DeadBlockSyms[i]);
  614. }
  615. if (CurrentFnBegin) {
  616. if (MAI->useAssignmentForEHBegin()) {
  617. MCSymbol *CurPos = OutContext.createTempSymbol();
  618. OutStreamer->EmitLabel(CurPos);
  619. OutStreamer->EmitAssignment(CurrentFnBegin,
  620. MCSymbolRefExpr::create(CurPos, OutContext));
  621. } else {
  622. OutStreamer->EmitLabel(CurrentFnBegin);
  623. }
  624. }
  625. // Emit pre-function debug and/or EH information.
  626. for (const HandlerInfo &HI : Handlers) {
  627. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  628. HI.TimerGroupDescription, TimePassesIsEnabled);
  629. HI.Handler->beginFunction(MF);
  630. }
  631. // Emit the prologue data.
  632. if (F.hasPrologueData())
  633. EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
  634. }
  635. /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
  636. /// function. This can be overridden by targets as required to do custom stuff.
  637. void AsmPrinter::EmitFunctionEntryLabel() {
  638. CurrentFnSym->redefineIfPossible();
  639. // The function label could have already been emitted if two symbols end up
  640. // conflicting due to asm renaming. Detect this and emit an error.
  641. if (CurrentFnSym->isVariable())
  642. report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
  643. "' is a protected alias");
  644. if (CurrentFnSym->isDefined())
  645. report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
  646. "' label emitted multiple times to assembly file");
  647. return OutStreamer->EmitLabel(CurrentFnSym);
  648. }
  649. /// emitComments - Pretty-print comments for instructions.
  650. static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
  651. const MachineFunction *MF = MI.getMF();
  652. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  653. // Check for spills and reloads
  654. // We assume a single instruction only has a spill or reload, not
  655. // both.
  656. Optional<unsigned> Size;
  657. if ((Size = MI.getRestoreSize(TII))) {
  658. CommentOS << *Size << "-byte Reload\n";
  659. } else if ((Size = MI.getFoldedRestoreSize(TII))) {
  660. if (*Size)
  661. CommentOS << *Size << "-byte Folded Reload\n";
  662. } else if ((Size = MI.getSpillSize(TII))) {
  663. CommentOS << *Size << "-byte Spill\n";
  664. } else if ((Size = MI.getFoldedSpillSize(TII))) {
  665. if (*Size)
  666. CommentOS << *Size << "-byte Folded Spill\n";
  667. }
  668. // Check for spill-induced copies
  669. if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
  670. CommentOS << " Reload Reuse\n";
  671. }
  672. /// emitImplicitDef - This method emits the specified machine instruction
  673. /// that is an implicit def.
  674. void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
  675. Register RegNo = MI->getOperand(0).getReg();
  676. SmallString<128> Str;
  677. raw_svector_ostream OS(Str);
  678. OS << "implicit-def: "
  679. << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
  680. OutStreamer->AddComment(OS.str());
  681. OutStreamer->AddBlankLine();
  682. }
  683. static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
  684. std::string Str;
  685. raw_string_ostream OS(Str);
  686. OS << "kill:";
  687. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  688. const MachineOperand &Op = MI->getOperand(i);
  689. assert(Op.isReg() && "KILL instruction must have only register operands");
  690. OS << ' ' << (Op.isDef() ? "def " : "killed ")
  691. << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
  692. }
  693. AP.OutStreamer->AddComment(OS.str());
  694. AP.OutStreamer->AddBlankLine();
  695. }
  696. /// emitDebugValueComment - This method handles the target-independent form
  697. /// of DBG_VALUE, returning true if it was able to do so. A false return
  698. /// means the target will need to handle MI in EmitInstruction.
  699. static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
  700. // This code handles only the 4-operand target-independent form.
  701. if (MI->getNumOperands() != 4)
  702. return false;
  703. SmallString<128> Str;
  704. raw_svector_ostream OS(Str);
  705. OS << "DEBUG_VALUE: ";
  706. const DILocalVariable *V = MI->getDebugVariable();
  707. if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
  708. StringRef Name = SP->getName();
  709. if (!Name.empty())
  710. OS << Name << ":";
  711. }
  712. OS << V->getName();
  713. OS << " <- ";
  714. // The second operand is only an offset if it's an immediate.
  715. bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
  716. int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0;
  717. const DIExpression *Expr = MI->getDebugExpression();
  718. if (Expr->getNumElements()) {
  719. OS << '[';
  720. bool NeedSep = false;
  721. for (auto Op : Expr->expr_ops()) {
  722. if (NeedSep)
  723. OS << ", ";
  724. else
  725. NeedSep = true;
  726. OS << dwarf::OperationEncodingString(Op.getOp());
  727. for (unsigned I = 0; I < Op.getNumArgs(); ++I)
  728. OS << ' ' << Op.getArg(I);
  729. }
  730. OS << "] ";
  731. }
  732. // Register or immediate value. Register 0 means undef.
  733. if (MI->getOperand(0).isFPImm()) {
  734. APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
  735. if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
  736. OS << (double)APF.convertToFloat();
  737. } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
  738. OS << APF.convertToDouble();
  739. } else {
  740. // There is no good way to print long double. Convert a copy to
  741. // double. Ah well, it's only a comment.
  742. bool ignored;
  743. APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
  744. &ignored);
  745. OS << "(long double) " << APF.convertToDouble();
  746. }
  747. } else if (MI->getOperand(0).isImm()) {
  748. OS << MI->getOperand(0).getImm();
  749. } else if (MI->getOperand(0).isCImm()) {
  750. MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
  751. } else {
  752. unsigned Reg;
  753. if (MI->getOperand(0).isReg()) {
  754. Reg = MI->getOperand(0).getReg();
  755. } else {
  756. assert(MI->getOperand(0).isFI() && "Unknown operand type");
  757. const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
  758. Offset += TFI->getFrameIndexReference(*AP.MF,
  759. MI->getOperand(0).getIndex(), Reg);
  760. MemLoc = true;
  761. }
  762. if (Reg == 0) {
  763. // Suppress offset, it is not meaningful here.
  764. OS << "undef";
  765. // NOTE: Want this comment at start of line, don't emit with AddComment.
  766. AP.OutStreamer->emitRawComment(OS.str());
  767. return true;
  768. }
  769. if (MemLoc)
  770. OS << '[';
  771. OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
  772. }
  773. if (MemLoc)
  774. OS << '+' << Offset << ']';
  775. // NOTE: Want this comment at start of line, don't emit with AddComment.
  776. AP.OutStreamer->emitRawComment(OS.str());
  777. return true;
  778. }
  779. /// This method handles the target-independent form of DBG_LABEL, returning
  780. /// true if it was able to do so. A false return means the target will need
  781. /// to handle MI in EmitInstruction.
  782. static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
  783. if (MI->getNumOperands() != 1)
  784. return false;
  785. SmallString<128> Str;
  786. raw_svector_ostream OS(Str);
  787. OS << "DEBUG_LABEL: ";
  788. const DILabel *V = MI->getDebugLabel();
  789. if (auto *SP = dyn_cast<DISubprogram>(
  790. V->getScope()->getNonLexicalBlockFileScope())) {
  791. StringRef Name = SP->getName();
  792. if (!Name.empty())
  793. OS << Name << ":";
  794. }
  795. OS << V->getName();
  796. // NOTE: Want this comment at start of line, don't emit with AddComment.
  797. AP.OutStreamer->emitRawComment(OS.str());
  798. return true;
  799. }
  800. AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() const {
  801. if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
  802. MF->getFunction().needsUnwindTableEntry())
  803. return CFI_M_EH;
  804. if (MMI->hasDebugInfo())
  805. return CFI_M_Debug;
  806. return CFI_M_None;
  807. }
  808. bool AsmPrinter::needsSEHMoves() {
  809. return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
  810. }
  811. void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
  812. ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
  813. if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
  814. ExceptionHandlingType != ExceptionHandling::ARM)
  815. return;
  816. if (needsCFIMoves() == CFI_M_None)
  817. return;
  818. // If there is no "real" instruction following this CFI instruction, skip
  819. // emitting it; it would be beyond the end of the function's FDE range.
  820. auto *MBB = MI.getParent();
  821. auto I = std::next(MI.getIterator());
  822. while (I != MBB->end() && I->isTransient())
  823. ++I;
  824. if (I == MBB->instr_end() &&
  825. MBB->getReverseIterator() == MBB->getParent()->rbegin())
  826. return;
  827. const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
  828. unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
  829. const MCCFIInstruction &CFI = Instrs[CFIIndex];
  830. emitCFIInstruction(CFI);
  831. }
  832. void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
  833. // The operands are the MCSymbol and the frame offset of the allocation.
  834. MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
  835. int FrameOffset = MI.getOperand(1).getImm();
  836. // Emit a symbol assignment.
  837. OutStreamer->EmitAssignment(FrameAllocSym,
  838. MCConstantExpr::create(FrameOffset, OutContext));
  839. }
  840. void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
  841. if (!MF.getTarget().Options.EmitStackSizeSection)
  842. return;
  843. MCSection *StackSizeSection =
  844. getObjFileLowering().getStackSizesSection(*getCurrentSection());
  845. if (!StackSizeSection)
  846. return;
  847. const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
  848. // Don't emit functions with dynamic stack allocations.
  849. if (FrameInfo.hasVarSizedObjects())
  850. return;
  851. OutStreamer->PushSection();
  852. OutStreamer->SwitchSection(StackSizeSection);
  853. const MCSymbol *FunctionSymbol = getFunctionBegin();
  854. uint64_t StackSize = FrameInfo.getStackSize();
  855. OutStreamer->EmitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
  856. OutStreamer->EmitULEB128IntValue(StackSize);
  857. OutStreamer->PopSection();
  858. }
  859. static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF,
  860. MachineModuleInfo *MMI) {
  861. if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo())
  862. return true;
  863. // We might emit an EH table that uses function begin and end labels even if
  864. // we don't have any landingpads.
  865. if (!MF.getFunction().hasPersonalityFn())
  866. return false;
  867. return !isNoOpWithoutInvoke(
  868. classifyEHPersonality(MF.getFunction().getPersonalityFn()));
  869. }
  870. /// EmitFunctionBody - This method emits the body and trailer for a
  871. /// function.
  872. void AsmPrinter::EmitFunctionBody() {
  873. EmitFunctionHeader();
  874. // Emit target-specific gunk before the function body.
  875. EmitFunctionBodyStart();
  876. bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
  877. if (isVerbose()) {
  878. // Get MachineDominatorTree or compute it on the fly if it's unavailable
  879. MDT = getAnalysisIfAvailable<MachineDominatorTree>();
  880. if (!MDT) {
  881. OwnedMDT = std::make_unique<MachineDominatorTree>();
  882. OwnedMDT->getBase().recalculate(*MF);
  883. MDT = OwnedMDT.get();
  884. }
  885. // Get MachineLoopInfo or compute it on the fly if it's unavailable
  886. MLI = getAnalysisIfAvailable<MachineLoopInfo>();
  887. if (!MLI) {
  888. OwnedMLI = std::make_unique<MachineLoopInfo>();
  889. OwnedMLI->getBase().analyze(MDT->getBase());
  890. MLI = OwnedMLI.get();
  891. }
  892. }
  893. // Print out code for the function.
  894. bool HasAnyRealCode = false;
  895. int NumInstsInFunction = 0;
  896. for (auto &MBB : *MF) {
  897. // Print a label for the basic block.
  898. EmitBasicBlockStart(MBB);
  899. for (auto &MI : MBB) {
  900. // Print the assembly for the instruction.
  901. if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
  902. !MI.isDebugInstr()) {
  903. HasAnyRealCode = true;
  904. ++NumInstsInFunction;
  905. }
  906. // If there is a pre-instruction symbol, emit a label for it here.
  907. if (MCSymbol *S = MI.getPreInstrSymbol())
  908. OutStreamer->EmitLabel(S);
  909. if (ShouldPrintDebugScopes) {
  910. for (const HandlerInfo &HI : Handlers) {
  911. NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
  912. HI.TimerGroupName, HI.TimerGroupDescription,
  913. TimePassesIsEnabled);
  914. HI.Handler->beginInstruction(&MI);
  915. }
  916. }
  917. if (isVerbose())
  918. emitComments(MI, OutStreamer->GetCommentOS());
  919. switch (MI.getOpcode()) {
  920. case TargetOpcode::CFI_INSTRUCTION:
  921. emitCFIInstruction(MI);
  922. break;
  923. case TargetOpcode::LOCAL_ESCAPE:
  924. emitFrameAlloc(MI);
  925. break;
  926. case TargetOpcode::ANNOTATION_LABEL:
  927. case TargetOpcode::EH_LABEL:
  928. case TargetOpcode::GC_LABEL:
  929. OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
  930. break;
  931. case TargetOpcode::INLINEASM:
  932. case TargetOpcode::INLINEASM_BR:
  933. EmitInlineAsm(&MI);
  934. break;
  935. case TargetOpcode::DBG_VALUE:
  936. if (isVerbose()) {
  937. if (!emitDebugValueComment(&MI, *this))
  938. EmitInstruction(&MI);
  939. }
  940. break;
  941. case TargetOpcode::DBG_LABEL:
  942. if (isVerbose()) {
  943. if (!emitDebugLabelComment(&MI, *this))
  944. EmitInstruction(&MI);
  945. }
  946. break;
  947. case TargetOpcode::IMPLICIT_DEF:
  948. if (isVerbose()) emitImplicitDef(&MI);
  949. break;
  950. case TargetOpcode::KILL:
  951. if (isVerbose()) emitKill(&MI, *this);
  952. break;
  953. default:
  954. EmitInstruction(&MI);
  955. break;
  956. }
  957. // If there is a post-instruction symbol, emit a label for it here.
  958. if (MCSymbol *S = MI.getPostInstrSymbol())
  959. OutStreamer->EmitLabel(S);
  960. if (ShouldPrintDebugScopes) {
  961. for (const HandlerInfo &HI : Handlers) {
  962. NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
  963. HI.TimerGroupName, HI.TimerGroupDescription,
  964. TimePassesIsEnabled);
  965. HI.Handler->endInstruction();
  966. }
  967. }
  968. }
  969. EmitBasicBlockEnd(MBB);
  970. }
  971. EmittedInsts += NumInstsInFunction;
  972. MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
  973. MF->getFunction().getSubprogram(),
  974. &MF->front());
  975. R << ore::NV("NumInstructions", NumInstsInFunction)
  976. << " instructions in function";
  977. ORE->emit(R);
  978. // If the function is empty and the object file uses .subsections_via_symbols,
  979. // then we need to emit *something* to the function body to prevent the
  980. // labels from collapsing together. Just emit a noop.
  981. // Similarly, don't emit empty functions on Windows either. It can lead to
  982. // duplicate entries (two functions with the same RVA) in the Guard CF Table
  983. // after linking, causing the kernel not to load the binary:
  984. // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
  985. // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
  986. const Triple &TT = TM.getTargetTriple();
  987. if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
  988. (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
  989. MCInst Noop;
  990. MF->getSubtarget().getInstrInfo()->getNoop(Noop);
  991. // Targets can opt-out of emitting the noop here by leaving the opcode
  992. // unspecified.
  993. if (Noop.getOpcode()) {
  994. OutStreamer->AddComment("avoids zero-length function");
  995. OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
  996. }
  997. }
  998. const Function &F = MF->getFunction();
  999. for (const auto &BB : F) {
  1000. if (!BB.hasAddressTaken())
  1001. continue;
  1002. MCSymbol *Sym = GetBlockAddressSymbol(&BB);
  1003. if (Sym->isDefined())
  1004. continue;
  1005. OutStreamer->AddComment("Address of block that was removed by CodeGen");
  1006. OutStreamer->EmitLabel(Sym);
  1007. }
  1008. // Emit target-specific gunk after the function body.
  1009. EmitFunctionBodyEnd();
  1010. if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) ||
  1011. MAI->hasDotTypeDotSizeDirective()) {
  1012. // Create a symbol for the end of function.
  1013. CurrentFnEnd = createTempSymbol("func_end");
  1014. OutStreamer->EmitLabel(CurrentFnEnd);
  1015. }
  1016. // If the target wants a .size directive for the size of the function, emit
  1017. // it.
  1018. if (MAI->hasDotTypeDotSizeDirective()) {
  1019. // We can get the size as difference between the function label and the
  1020. // temp label.
  1021. const MCExpr *SizeExp = MCBinaryExpr::createSub(
  1022. MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
  1023. MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
  1024. OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
  1025. }
  1026. for (const HandlerInfo &HI : Handlers) {
  1027. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1028. HI.TimerGroupDescription, TimePassesIsEnabled);
  1029. HI.Handler->markFunctionEnd();
  1030. }
  1031. // Print out jump tables referenced by the function.
  1032. EmitJumpTableInfo();
  1033. // Emit post-function debug and/or EH information.
  1034. for (const HandlerInfo &HI : Handlers) {
  1035. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1036. HI.TimerGroupDescription, TimePassesIsEnabled);
  1037. HI.Handler->endFunction(MF);
  1038. }
  1039. // Emit section containing stack size metadata.
  1040. emitStackSizeSection(*MF);
  1041. if (isVerbose())
  1042. OutStreamer->GetCommentOS() << "-- End function\n";
  1043. OutStreamer->AddBlankLine();
  1044. }
  1045. /// Compute the number of Global Variables that uses a Constant.
  1046. static unsigned getNumGlobalVariableUses(const Constant *C) {
  1047. if (!C)
  1048. return 0;
  1049. if (isa<GlobalVariable>(C))
  1050. return 1;
  1051. unsigned NumUses = 0;
  1052. for (auto *CU : C->users())
  1053. NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
  1054. return NumUses;
  1055. }
  1056. /// Only consider global GOT equivalents if at least one user is a
  1057. /// cstexpr inside an initializer of another global variables. Also, don't
  1058. /// handle cstexpr inside instructions. During global variable emission,
  1059. /// candidates are skipped and are emitted later in case at least one cstexpr
  1060. /// isn't replaced by a PC relative GOT entry access.
  1061. static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
  1062. unsigned &NumGOTEquivUsers) {
  1063. // Global GOT equivalents are unnamed private globals with a constant
  1064. // pointer initializer to another global symbol. They must point to a
  1065. // GlobalVariable or Function, i.e., as GlobalValue.
  1066. if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
  1067. !GV->isConstant() || !GV->isDiscardableIfUnused() ||
  1068. !isa<GlobalValue>(GV->getOperand(0)))
  1069. return false;
  1070. // To be a got equivalent, at least one of its users need to be a constant
  1071. // expression used by another global variable.
  1072. for (auto *U : GV->users())
  1073. NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
  1074. return NumGOTEquivUsers > 0;
  1075. }
  1076. /// Unnamed constant global variables solely contaning a pointer to
  1077. /// another globals variable is equivalent to a GOT table entry; it contains the
  1078. /// the address of another symbol. Optimize it and replace accesses to these
  1079. /// "GOT equivalents" by using the GOT entry for the final global instead.
  1080. /// Compute GOT equivalent candidates among all global variables to avoid
  1081. /// emitting them if possible later on, after it use is replaced by a GOT entry
  1082. /// access.
  1083. void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
  1084. if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
  1085. return;
  1086. for (const auto &G : M.globals()) {
  1087. unsigned NumGOTEquivUsers = 0;
  1088. if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
  1089. continue;
  1090. const MCSymbol *GOTEquivSym = getSymbol(&G);
  1091. GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
  1092. }
  1093. }
  1094. /// Constant expressions using GOT equivalent globals may not be eligible
  1095. /// for PC relative GOT entry conversion, in such cases we need to emit such
  1096. /// globals we previously omitted in EmitGlobalVariable.
  1097. void AsmPrinter::emitGlobalGOTEquivs() {
  1098. if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
  1099. return;
  1100. SmallVector<const GlobalVariable *, 8> FailedCandidates;
  1101. for (auto &I : GlobalGOTEquivs) {
  1102. const GlobalVariable *GV = I.second.first;
  1103. unsigned Cnt = I.second.second;
  1104. if (Cnt)
  1105. FailedCandidates.push_back(GV);
  1106. }
  1107. GlobalGOTEquivs.clear();
  1108. for (auto *GV : FailedCandidates)
  1109. EmitGlobalVariable(GV);
  1110. }
  1111. void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
  1112. const GlobalIndirectSymbol& GIS) {
  1113. MCSymbol *Name = getSymbol(&GIS);
  1114. if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
  1115. OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
  1116. else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
  1117. OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
  1118. else
  1119. assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
  1120. bool IsFunction = GIS.getValueType()->isFunctionTy();
  1121. // Treat bitcasts of functions as functions also. This is important at least
  1122. // on WebAssembly where object and function addresses can't alias each other.
  1123. if (!IsFunction)
  1124. if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol()))
  1125. if (CE->getOpcode() == Instruction::BitCast)
  1126. IsFunction =
  1127. CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy();
  1128. // Set the symbol type to function if the alias has a function type.
  1129. // This affects codegen when the aliasee is not a function.
  1130. if (IsFunction)
  1131. OutStreamer->EmitSymbolAttribute(Name, isa<GlobalIFunc>(GIS)
  1132. ? MCSA_ELF_TypeIndFunction
  1133. : MCSA_ELF_TypeFunction);
  1134. EmitVisibility(Name, GIS.getVisibility());
  1135. const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
  1136. if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
  1137. OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
  1138. // Emit the directives as assignments aka .set:
  1139. OutStreamer->EmitAssignment(Name, Expr);
  1140. if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
  1141. // If the aliasee does not correspond to a symbol in the output, i.e. the
  1142. // alias is not of an object or the aliased object is private, then set the
  1143. // size of the alias symbol from the type of the alias. We don't do this in
  1144. // other situations as the alias and aliasee having differing types but same
  1145. // size may be intentional.
  1146. const GlobalObject *BaseObject = GA->getBaseObject();
  1147. if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
  1148. (!BaseObject || BaseObject->hasPrivateLinkage())) {
  1149. const DataLayout &DL = M.getDataLayout();
  1150. uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
  1151. OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
  1152. }
  1153. }
  1154. }
  1155. void AsmPrinter::emitRemarksSection(Module &M) {
  1156. RemarkStreamer *RS = M.getContext().getRemarkStreamer();
  1157. if (!RS)
  1158. return;
  1159. remarks::RemarkSerializer &RemarkSerializer = RS->getSerializer();
  1160. Optional<SmallString<128>> Filename;
  1161. if (Optional<StringRef> FilenameRef = RS->getFilename()) {
  1162. Filename = *FilenameRef;
  1163. sys::fs::make_absolute(*Filename);
  1164. assert(!Filename->empty() && "The filename can't be empty.");
  1165. }
  1166. std::string Buf;
  1167. raw_string_ostream OS(Buf);
  1168. std::unique_ptr<remarks::MetaSerializer> MetaSerializer =
  1169. Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename))
  1170. : RemarkSerializer.metaSerializer(OS);
  1171. MetaSerializer->emit();
  1172. // Switch to the right section: .remarks/__remarks.
  1173. MCSection *RemarksSection =
  1174. OutContext.getObjectFileInfo()->getRemarksSection();
  1175. OutStreamer->SwitchSection(RemarksSection);
  1176. OutStreamer->EmitBinaryData(OS.str());
  1177. }
  1178. bool AsmPrinter::doFinalization(Module &M) {
  1179. // Set the MachineFunction to nullptr so that we can catch attempted
  1180. // accesses to MF specific features at the module level and so that
  1181. // we can conditionalize accesses based on whether or not it is nullptr.
  1182. MF = nullptr;
  1183. // Gather all GOT equivalent globals in the module. We really need two
  1184. // passes over the globals: one to compute and another to avoid its emission
  1185. // in EmitGlobalVariable, otherwise we would not be able to handle cases
  1186. // where the got equivalent shows up before its use.
  1187. computeGlobalGOTEquivs(M);
  1188. // Emit global variables.
  1189. for (const auto &G : M.globals())
  1190. EmitGlobalVariable(&G);
  1191. // Emit remaining GOT equivalent globals.
  1192. emitGlobalGOTEquivs();
  1193. // Emit visibility info for declarations
  1194. for (const Function &F : M) {
  1195. if (!F.isDeclarationForLinker())
  1196. continue;
  1197. GlobalValue::VisibilityTypes V = F.getVisibility();
  1198. if (V == GlobalValue::DefaultVisibility)
  1199. continue;
  1200. MCSymbol *Name = getSymbol(&F);
  1201. EmitVisibility(Name, V, false);
  1202. }
  1203. // Emit the remarks section contents.
  1204. // FIXME: Figure out when is the safest time to emit this section. It should
  1205. // not come after debug info.
  1206. if (EnableRemarksSection)
  1207. emitRemarksSection(M);
  1208. const TargetLoweringObjectFile &TLOF = getObjFileLowering();
  1209. TLOF.emitModuleMetadata(*OutStreamer, M);
  1210. if (TM.getTargetTriple().isOSBinFormatELF()) {
  1211. MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
  1212. // Output stubs for external and common global variables.
  1213. MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
  1214. if (!Stubs.empty()) {
  1215. OutStreamer->SwitchSection(TLOF.getDataSection());
  1216. const DataLayout &DL = M.getDataLayout();
  1217. EmitAlignment(llvm::Align(DL.getPointerSize()));
  1218. for (const auto &Stub : Stubs) {
  1219. OutStreamer->EmitLabel(Stub.first);
  1220. OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
  1221. DL.getPointerSize());
  1222. }
  1223. }
  1224. }
  1225. if (TM.getTargetTriple().isOSBinFormatCOFF()) {
  1226. MachineModuleInfoCOFF &MMICOFF =
  1227. MMI->getObjFileInfo<MachineModuleInfoCOFF>();
  1228. // Output stubs for external and common global variables.
  1229. MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList();
  1230. if (!Stubs.empty()) {
  1231. const DataLayout &DL = M.getDataLayout();
  1232. for (const auto &Stub : Stubs) {
  1233. SmallString<256> SectionName = StringRef(".rdata$");
  1234. SectionName += Stub.first->getName();
  1235. OutStreamer->SwitchSection(OutContext.getCOFFSection(
  1236. SectionName,
  1237. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ |
  1238. COFF::IMAGE_SCN_LNK_COMDAT,
  1239. SectionKind::getReadOnly(), Stub.first->getName(),
  1240. COFF::IMAGE_COMDAT_SELECT_ANY));
  1241. EmitAlignment(llvm::Align(DL.getPointerSize()));
  1242. OutStreamer->EmitSymbolAttribute(Stub.first, MCSA_Global);
  1243. OutStreamer->EmitLabel(Stub.first);
  1244. OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
  1245. DL.getPointerSize());
  1246. }
  1247. }
  1248. }
  1249. // Finalize debug and EH information.
  1250. for (const HandlerInfo &HI : Handlers) {
  1251. NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
  1252. HI.TimerGroupDescription, TimePassesIsEnabled);
  1253. HI.Handler->endModule();
  1254. }
  1255. Handlers.clear();
  1256. DD = nullptr;
  1257. // If the target wants to know about weak references, print them all.
  1258. if (MAI->getWeakRefDirective()) {
  1259. // FIXME: This is not lazy, it would be nice to only print weak references
  1260. // to stuff that is actually used. Note that doing so would require targets
  1261. // to notice uses in operands (due to constant exprs etc). This should
  1262. // happen with the MC stuff eventually.
  1263. // Print out module-level global objects here.
  1264. for (const auto &GO : M.global_objects()) {
  1265. if (!GO.hasExternalWeakLinkage())
  1266. continue;
  1267. OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
  1268. }
  1269. }
  1270. OutStreamer->AddBlankLine();
  1271. // Print aliases in topological order, that is, for each alias a = b,
  1272. // b must be printed before a.
  1273. // This is because on some targets (e.g. PowerPC) linker expects aliases in
  1274. // such an order to generate correct TOC information.
  1275. SmallVector<const GlobalAlias *, 16> AliasStack;
  1276. SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
  1277. for (const auto &Alias : M.aliases()) {
  1278. for (const GlobalAlias *Cur = &Alias; Cur;
  1279. Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
  1280. if (!AliasVisited.insert(Cur).second)
  1281. break;
  1282. AliasStack.push_back(Cur);
  1283. }
  1284. for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
  1285. emitGlobalIndirectSymbol(M, *AncestorAlias);
  1286. AliasStack.clear();
  1287. }
  1288. for (const auto &IFunc : M.ifuncs())
  1289. emitGlobalIndirectSymbol(M, IFunc);
  1290. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  1291. assert(MI && "AsmPrinter didn't require GCModuleInfo?");
  1292. for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
  1293. if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
  1294. MP->finishAssembly(M, *MI, *this);
  1295. // Emit llvm.ident metadata in an '.ident' directive.
  1296. EmitModuleIdents(M);
  1297. // Emit bytes for llvm.commandline metadata.
  1298. EmitModuleCommandLines(M);
  1299. // Emit __morestack address if needed for indirect calls.
  1300. if (MMI->usesMorestackAddr()) {
  1301. unsigned Align = 1;
  1302. MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
  1303. getDataLayout(), SectionKind::getReadOnly(),
  1304. /*C=*/nullptr, Align);
  1305. OutStreamer->SwitchSection(ReadOnlySection);
  1306. MCSymbol *AddrSymbol =
  1307. OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
  1308. OutStreamer->EmitLabel(AddrSymbol);
  1309. unsigned PtrSize = MAI->getCodePointerSize();
  1310. OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
  1311. PtrSize);
  1312. }
  1313. // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
  1314. // split-stack is used.
  1315. if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
  1316. OutStreamer->SwitchSection(
  1317. OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
  1318. if (MMI->hasNosplitStack())
  1319. OutStreamer->SwitchSection(
  1320. OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
  1321. }
  1322. // If we don't have any trampolines, then we don't require stack memory
  1323. // to be executable. Some targets have a directive to declare this.
  1324. Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
  1325. if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
  1326. if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
  1327. OutStreamer->SwitchSection(S);
  1328. if (TM.getTargetTriple().isOSBinFormatCOFF()) {
  1329. // Emit /EXPORT: flags for each exported global as necessary.
  1330. const auto &TLOF = getObjFileLowering();
  1331. std::string Flags;
  1332. for (const GlobalValue &GV : M.global_values()) {
  1333. raw_string_ostream OS(Flags);
  1334. TLOF.emitLinkerFlagsForGlobal(OS, &GV);
  1335. OS.flush();
  1336. if (!Flags.empty()) {
  1337. OutStreamer->SwitchSection(TLOF.getDrectveSection());
  1338. OutStreamer->EmitBytes(Flags);
  1339. }
  1340. Flags.clear();
  1341. }
  1342. // Emit /INCLUDE: flags for each used global as necessary.
  1343. if (const auto *LU = M.getNamedGlobal("llvm.used")) {
  1344. assert(LU->hasInitializer() &&
  1345. "expected llvm.used to have an initializer");
  1346. assert(isa<ArrayType>(LU->getValueType()) &&
  1347. "expected llvm.used to be an array type");
  1348. if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
  1349. for (const Value *Op : A->operands()) {
  1350. const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
  1351. // Global symbols with internal or private linkage are not visible to
  1352. // the linker, and thus would cause an error when the linker tried to
  1353. // preserve the symbol due to the `/include:` directive.
  1354. if (GV->hasLocalLinkage())
  1355. continue;
  1356. raw_string_ostream OS(Flags);
  1357. TLOF.emitLinkerFlagsForUsed(OS, GV);
  1358. OS.flush();
  1359. if (!Flags.empty()) {
  1360. OutStreamer->SwitchSection(TLOF.getDrectveSection());
  1361. OutStreamer->EmitBytes(Flags);
  1362. }
  1363. Flags.clear();
  1364. }
  1365. }
  1366. }
  1367. }
  1368. if (TM.Options.EmitAddrsig) {
  1369. // Emit address-significance attributes for all globals.
  1370. OutStreamer->EmitAddrsig();
  1371. for (const GlobalValue &GV : M.global_values())
  1372. if (!GV.use_empty() && !GV.isThreadLocal() &&
  1373. !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") &&
  1374. !GV.hasAtLeastLocalUnnamedAddr())
  1375. OutStreamer->EmitAddrsigSym(getSymbol(&GV));
  1376. }
  1377. // Emit symbol partition specifications (ELF only).
  1378. if (TM.getTargetTriple().isOSBinFormatELF()) {
  1379. unsigned UniqueID = 0;
  1380. for (const GlobalValue &GV : M.global_values()) {
  1381. if (!GV.hasPartition() || GV.isDeclarationForLinker() ||
  1382. GV.getVisibility() != GlobalValue::DefaultVisibility)
  1383. continue;
  1384. OutStreamer->SwitchSection(OutContext.getELFSection(
  1385. ".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, "", ++UniqueID));
  1386. OutStreamer->EmitBytes(GV.getPartition());
  1387. OutStreamer->EmitZeros(1);
  1388. OutStreamer->EmitValue(
  1389. MCSymbolRefExpr::create(getSymbol(&GV), OutContext),
  1390. MAI->getCodePointerSize());
  1391. }
  1392. }
  1393. // Allow the target to emit any magic that it wants at the end of the file,
  1394. // after everything else has gone out.
  1395. EmitEndOfAsmFile(M);
  1396. MMI = nullptr;
  1397. OutStreamer->Finish();
  1398. OutStreamer->reset();
  1399. OwnedMLI.reset();
  1400. OwnedMDT.reset();
  1401. return false;
  1402. }
  1403. MCSymbol *AsmPrinter::getCurExceptionSym() {
  1404. if (!CurExceptionSym)
  1405. CurExceptionSym = createTempSymbol("exception");
  1406. return CurExceptionSym;
  1407. }
  1408. void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
  1409. this->MF = &MF;
  1410. // Get the function symbol.
  1411. CurrentFnSym = getSymbol(&MF.getFunction());
  1412. CurrentFnSymForSize = CurrentFnSym;
  1413. CurrentFnBegin = nullptr;
  1414. CurExceptionSym = nullptr;
  1415. bool NeedsLocalForSize = MAI->needsLocalForSize();
  1416. if (needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
  1417. MF.getTarget().Options.EmitStackSizeSection) {
  1418. CurrentFnBegin = createTempSymbol("func_begin");
  1419. if (NeedsLocalForSize)
  1420. CurrentFnSymForSize = CurrentFnBegin;
  1421. }
  1422. ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
  1423. }
  1424. namespace {
  1425. // Keep track the alignment, constpool entries per Section.
  1426. struct SectionCPs {
  1427. MCSection *S;
  1428. unsigned Alignment;
  1429. SmallVector<unsigned, 4> CPEs;
  1430. SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
  1431. };
  1432. } // end anonymous namespace
  1433. /// EmitConstantPool - Print to the current output stream assembly
  1434. /// representations of the constants in the constant pool MCP. This is
  1435. /// used to print out constants which have been "spilled to memory" by
  1436. /// the code generator.
  1437. void AsmPrinter::EmitConstantPool() {
  1438. const MachineConstantPool *MCP = MF->getConstantPool();
  1439. const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
  1440. if (CP.empty()) return;
  1441. // Calculate sections for constant pool entries. We collect entries to go into
  1442. // the same section together to reduce amount of section switch statements.
  1443. SmallVector<SectionCPs, 4> CPSections;
  1444. for (unsigned i = 0, e = CP.size(); i != e; ++i) {
  1445. const MachineConstantPoolEntry &CPE = CP[i];
  1446. unsigned Align = CPE.getAlignment();
  1447. SectionKind Kind = CPE.getSectionKind(&getDataLayout());
  1448. const Constant *C = nullptr;
  1449. if (!CPE.isMachineConstantPoolEntry())
  1450. C = CPE.Val.ConstVal;
  1451. MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
  1452. Kind, C, Align);
  1453. // The number of sections are small, just do a linear search from the
  1454. // last section to the first.
  1455. bool Found = false;
  1456. unsigned SecIdx = CPSections.size();
  1457. while (SecIdx != 0) {
  1458. if (CPSections[--SecIdx].S == S) {
  1459. Found = true;
  1460. break;
  1461. }
  1462. }
  1463. if (!Found) {
  1464. SecIdx = CPSections.size();
  1465. CPSections.push_back(SectionCPs(S, Align));
  1466. }
  1467. if (Align > CPSections[SecIdx].Alignment)
  1468. CPSections[SecIdx].Alignment = Align;
  1469. CPSections[SecIdx].CPEs.push_back(i);
  1470. }
  1471. // Now print stuff into the calculated sections.
  1472. const MCSection *CurSection = nullptr;
  1473. unsigned Offset = 0;
  1474. for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
  1475. for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
  1476. unsigned CPI = CPSections[i].CPEs[j];
  1477. MCSymbol *Sym = GetCPISymbol(CPI);
  1478. if (!Sym->isUndefined())
  1479. continue;
  1480. if (CurSection != CPSections[i].S) {
  1481. OutStreamer->SwitchSection(CPSections[i].S);
  1482. EmitAlignment(llvm::Align(CPSections[i].Alignment));
  1483. CurSection = CPSections[i].S;
  1484. Offset = 0;
  1485. }
  1486. MachineConstantPoolEntry CPE = CP[CPI];
  1487. // Emit inter-object padding for alignment.
  1488. unsigned AlignMask = CPE.getAlignment() - 1;
  1489. unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
  1490. OutStreamer->EmitZeros(NewOffset - Offset);
  1491. Type *Ty = CPE.getType();
  1492. Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
  1493. OutStreamer->EmitLabel(Sym);
  1494. if (CPE.isMachineConstantPoolEntry())
  1495. EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
  1496. else
  1497. EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
  1498. }
  1499. }
  1500. }
  1501. /// EmitJumpTableInfo - Print assembly representations of the jump tables used
  1502. /// by the current function to the current output stream.
  1503. void AsmPrinter::EmitJumpTableInfo() {
  1504. const DataLayout &DL = MF->getDataLayout();
  1505. const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
  1506. if (!MJTI) return;
  1507. if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
  1508. const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
  1509. if (JT.empty()) return;
  1510. // Pick the directive to use to print the jump table entries, and switch to
  1511. // the appropriate section.
  1512. const Function &F = MF->getFunction();
  1513. const TargetLoweringObjectFile &TLOF = getObjFileLowering();
  1514. bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
  1515. MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
  1516. F);
  1517. if (JTInDiffSection) {
  1518. // Drop it in the readonly section.
  1519. MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
  1520. OutStreamer->SwitchSection(ReadOnlySection);
  1521. }
  1522. EmitAlignment(llvm::Align(MJTI->getEntryAlignment(DL)));
  1523. // Jump tables in code sections are marked with a data_region directive
  1524. // where that's supported.
  1525. if (!JTInDiffSection)
  1526. OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
  1527. for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
  1528. const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
  1529. // If this jump table was deleted, ignore it.
  1530. if (JTBBs.empty()) continue;
  1531. // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
  1532. /// emit a .set directive for each unique entry.
  1533. if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
  1534. MAI->doesSetDirectiveSuppressReloc()) {
  1535. SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
  1536. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  1537. const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
  1538. for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
  1539. const MachineBasicBlock *MBB = JTBBs[ii];
  1540. if (!EmittedSets.insert(MBB).second)
  1541. continue;
  1542. // .set LJTSet, LBB32-base
  1543. const MCExpr *LHS =
  1544. MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
  1545. OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
  1546. MCBinaryExpr::createSub(LHS, Base,
  1547. OutContext));
  1548. }
  1549. }
  1550. // On some targets (e.g. Darwin) we want to emit two consecutive labels
  1551. // before each jump table. The first label is never referenced, but tells
  1552. // the assembler and linker the extents of the jump table object. The
  1553. // second label is actually referenced by the code.
  1554. if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
  1555. // FIXME: This doesn't have to have any specific name, just any randomly
  1556. // named and numbered 'l' label would work. Simplify GetJTISymbol.
  1557. OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
  1558. OutStreamer->EmitLabel(GetJTISymbol(JTI));
  1559. for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
  1560. EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
  1561. }
  1562. if (!JTInDiffSection)
  1563. OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
  1564. }
  1565. /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
  1566. /// current stream.
  1567. void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
  1568. const MachineBasicBlock *MBB,
  1569. unsigned UID) const {
  1570. assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
  1571. const MCExpr *Value = nullptr;
  1572. switch (MJTI->getEntryKind()) {
  1573. case MachineJumpTableInfo::EK_Inline:
  1574. llvm_unreachable("Cannot emit EK_Inline jump table entry");
  1575. case MachineJumpTableInfo::EK_Custom32:
  1576. Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
  1577. MJTI, MBB, UID, OutContext);
  1578. break;
  1579. case MachineJumpTableInfo::EK_BlockAddress:
  1580. // EK_BlockAddress - Each entry is a plain address of block, e.g.:
  1581. // .word LBB123
  1582. Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
  1583. break;
  1584. case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
  1585. // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
  1586. // with a relocation as gp-relative, e.g.:
  1587. // .gprel32 LBB123
  1588. MCSymbol *MBBSym = MBB->getSymbol();
  1589. OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
  1590. return;
  1591. }
  1592. case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
  1593. // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
  1594. // with a relocation as gp-relative, e.g.:
  1595. // .gpdword LBB123
  1596. MCSymbol *MBBSym = MBB->getSymbol();
  1597. OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
  1598. return;
  1599. }
  1600. case MachineJumpTableInfo::EK_LabelDifference32: {
  1601. // Each entry is the address of the block minus the address of the jump
  1602. // table. This is used for PIC jump tables where gprel32 is not supported.
  1603. // e.g.:
  1604. // .word LBB123 - LJTI1_2
  1605. // If the .set directive avoids relocations, this is emitted as:
  1606. // .set L4_5_set_123, LBB123 - LJTI1_2
  1607. // .word L4_5_set_123
  1608. if (MAI->doesSetDirectiveSuppressReloc()) {
  1609. Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
  1610. OutContext);
  1611. break;
  1612. }
  1613. Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
  1614. const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
  1615. const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
  1616. Value = MCBinaryExpr::createSub(Value, Base, OutContext);
  1617. break;
  1618. }
  1619. }
  1620. assert(Value && "Unknown entry kind!");
  1621. unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
  1622. OutStreamer->EmitValue(Value, EntrySize);
  1623. }
  1624. /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
  1625. /// special global used by LLVM. If so, emit it and return true, otherwise
  1626. /// do nothing and return false.
  1627. bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
  1628. if (GV->getName() == "llvm.used") {
  1629. if (MAI->hasNoDeadStrip()) // No need to emit this at all.
  1630. EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
  1631. return true;
  1632. }
  1633. // Ignore debug and non-emitted data. This handles llvm.compiler.used.
  1634. if (GV->getSection() == "llvm.metadata" ||
  1635. GV->hasAvailableExternallyLinkage())
  1636. return true;
  1637. if (!GV->hasAppendingLinkage()) return false;
  1638. assert(GV->hasInitializer() && "Not a special LLVM global!");
  1639. if (GV->getName() == "llvm.global_ctors") {
  1640. EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
  1641. /* isCtor */ true);
  1642. return true;
  1643. }
  1644. if (GV->getName() == "llvm.global_dtors") {
  1645. EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
  1646. /* isCtor */ false);
  1647. return true;
  1648. }
  1649. report_fatal_error("unknown special variable");
  1650. }
  1651. /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
  1652. /// global in the specified llvm.used list.
  1653. void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
  1654. // Should be an array of 'i8*'.
  1655. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
  1656. const GlobalValue *GV =
  1657. dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
  1658. if (GV)
  1659. OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
  1660. }
  1661. }
  1662. namespace {
  1663. struct Structor {
  1664. int Priority = 0;
  1665. Constant *Func = nullptr;
  1666. GlobalValue *ComdatKey = nullptr;
  1667. Structor() = default;
  1668. };
  1669. } // end anonymous namespace
  1670. /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
  1671. /// priority.
  1672. void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
  1673. bool isCtor) {
  1674. // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the
  1675. // init priority.
  1676. if (!isa<ConstantArray>(List)) return;
  1677. // Sanity check the structors list.
  1678. const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
  1679. if (!InitList) return; // Not an array!
  1680. StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
  1681. if (!ETy || ETy->getNumElements() != 3 ||
  1682. !isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
  1683. !isa<PointerType>(ETy->getTypeAtIndex(1U)) ||
  1684. !isa<PointerType>(ETy->getTypeAtIndex(2U)))
  1685. return; // Not (int, ptr, ptr).
  1686. // Gather the structors in a form that's convenient for sorting by priority.
  1687. SmallVector<Structor, 8> Structors;
  1688. for (Value *O : InitList->operands()) {
  1689. ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
  1690. if (!CS) continue; // Malformed.
  1691. if (CS->getOperand(1)->isNullValue())
  1692. break; // Found a null terminator, skip the rest.
  1693. ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
  1694. if (!Priority) continue; // Malformed.
  1695. Structors.push_back(Structor());
  1696. Structor &S = Structors.back();
  1697. S.Priority = Priority->getLimitedValue(65535);
  1698. S.Func = CS->getOperand(1);
  1699. if (!CS->getOperand(2)->isNullValue())
  1700. S.ComdatKey =
  1701. dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
  1702. }
  1703. // Emit the function pointers in the target-specific order
  1704. const llvm::Align Align = llvm::Align(DL.getPointerPrefAlignment());
  1705. llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) {
  1706. return L.Priority < R.Priority;
  1707. });
  1708. for (Structor &S : Structors) {
  1709. const TargetLoweringObjectFile &Obj = getObjFileLowering();
  1710. const MCSymbol *KeySym = nullptr;
  1711. if (GlobalValue *GV = S.ComdatKey) {
  1712. if (GV->isDeclarationForLinker())
  1713. // If the associated variable is not defined in this module
  1714. // (it might be available_externally, or have been an
  1715. // available_externally definition that was dropped by the
  1716. // EliminateAvailableExternally pass), some other TU
  1717. // will provide its dynamic initializer.
  1718. continue;
  1719. KeySym = getSymbol(GV);
  1720. }
  1721. MCSection *OutputSection =
  1722. (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
  1723. : Obj.getStaticDtorSection(S.Priority, KeySym));
  1724. OutStreamer->SwitchSection(OutputSection);
  1725. if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
  1726. EmitAlignment(Align);
  1727. EmitXXStructor(DL, S.Func);
  1728. }
  1729. }
  1730. void AsmPrinter::EmitModuleIdents(Module &M) {
  1731. if (!MAI->hasIdentDirective())
  1732. return;
  1733. if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
  1734. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  1735. const MDNode *N = NMD->getOperand(i);
  1736. assert(N->getNumOperands() == 1 &&
  1737. "llvm.ident metadata entry can have only one operand");
  1738. const MDString *S = cast<MDString>(N->getOperand(0));
  1739. OutStreamer->EmitIdent(S->getString());
  1740. }
  1741. }
  1742. }
  1743. void AsmPrinter::EmitModuleCommandLines(Module &M) {
  1744. MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines();
  1745. if (!CommandLine)
  1746. return;
  1747. const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline");
  1748. if (!NMD || !NMD->getNumOperands())
  1749. return;
  1750. OutStreamer->PushSection();
  1751. OutStreamer->SwitchSection(CommandLine);
  1752. OutStreamer->EmitZeros(1);
  1753. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  1754. const MDNode *N = NMD->getOperand(i);
  1755. assert(N->getNumOperands() == 1 &&
  1756. "llvm.commandline metadata entry can have only one operand");
  1757. const MDString *S = cast<MDString>(N->getOperand(0));
  1758. OutStreamer->EmitBytes(S->getString());
  1759. OutStreamer->EmitZeros(1);
  1760. }
  1761. OutStreamer->PopSection();
  1762. }
  1763. //===--------------------------------------------------------------------===//
  1764. // Emission and print routines
  1765. //
  1766. /// Emit a byte directive and value.
  1767. ///
  1768. void AsmPrinter::emitInt8(int Value) const {
  1769. OutStreamer->EmitIntValue(Value, 1);
  1770. }
  1771. /// Emit a short directive and value.
  1772. void AsmPrinter::emitInt16(int Value) const {
  1773. OutStreamer->EmitIntValue(Value, 2);
  1774. }
  1775. /// Emit a long directive and value.
  1776. void AsmPrinter::emitInt32(int Value) const {
  1777. OutStreamer->EmitIntValue(Value, 4);
  1778. }
  1779. /// Emit a long long directive and value.
  1780. void AsmPrinter::emitInt64(uint64_t Value) const {
  1781. OutStreamer->EmitIntValue(Value, 8);
  1782. }
  1783. /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
  1784. /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
  1785. /// .set if it avoids relocations.
  1786. void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
  1787. unsigned Size) const {
  1788. OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
  1789. }
  1790. /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
  1791. /// where the size in bytes of the directive is specified by Size and Label
  1792. /// specifies the label. This implicitly uses .set if it is available.
  1793. void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
  1794. unsigned Size,
  1795. bool IsSectionRelative) const {
  1796. if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
  1797. OutStreamer->EmitCOFFSecRel32(Label, Offset);
  1798. if (Size > 4)
  1799. OutStreamer->EmitZeros(Size - 4);
  1800. return;
  1801. }
  1802. // Emit Label+Offset (or just Label if Offset is zero)
  1803. const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
  1804. if (Offset)
  1805. Expr = MCBinaryExpr::createAdd(
  1806. Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
  1807. OutStreamer->EmitValue(Expr, Size);
  1808. }
  1809. //===----------------------------------------------------------------------===//
  1810. // EmitAlignment - Emit an alignment directive to the specified power of
  1811. // two boundary. If a global value is specified, and if that global has
  1812. // an explicit alignment requested, it will override the alignment request
  1813. // if required for correctness.
  1814. void AsmPrinter::EmitAlignment(llvm::Align Align,
  1815. const GlobalObject *GV) const {
  1816. if (GV)
  1817. Align = getGVAlignment(GV, GV->getParent()->getDataLayout(), Align);
  1818. if (Align == 1)
  1819. return; // 1-byte aligned: no need to emit alignment.
  1820. if (getCurrentSection()->getKind().isText())
  1821. OutStreamer->EmitCodeAlignment(Align.value());
  1822. else
  1823. OutStreamer->EmitValueToAlignment(Align.value());
  1824. }
  1825. //===----------------------------------------------------------------------===//
  1826. // Constant emission.
  1827. //===----------------------------------------------------------------------===//
  1828. const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
  1829. MCContext &Ctx = OutContext;
  1830. if (CV->isNullValue() || isa<UndefValue>(CV))
  1831. return MCConstantExpr::create(0, Ctx);
  1832. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
  1833. return MCConstantExpr::create(CI->getZExtValue(), Ctx);
  1834. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
  1835. return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
  1836. if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
  1837. return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
  1838. const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
  1839. if (!CE) {
  1840. llvm_unreachable("Unknown constant value to lower!");
  1841. }
  1842. switch (CE->getOpcode()) {
  1843. default:
  1844. // If the code isn't optimized, there may be outstanding folding
  1845. // opportunities. Attempt to fold the expression using DataLayout as a
  1846. // last resort before giving up.
  1847. if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
  1848. if (C != CE)
  1849. return lowerConstant(C);
  1850. // Otherwise report the problem to the user.
  1851. {
  1852. std::string S;
  1853. raw_string_ostream OS(S);
  1854. OS << "Unsupported expression in static initializer: ";
  1855. CE->printAsOperand(OS, /*PrintType=*/false,
  1856. !MF ? nullptr : MF->getFunction().getParent());
  1857. report_fatal_error(OS.str());
  1858. }
  1859. case Instruction::GetElementPtr: {
  1860. // Generate a symbolic expression for the byte address
  1861. APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
  1862. cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
  1863. const MCExpr *Base = lowerConstant(CE->getOperand(0));
  1864. if (!OffsetAI)
  1865. return Base;
  1866. int64_t Offset = OffsetAI.getSExtValue();
  1867. return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
  1868. Ctx);
  1869. }
  1870. case Instruction::Trunc:
  1871. // We emit the value and depend on the assembler to truncate the generated
  1872. // expression properly. This is important for differences between
  1873. // blockaddress labels. Since the two labels are in the same function, it
  1874. // is reasonable to treat their delta as a 32-bit value.
  1875. LLVM_FALLTHROUGH;
  1876. case Instruction::BitCast:
  1877. return lowerConstant(CE->getOperand(0));
  1878. case Instruction::IntToPtr: {
  1879. const DataLayout &DL = getDataLayout();
  1880. // Handle casts to pointers by changing them into casts to the appropriate
  1881. // integer type. This promotes constant folding and simplifies this code.
  1882. Constant *Op = CE->getOperand(0);
  1883. Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
  1884. false/*ZExt*/);
  1885. return lowerConstant(Op);
  1886. }
  1887. case Instruction::PtrToInt: {
  1888. const DataLayout &DL = getDataLayout();
  1889. // Support only foldable casts to/from pointers that can be eliminated by
  1890. // changing the pointer to the appropriately sized integer type.
  1891. Constant *Op = CE->getOperand(0);
  1892. Type *Ty = CE->getType();
  1893. const MCExpr *OpExpr = lowerConstant(Op);
  1894. // We can emit the pointer value into this slot if the slot is an
  1895. // integer slot equal to the size of the pointer.
  1896. //
  1897. // If the pointer is larger than the resultant integer, then
  1898. // as with Trunc just depend on the assembler to truncate it.
  1899. if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType()))
  1900. return OpExpr;
  1901. // Otherwise the pointer is smaller than the resultant integer, mask off
  1902. // the high bits so we are sure to get a proper truncation if the input is
  1903. // a constant expr.
  1904. unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
  1905. const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
  1906. return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
  1907. }
  1908. case Instruction::Sub: {
  1909. GlobalValue *LHSGV;
  1910. APInt LHSOffset;
  1911. if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
  1912. getDataLayout())) {
  1913. GlobalValue *RHSGV;
  1914. APInt RHSOffset;
  1915. if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
  1916. getDataLayout())) {
  1917. const MCExpr *RelocExpr =
  1918. getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
  1919. if (!RelocExpr)
  1920. RelocExpr = MCBinaryExpr::createSub(
  1921. MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
  1922. MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
  1923. int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
  1924. if (Addend != 0)
  1925. RelocExpr = MCBinaryExpr::createAdd(
  1926. RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
  1927. return RelocExpr;
  1928. }
  1929. }
  1930. }
  1931. // else fallthrough
  1932. LLVM_FALLTHROUGH;
  1933. // The MC library also has a right-shift operator, but it isn't consistently
  1934. // signed or unsigned between different targets.
  1935. case Instruction::Add:
  1936. case Instruction::Mul:
  1937. case Instruction::SDiv:
  1938. case Instruction::SRem:
  1939. case Instruction::Shl:
  1940. case Instruction::And:
  1941. case Instruction::Or:
  1942. case Instruction::Xor: {
  1943. const MCExpr *LHS = lowerConstant(CE->getOperand(0));
  1944. const MCExpr *RHS = lowerConstant(CE->getOperand(1));
  1945. switch (CE->getOpcode()) {
  1946. default: llvm_unreachable("Unknown binary operator constant cast expr");
  1947. case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
  1948. case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  1949. case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
  1950. case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
  1951. case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
  1952. case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
  1953. case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
  1954. case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx);
  1955. case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
  1956. }
  1957. }
  1958. }
  1959. }
  1960. static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
  1961. AsmPrinter &AP,
  1962. const Constant *BaseCV = nullptr,
  1963. uint64_t Offset = 0);
  1964. static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
  1965. static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
  1966. /// isRepeatedByteSequence - Determine whether the given value is
  1967. /// composed of a repeated sequence of identical bytes and return the
  1968. /// byte value. If it is not a repeated sequence, return -1.
  1969. static int isRepeatedByteSequence(const ConstantDataSequential *V) {
  1970. StringRef Data = V->getRawDataValues();
  1971. assert(!Data.empty() && "Empty aggregates should be CAZ node");
  1972. char C = Data[0];
  1973. for (unsigned i = 1, e = Data.size(); i != e; ++i)
  1974. if (Data[i] != C) return -1;
  1975. return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
  1976. }
  1977. /// isRepeatedByteSequence - Determine whether the given value is
  1978. /// composed of a repeated sequence of identical bytes and return the
  1979. /// byte value. If it is not a repeated sequence, return -1.
  1980. static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
  1981. if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  1982. uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
  1983. assert(Size % 8 == 0);
  1984. // Extend the element to take zero padding into account.
  1985. APInt Value = CI->getValue().zextOrSelf(Size);
  1986. if (!Value.isSplat(8))
  1987. return -1;
  1988. return Value.zextOrTrunc(8).getZExtValue();
  1989. }
  1990. if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
  1991. // Make sure all array elements are sequences of the same repeated
  1992. // byte.
  1993. assert(CA->getNumOperands() != 0 && "Should be a CAZ");
  1994. Constant *Op0 = CA->getOperand(0);
  1995. int Byte = isRepeatedByteSequence(Op0, DL);
  1996. if (Byte == -1)
  1997. return -1;
  1998. // All array elements must be equal.
  1999. for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
  2000. if (CA->getOperand(i) != Op0)
  2001. return -1;
  2002. return Byte;
  2003. }
  2004. if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
  2005. return isRepeatedByteSequence(CDS);
  2006. return -1;
  2007. }
  2008. static void emitGlobalConstantDataSequential(const DataLayout &DL,
  2009. const ConstantDataSequential *CDS,
  2010. AsmPrinter &AP) {
  2011. // See if we can aggregate this into a .fill, if so, emit it as such.
  2012. int Value = isRepeatedByteSequence(CDS, DL);
  2013. if (Value != -1) {
  2014. uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
  2015. // Don't emit a 1-byte object as a .fill.
  2016. if (Bytes > 1)
  2017. return AP.OutStreamer->emitFill(Bytes, Value);
  2018. }
  2019. // If this can be emitted with .ascii/.asciz, emit it as such.
  2020. if (CDS->isString())
  2021. return AP.OutStreamer->EmitBytes(CDS->getAsString());
  2022. // Otherwise, emit the values in successive locations.
  2023. unsigned ElementByteSize = CDS->getElementByteSize();
  2024. if (isa<IntegerType>(CDS->getElementType())) {
  2025. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  2026. if (AP.isVerbose())
  2027. AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
  2028. CDS->getElementAsInteger(i));
  2029. AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
  2030. ElementByteSize);
  2031. }
  2032. } else {
  2033. Type *ET = CDS->getElementType();
  2034. for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
  2035. emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
  2036. }
  2037. unsigned Size = DL.getTypeAllocSize(CDS->getType());
  2038. unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
  2039. CDS->getNumElements();
  2040. assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
  2041. if (unsigned Padding = Size - EmittedSize)
  2042. AP.OutStreamer->EmitZeros(Padding);
  2043. }
  2044. static void emitGlobalConstantArray(const DataLayout &DL,
  2045. const ConstantArray *CA, AsmPrinter &AP,
  2046. const Constant *BaseCV, uint64_t Offset) {
  2047. // See if we can aggregate some values. Make sure it can be
  2048. // represented as a series of bytes of the constant value.
  2049. int Value = isRepeatedByteSequence(CA, DL);
  2050. if (Value != -1) {
  2051. uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
  2052. AP.OutStreamer->emitFill(Bytes, Value);
  2053. }
  2054. else {
  2055. for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
  2056. emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
  2057. Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
  2058. }
  2059. }
  2060. }
  2061. static void emitGlobalConstantVector(const DataLayout &DL,
  2062. const ConstantVector *CV, AsmPrinter &AP) {
  2063. for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
  2064. emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
  2065. unsigned Size = DL.getTypeAllocSize(CV->getType());
  2066. unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
  2067. CV->getType()->getNumElements();
  2068. if (unsigned Padding = Size - EmittedSize)
  2069. AP.OutStreamer->EmitZeros(Padding);
  2070. }
  2071. static void emitGlobalConstantStruct(const DataLayout &DL,
  2072. const ConstantStruct *CS, AsmPrinter &AP,
  2073. const Constant *BaseCV, uint64_t Offset) {
  2074. // Print the fields in successive locations. Pad to align if needed!
  2075. unsigned Size = DL.getTypeAllocSize(CS->getType());
  2076. const StructLayout *Layout = DL.getStructLayout(CS->getType());
  2077. uint64_t SizeSoFar = 0;
  2078. for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
  2079. const Constant *Field = CS->getOperand(i);
  2080. // Print the actual field value.
  2081. emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
  2082. // Check if padding is needed and insert one or more 0s.
  2083. uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
  2084. uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
  2085. - Layout->getElementOffset(i)) - FieldSize;
  2086. SizeSoFar += FieldSize + PadSize;
  2087. // Insert padding - this may include padding to increase the size of the
  2088. // current field up to the ABI size (if the struct is not packed) as well
  2089. // as padding to ensure that the next field starts at the right offset.
  2090. AP.OutStreamer->EmitZeros(PadSize);
  2091. }
  2092. assert(SizeSoFar == Layout->getSizeInBytes() &&
  2093. "Layout of constant struct may be incorrect!");
  2094. }
  2095. static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
  2096. APInt API = APF.bitcastToAPInt();
  2097. // First print a comment with what we think the original floating-point value
  2098. // should have been.
  2099. if (AP.isVerbose()) {
  2100. SmallString<8> StrVal;
  2101. APF.toString(StrVal);
  2102. if (ET)
  2103. ET->print(AP.OutStreamer->GetCommentOS());
  2104. else
  2105. AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
  2106. AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
  2107. }
  2108. // Now iterate through the APInt chunks, emitting them in endian-correct
  2109. // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
  2110. // floats).
  2111. unsigned NumBytes = API.getBitWidth() / 8;
  2112. unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
  2113. const uint64_t *p = API.getRawData();
  2114. // PPC's long double has odd notions of endianness compared to how LLVM
  2115. // handles it: p[0] goes first for *big* endian on PPC.
  2116. if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
  2117. int Chunk = API.getNumWords() - 1;
  2118. if (TrailingBytes)
  2119. AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
  2120. for (; Chunk >= 0; --Chunk)
  2121. AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
  2122. } else {
  2123. unsigned Chunk;
  2124. for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
  2125. AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
  2126. if (TrailingBytes)
  2127. AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
  2128. }
  2129. // Emit the tail padding for the long double.
  2130. const DataLayout &DL = AP.getDataLayout();
  2131. AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
  2132. }
  2133. static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
  2134. emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
  2135. }
  2136. static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
  2137. const DataLayout &DL = AP.getDataLayout();
  2138. unsigned BitWidth = CI->getBitWidth();
  2139. // Copy the value as we may massage the layout for constants whose bit width
  2140. // is not a multiple of 64-bits.
  2141. APInt Realigned(CI->getValue());
  2142. uint64_t ExtraBits = 0;
  2143. unsigned ExtraBitsSize = BitWidth & 63;
  2144. if (ExtraBitsSize) {
  2145. // The bit width of the data is not a multiple of 64-bits.
  2146. // The extra bits are expected to be at the end of the chunk of the memory.
  2147. // Little endian:
  2148. // * Nothing to be done, just record the extra bits to emit.
  2149. // Big endian:
  2150. // * Record the extra bits to emit.
  2151. // * Realign the raw data to emit the chunks of 64-bits.
  2152. if (DL.isBigEndian()) {
  2153. // Basically the structure of the raw data is a chunk of 64-bits cells:
  2154. // 0 1 BitWidth / 64
  2155. // [chunk1][chunk2] ... [chunkN].
  2156. // The most significant chunk is chunkN and it should be emitted first.
  2157. // However, due to the alignment issue chunkN contains useless bits.
  2158. // Realign the chunks so that they contain only useless information:
  2159. // ExtraBits 0 1 (BitWidth / 64) - 1
  2160. // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
  2161. ExtraBits = Realigned.getRawData()[0] &
  2162. (((uint64_t)-1) >> (64 - ExtraBitsSize));
  2163. Realigned.lshrInPlace(ExtraBitsSize);
  2164. } else
  2165. ExtraBits = Realigned.getRawData()[BitWidth / 64];
  2166. }
  2167. // We don't expect assemblers to support integer data directives
  2168. // for more than 64 bits, so we emit the data in at most 64-bit
  2169. // quantities at a time.
  2170. const uint64_t *RawData = Realigned.getRawData();
  2171. for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
  2172. uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
  2173. AP.OutStreamer->EmitIntValue(Val, 8);
  2174. }
  2175. if (ExtraBitsSize) {
  2176. // Emit the extra bits after the 64-bits chunks.
  2177. // Emit a directive that fills the expected size.
  2178. uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
  2179. Size -= (BitWidth / 64) * 8;
  2180. assert(Size && Size * 8 >= ExtraBitsSize &&
  2181. (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
  2182. == ExtraBits && "Directive too small for extra bits.");
  2183. AP.OutStreamer->EmitIntValue(ExtraBits, Size);
  2184. }
  2185. }
  2186. /// Transform a not absolute MCExpr containing a reference to a GOT
  2187. /// equivalent global, by a target specific GOT pc relative access to the
  2188. /// final symbol.
  2189. static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
  2190. const Constant *BaseCst,
  2191. uint64_t Offset) {
  2192. // The global @foo below illustrates a global that uses a got equivalent.
  2193. //
  2194. // @bar = global i32 42
  2195. // @gotequiv = private unnamed_addr constant i32* @bar
  2196. // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
  2197. // i64 ptrtoint (i32* @foo to i64))
  2198. // to i32)
  2199. //
  2200. // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
  2201. // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
  2202. // form:
  2203. //
  2204. // foo = cstexpr, where
  2205. // cstexpr := <gotequiv> - "." + <cst>
  2206. // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
  2207. //
  2208. // After canonicalization by evaluateAsRelocatable `ME` turns into:
  2209. //
  2210. // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
  2211. // gotpcrelcst := <offset from @foo base> + <cst>
  2212. MCValue MV;
  2213. if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
  2214. return;
  2215. const MCSymbolRefExpr *SymA = MV.getSymA();
  2216. if (!SymA)
  2217. return;
  2218. // Check that GOT equivalent symbol is cached.
  2219. const MCSymbol *GOTEquivSym = &SymA->getSymbol();
  2220. if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
  2221. return;
  2222. const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
  2223. if (!BaseGV)
  2224. return;
  2225. // Check for a valid base symbol
  2226. const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
  2227. const MCSymbolRefExpr *SymB = MV.getSymB();
  2228. if (!SymB || BaseSym != &SymB->getSymbol())
  2229. return;
  2230. // Make sure to match:
  2231. //
  2232. // gotpcrelcst := <offset from @foo base> + <cst>
  2233. //
  2234. // If gotpcrelcst is positive it means that we can safely fold the pc rel
  2235. // displacement into the GOTPCREL. We can also can have an extra offset <cst>
  2236. // if the target knows how to encode it.
  2237. int64_t GOTPCRelCst = Offset + MV.getConstant();
  2238. if (GOTPCRelCst < 0)
  2239. return;
  2240. if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
  2241. return;
  2242. // Emit the GOT PC relative to replace the got equivalent global, i.e.:
  2243. //
  2244. // bar:
  2245. // .long 42
  2246. // gotequiv:
  2247. // .quad bar
  2248. // foo:
  2249. // .long gotequiv - "." + <cst>
  2250. //
  2251. // is replaced by the target specific equivalent to:
  2252. //
  2253. // bar:
  2254. // .long 42
  2255. // foo:
  2256. // .long bar@GOTPCREL+<gotpcrelcst>
  2257. AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
  2258. const GlobalVariable *GV = Result.first;
  2259. int NumUses = (int)Result.second;
  2260. const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
  2261. const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
  2262. *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
  2263. FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
  2264. // Update GOT equivalent usage information
  2265. --NumUses;
  2266. if (NumUses >= 0)
  2267. AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
  2268. }
  2269. static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
  2270. AsmPrinter &AP, const Constant *BaseCV,
  2271. uint64_t Offset) {
  2272. uint64_t Size = DL.getTypeAllocSize(CV->getType());
  2273. // Globals with sub-elements such as combinations of arrays and structs
  2274. // are handled recursively by emitGlobalConstantImpl. Keep track of the
  2275. // constant symbol base and the current position with BaseCV and Offset.
  2276. if (!BaseCV && CV->hasOneUse())
  2277. BaseCV = dyn_cast<Constant>(CV->user_back());
  2278. if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
  2279. return AP.OutStreamer->EmitZeros(Size);
  2280. if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  2281. switch (Size) {
  2282. case 1:
  2283. case 2:
  2284. case 4:
  2285. case 8:
  2286. if (AP.isVerbose())
  2287. AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
  2288. CI->getZExtValue());
  2289. AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
  2290. return;
  2291. default:
  2292. emitGlobalConstantLargeInt(CI, AP);
  2293. return;
  2294. }
  2295. }
  2296. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
  2297. return emitGlobalConstantFP(CFP, AP);
  2298. if (isa<ConstantPointerNull>(CV)) {
  2299. AP.OutStreamer->EmitIntValue(0, Size);
  2300. return;
  2301. }
  2302. if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
  2303. return emitGlobalConstantDataSequential(DL, CDS, AP);
  2304. if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
  2305. return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
  2306. if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
  2307. return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
  2308. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  2309. // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
  2310. // vectors).
  2311. if (CE->getOpcode() == Instruction::BitCast)
  2312. return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
  2313. if (Size > 8) {
  2314. // If the constant expression's size is greater than 64-bits, then we have
  2315. // to emit the value in chunks. Try to constant fold the value and emit it
  2316. // that way.
  2317. Constant *New = ConstantFoldConstant(CE, DL);
  2318. if (New && New != CE)
  2319. return emitGlobalConstantImpl(DL, New, AP);
  2320. }
  2321. }
  2322. if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
  2323. return emitGlobalConstantVector(DL, V, AP);
  2324. // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it
  2325. // thread the streamer with EmitValue.
  2326. const MCExpr *ME = AP.lowerConstant(CV);
  2327. // Since lowerConstant already folded and got rid of all IR pointer and
  2328. // integer casts, detect GOT equivalent accesses by looking into the MCExpr
  2329. // directly.
  2330. if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
  2331. handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
  2332. AP.OutStreamer->EmitValue(ME, Size);
  2333. }
  2334. /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
  2335. void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
  2336. uint64_t Size = DL.getTypeAllocSize(CV->getType());
  2337. if (Size)
  2338. emitGlobalConstantImpl(DL, CV, *this);
  2339. else if (MAI->hasSubsectionsViaSymbols()) {
  2340. // If the global has zero size, emit a single byte so that two labels don't
  2341. // look like they are at the same location.
  2342. OutStreamer->EmitIntValue(0, 1);
  2343. }
  2344. }
  2345. void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
  2346. // Target doesn't support this yet!
  2347. llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
  2348. }
  2349. void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
  2350. if (Offset > 0)
  2351. OS << '+' << Offset;
  2352. else if (Offset < 0)
  2353. OS << Offset;
  2354. }
  2355. //===----------------------------------------------------------------------===//
  2356. // Symbol Lowering Routines.
  2357. //===----------------------------------------------------------------------===//
  2358. MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
  2359. return OutContext.createTempSymbol(Name, true);
  2360. }
  2361. MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
  2362. return MMI->getAddrLabelSymbol(BA->getBasicBlock());
  2363. }
  2364. MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
  2365. return MMI->getAddrLabelSymbol(BB);
  2366. }
  2367. /// GetCPISymbol - Return the symbol for the specified constant pool entry.
  2368. MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
  2369. if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) {
  2370. const MachineConstantPoolEntry &CPE =
  2371. MF->getConstantPool()->getConstants()[CPID];
  2372. if (!CPE.isMachineConstantPoolEntry()) {
  2373. const DataLayout &DL = MF->getDataLayout();
  2374. SectionKind Kind = CPE.getSectionKind(&DL);
  2375. const Constant *C = CPE.Val.ConstVal;
  2376. unsigned Align = CPE.Alignment;
  2377. if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>(
  2378. getObjFileLowering().getSectionForConstant(DL, Kind, C, Align))) {
  2379. if (MCSymbol *Sym = S->getCOMDATSymbol()) {
  2380. if (Sym->isUndefined())
  2381. OutStreamer->EmitSymbolAttribute(Sym, MCSA_Global);
  2382. return Sym;
  2383. }
  2384. }
  2385. }
  2386. }
  2387. const DataLayout &DL = getDataLayout();
  2388. return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  2389. "CPI" + Twine(getFunctionNumber()) + "_" +
  2390. Twine(CPID));
  2391. }
  2392. /// GetJTISymbol - Return the symbol for the specified jump table entry.
  2393. MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
  2394. return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
  2395. }
  2396. /// GetJTSetSymbol - Return the symbol for the specified jump table .set
  2397. /// FIXME: privatize to AsmPrinter.
  2398. MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
  2399. const DataLayout &DL = getDataLayout();
  2400. return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
  2401. Twine(getFunctionNumber()) + "_" +
  2402. Twine(UID) + "_set_" + Twine(MBBID));
  2403. }
  2404. MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
  2405. StringRef Suffix) const {
  2406. return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
  2407. }
  2408. /// Return the MCSymbol for the specified ExternalSymbol.
  2409. MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
  2410. SmallString<60> NameStr;
  2411. Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
  2412. return OutContext.getOrCreateSymbol(NameStr);
  2413. }
  2414. /// PrintParentLoopComment - Print comments about parent loops of this one.
  2415. static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
  2416. unsigned FunctionNumber) {
  2417. if (!Loop) return;
  2418. PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
  2419. OS.indent(Loop->getLoopDepth()*2)
  2420. << "Parent Loop BB" << FunctionNumber << "_"
  2421. << Loop->getHeader()->getNumber()
  2422. << " Depth=" << Loop->getLoopDepth() << '\n';
  2423. }
  2424. /// PrintChildLoopComment - Print comments about child loops within
  2425. /// the loop for this basic block, with nesting.
  2426. static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
  2427. unsigned FunctionNumber) {
  2428. // Add child loop information
  2429. for (const MachineLoop *CL : *Loop) {
  2430. OS.indent(CL->getLoopDepth()*2)
  2431. << "Child Loop BB" << FunctionNumber << "_"
  2432. << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
  2433. << '\n';
  2434. PrintChildLoopComment(OS, CL, FunctionNumber);
  2435. }
  2436. }
  2437. /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
  2438. static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
  2439. const MachineLoopInfo *LI,
  2440. const AsmPrinter &AP) {
  2441. // Add loop depth information
  2442. const MachineLoop *Loop = LI->getLoopFor(&MBB);
  2443. if (!Loop) return;
  2444. MachineBasicBlock *Header = Loop->getHeader();
  2445. assert(Header && "No header for loop");
  2446. // If this block is not a loop header, just print out what is the loop header
  2447. // and return.
  2448. if (Header != &MBB) {
  2449. AP.OutStreamer->AddComment(" in Loop: Header=BB" +
  2450. Twine(AP.getFunctionNumber())+"_" +
  2451. Twine(Loop->getHeader()->getNumber())+
  2452. " Depth="+Twine(Loop->getLoopDepth()));
  2453. return;
  2454. }
  2455. // Otherwise, it is a loop header. Print out information about child and
  2456. // parent loops.
  2457. raw_ostream &OS = AP.OutStreamer->GetCommentOS();
  2458. PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
  2459. OS << "=>";
  2460. OS.indent(Loop->getLoopDepth()*2-2);
  2461. OS << "This ";
  2462. if (Loop->empty())
  2463. OS << "Inner ";
  2464. OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
  2465. PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
  2466. }
  2467. void AsmPrinter::setupCodePaddingContext(const MachineBasicBlock &MBB,
  2468. MCCodePaddingContext &Context) const {
  2469. assert(MF != nullptr && "Machine function must be valid");
  2470. Context.IsPaddingActive = !MF->hasInlineAsm() &&
  2471. !MF->getFunction().hasOptSize() &&
  2472. TM.getOptLevel() != CodeGenOpt::None;
  2473. Context.IsBasicBlockReachableViaFallthrough =
  2474. std::find(MBB.pred_begin(), MBB.pred_end(), MBB.getPrevNode()) !=
  2475. MBB.pred_end();
  2476. Context.IsBasicBlockReachableViaBranch =
  2477. MBB.pred_size() > 0 && !isBlockOnlyReachableByFallthrough(&MBB);
  2478. }
  2479. /// EmitBasicBlockStart - This method prints the label for the specified
  2480. /// MachineBasicBlock, an alignment (if present) and a comment describing
  2481. /// it if appropriate.
  2482. void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) {
  2483. // End the previous funclet and start a new one.
  2484. if (MBB.isEHFuncletEntry()) {
  2485. for (const HandlerInfo &HI : Handlers) {
  2486. HI.Handler->endFunclet();
  2487. HI.Handler->beginFunclet(MBB);
  2488. }
  2489. }
  2490. // Emit an alignment directive for this block, if needed.
  2491. const llvm::Align Align = MBB.getAlignment();
  2492. if (Align != llvm::Align::None())
  2493. EmitAlignment(Align);
  2494. MCCodePaddingContext Context;
  2495. setupCodePaddingContext(MBB, Context);
  2496. OutStreamer->EmitCodePaddingBasicBlockStart(Context);
  2497. // If the block has its address taken, emit any labels that were used to
  2498. // reference the block. It is possible that there is more than one label
  2499. // here, because multiple LLVM BB's may have been RAUW'd to this block after
  2500. // the references were generated.
  2501. if (MBB.hasAddressTaken()) {
  2502. const BasicBlock *BB = MBB.getBasicBlock();
  2503. if (isVerbose())
  2504. OutStreamer->AddComment("Block address taken");
  2505. // MBBs can have their address taken as part of CodeGen without having
  2506. // their corresponding BB's address taken in IR
  2507. if (BB->hasAddressTaken())
  2508. for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
  2509. OutStreamer->EmitLabel(Sym);
  2510. }
  2511. // Print some verbose block comments.
  2512. if (isVerbose()) {
  2513. if (const BasicBlock *BB = MBB.getBasicBlock()) {
  2514. if (BB->hasName()) {
  2515. BB->printAsOperand(OutStreamer->GetCommentOS(),
  2516. /*PrintType=*/false, BB->getModule());
  2517. OutStreamer->GetCommentOS() << '\n';
  2518. }
  2519. }
  2520. assert(MLI != nullptr && "MachineLoopInfo should has been computed");
  2521. emitBasicBlockLoopComments(MBB, MLI, *this);
  2522. }
  2523. // Print the main label for the block.
  2524. if (MBB.pred_empty() ||
  2525. (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry() &&
  2526. !MBB.hasLabelMustBeEmitted())) {
  2527. if (isVerbose()) {
  2528. // NOTE: Want this comment at start of line, don't emit with AddComment.
  2529. OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
  2530. false);
  2531. }
  2532. } else {
  2533. if (isVerbose() && MBB.hasLabelMustBeEmitted())
  2534. OutStreamer->AddComment("Label of block must be emitted");
  2535. OutStreamer->EmitLabel(MBB.getSymbol());
  2536. }
  2537. }
  2538. void AsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
  2539. MCCodePaddingContext Context;
  2540. setupCodePaddingContext(MBB, Context);
  2541. OutStreamer->EmitCodePaddingBasicBlockEnd(Context);
  2542. }
  2543. void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
  2544. bool IsDefinition) const {
  2545. MCSymbolAttr Attr = MCSA_Invalid;
  2546. switch (Visibility) {
  2547. default: break;
  2548. case GlobalValue::HiddenVisibility:
  2549. if (IsDefinition)
  2550. Attr = MAI->getHiddenVisibilityAttr();
  2551. else
  2552. Attr = MAI->getHiddenDeclarationVisibilityAttr();
  2553. break;
  2554. case GlobalValue::ProtectedVisibility:
  2555. Attr = MAI->getProtectedVisibilityAttr();
  2556. break;
  2557. }
  2558. if (Attr != MCSA_Invalid)
  2559. OutStreamer->EmitSymbolAttribute(Sym, Attr);
  2560. }
  2561. /// isBlockOnlyReachableByFallthough - Return true if the basic block has
  2562. /// exactly one predecessor and the control transfer mechanism between
  2563. /// the predecessor and this block is a fall-through.
  2564. bool AsmPrinter::
  2565. isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
  2566. // If this is a landing pad, it isn't a fall through. If it has no preds,
  2567. // then nothing falls through to it.
  2568. if (MBB->isEHPad() || MBB->pred_empty())
  2569. return false;
  2570. // If there isn't exactly one predecessor, it can't be a fall through.
  2571. if (MBB->pred_size() > 1)
  2572. return false;
  2573. // The predecessor has to be immediately before this block.
  2574. MachineBasicBlock *Pred = *MBB->pred_begin();
  2575. if (!Pred->isLayoutSuccessor(MBB))
  2576. return false;
  2577. // If the block is completely empty, then it definitely does fall through.
  2578. if (Pred->empty())
  2579. return true;
  2580. // Check the terminators in the previous blocks
  2581. for (const auto &MI : Pred->terminators()) {
  2582. // If it is not a simple branch, we are in a table somewhere.
  2583. if (!MI.isBranch() || MI.isIndirectBranch())
  2584. return false;
  2585. // If we are the operands of one of the branches, this is not a fall
  2586. // through. Note that targets with delay slots will usually bundle
  2587. // terminators with the delay slot instruction.
  2588. for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
  2589. if (OP->isJTI())
  2590. return false;
  2591. if (OP->isMBB() && OP->getMBB() == MBB)
  2592. return false;
  2593. }
  2594. }
  2595. return true;
  2596. }
  2597. GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
  2598. if (!S.usesMetadata())
  2599. return nullptr;
  2600. gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
  2601. gcp_map_type::iterator GCPI = GCMap.find(&S);
  2602. if (GCPI != GCMap.end())
  2603. return GCPI->second.get();
  2604. auto Name = S.getName();
  2605. for (GCMetadataPrinterRegistry::iterator
  2606. I = GCMetadataPrinterRegistry::begin(),
  2607. E = GCMetadataPrinterRegistry::end(); I != E; ++I)
  2608. if (Name == I->getName()) {
  2609. std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
  2610. GMP->S = &S;
  2611. auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
  2612. return IterBool.first->second.get();
  2613. }
  2614. report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
  2615. }
  2616. void AsmPrinter::emitStackMaps(StackMaps &SM) {
  2617. GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
  2618. assert(MI && "AsmPrinter didn't require GCModuleInfo?");
  2619. bool NeedsDefault = false;
  2620. if (MI->begin() == MI->end())
  2621. // No GC strategy, use the default format.
  2622. NeedsDefault = true;
  2623. else
  2624. for (auto &I : *MI) {
  2625. if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
  2626. if (MP->emitStackMaps(SM, *this))
  2627. continue;
  2628. // The strategy doesn't have printer or doesn't emit custom stack maps.
  2629. // Use the default format.
  2630. NeedsDefault = true;
  2631. }
  2632. if (NeedsDefault)
  2633. SM.serializeToStackMapSection();
  2634. }
  2635. /// Pin vtable to this file.
  2636. AsmPrinterHandler::~AsmPrinterHandler() = default;
  2637. void AsmPrinterHandler::markFunctionEnd() {}
  2638. // In the binary's "xray_instr_map" section, an array of these function entries
  2639. // describes each instrumentation point. When XRay patches your code, the index
  2640. // into this table will be given to your handler as a patch point identifier.
  2641. void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out,
  2642. const MCSymbol *CurrentFnSym) const {
  2643. Out->EmitSymbolValue(Sled, Bytes);
  2644. Out->EmitSymbolValue(CurrentFnSym, Bytes);
  2645. auto Kind8 = static_cast<uint8_t>(Kind);
  2646. Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
  2647. Out->EmitBinaryData(
  2648. StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
  2649. Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
  2650. auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
  2651. assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
  2652. Out->EmitZeros(Padding);
  2653. }
  2654. void AsmPrinter::emitXRayTable() {
  2655. if (Sleds.empty())
  2656. return;
  2657. auto PrevSection = OutStreamer->getCurrentSectionOnly();
  2658. const Function &F = MF->getFunction();
  2659. MCSection *InstMap = nullptr;
  2660. MCSection *FnSledIndex = nullptr;
  2661. if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) {
  2662. auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym);
  2663. assert(Associated != nullptr);
  2664. auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
  2665. std::string GroupName;
  2666. if (F.hasComdat()) {
  2667. Flags |= ELF::SHF_GROUP;
  2668. GroupName = F.getComdat()->getName();
  2669. }
  2670. auto UniqueID = ++XRayFnUniqueID;
  2671. InstMap =
  2672. OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
  2673. GroupName, UniqueID, Associated);
  2674. FnSledIndex =
  2675. OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
  2676. GroupName, UniqueID, Associated);
  2677. } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
  2678. InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
  2679. SectionKind::getReadOnlyWithRel());
  2680. FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
  2681. SectionKind::getReadOnlyWithRel());
  2682. } else {
  2683. llvm_unreachable("Unsupported target");
  2684. }
  2685. auto WordSizeBytes = MAI->getCodePointerSize();
  2686. // Now we switch to the instrumentation map section. Because this is done
  2687. // per-function, we are able to create an index entry that will represent the
  2688. // range of sleds associated with a function.
  2689. MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
  2690. OutStreamer->SwitchSection(InstMap);
  2691. OutStreamer->EmitLabel(SledsStart);
  2692. for (const auto &Sled : Sleds)
  2693. Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
  2694. MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
  2695. OutStreamer->EmitLabel(SledsEnd);
  2696. // We then emit a single entry in the index per function. We use the symbols
  2697. // that bound the instrumentation map as the range for a specific function.
  2698. // Each entry here will be 2 * word size aligned, as we're writing down two
  2699. // pointers. This should work for both 32-bit and 64-bit platforms.
  2700. OutStreamer->SwitchSection(FnSledIndex);
  2701. OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
  2702. OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
  2703. OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
  2704. OutStreamer->SwitchSection(PrevSection);
  2705. Sleds.clear();
  2706. }
  2707. void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
  2708. SledKind Kind, uint8_t Version) {
  2709. const Function &F = MI.getMF()->getFunction();
  2710. auto Attr = F.getFnAttribute("function-instrument");
  2711. bool LogArgs = F.hasFnAttribute("xray-log-args");
  2712. bool AlwaysInstrument =
  2713. Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
  2714. if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
  2715. Kind = SledKind::LOG_ARGS_ENTER;
  2716. Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
  2717. AlwaysInstrument, &F, Version});
  2718. }
  2719. uint16_t AsmPrinter::getDwarfVersion() const {
  2720. return OutStreamer->getContext().getDwarfVersion();
  2721. }
  2722. void AsmPrinter::setDwarfVersion(uint16_t Version) {
  2723. OutStreamer->getContext().setDwarfVersion(Version);
  2724. }