PPCAsmPrinter.cpp 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823
  1. //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
  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 contains a printer that converts from our internal representation
  10. // of machine-dependent LLVM code to PowerPC assembly language. This printer is
  11. // the output mechanism used by `llc'.
  12. //
  13. // Documentation at http://developer.apple.com/documentation/DeveloperTools/
  14. // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "MCTargetDesc/PPCInstPrinter.h"
  18. #include "MCTargetDesc/PPCMCExpr.h"
  19. #include "MCTargetDesc/PPCMCTargetDesc.h"
  20. #include "MCTargetDesc/PPCPredicates.h"
  21. #include "PPC.h"
  22. #include "PPCInstrInfo.h"
  23. #include "PPCMachineFunctionInfo.h"
  24. #include "PPCSubtarget.h"
  25. #include "PPCTargetMachine.h"
  26. #include "PPCTargetStreamer.h"
  27. #include "TargetInfo/PowerPCTargetInfo.h"
  28. #include "llvm/ADT/MapVector.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/StringRef.h"
  31. #include "llvm/ADT/Triple.h"
  32. #include "llvm/ADT/Twine.h"
  33. #include "llvm/BinaryFormat/ELF.h"
  34. #include "llvm/CodeGen/AsmPrinter.h"
  35. #include "llvm/CodeGen/MachineBasicBlock.h"
  36. #include "llvm/CodeGen/MachineFrameInfo.h"
  37. #include "llvm/CodeGen/MachineFunction.h"
  38. #include "llvm/CodeGen/MachineInstr.h"
  39. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  40. #include "llvm/CodeGen/MachineOperand.h"
  41. #include "llvm/CodeGen/MachineRegisterInfo.h"
  42. #include "llvm/CodeGen/StackMaps.h"
  43. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  44. #include "llvm/IR/DataLayout.h"
  45. #include "llvm/IR/GlobalValue.h"
  46. #include "llvm/IR/GlobalVariable.h"
  47. #include "llvm/IR/Module.h"
  48. #include "llvm/MC/MCAsmInfo.h"
  49. #include "llvm/MC/MCContext.h"
  50. #include "llvm/MC/MCDirectives.h"
  51. #include "llvm/MC/MCExpr.h"
  52. #include "llvm/MC/MCInst.h"
  53. #include "llvm/MC/MCInstBuilder.h"
  54. #include "llvm/MC/MCSectionELF.h"
  55. #include "llvm/MC/MCSectionXCOFF.h"
  56. #include "llvm/MC/MCStreamer.h"
  57. #include "llvm/MC/MCSymbol.h"
  58. #include "llvm/MC/MCSymbolELF.h"
  59. #include "llvm/MC/MCSymbolXCOFF.h"
  60. #include "llvm/MC/SectionKind.h"
  61. #include "llvm/MC/TargetRegistry.h"
  62. #include "llvm/Support/Casting.h"
  63. #include "llvm/Support/CodeGen.h"
  64. #include "llvm/Support/Debug.h"
  65. #include "llvm/Support/Error.h"
  66. #include "llvm/Support/ErrorHandling.h"
  67. #include "llvm/Support/Process.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. #include "llvm/Target/TargetMachine.h"
  70. #include "llvm/Transforms/Utils/ModuleUtils.h"
  71. #include <algorithm>
  72. #include <cassert>
  73. #include <cstdint>
  74. #include <memory>
  75. #include <new>
  76. using namespace llvm;
  77. using namespace llvm::XCOFF;
  78. #define DEBUG_TYPE "asmprinter"
  79. static cl::opt<bool> EnableSSPCanaryBitInTB(
  80. "aix-ssp-tb-bit", cl::init(false),
  81. cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden);
  82. // Specialize DenseMapInfo to allow
  83. // std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap.
  84. // This specialization is needed here because that type is used as keys in the
  85. // map representing TOC entries.
  86. namespace llvm {
  87. template <>
  88. struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> {
  89. using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>;
  90. static inline TOCKey getEmptyKey() {
  91. return {nullptr, MCSymbolRefExpr::VariantKind::VK_None};
  92. }
  93. static inline TOCKey getTombstoneKey() {
  94. return {nullptr, MCSymbolRefExpr::VariantKind::VK_Invalid};
  95. }
  96. static unsigned getHashValue(const TOCKey &PairVal) {
  97. return detail::combineHashValue(
  98. DenseMapInfo<const MCSymbol *>::getHashValue(PairVal.first),
  99. DenseMapInfo<int>::getHashValue(PairVal.second));
  100. }
  101. static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; }
  102. };
  103. } // end namespace llvm
  104. namespace {
  105. enum {
  106. // GNU attribute tags for PowerPC ABI
  107. Tag_GNU_Power_ABI_FP = 4,
  108. Tag_GNU_Power_ABI_Vector = 8,
  109. Tag_GNU_Power_ABI_Struct_Return = 12,
  110. // GNU attribute values for PowerPC float ABI, as combination of two parts
  111. Val_GNU_Power_ABI_NoFloat = 0b00,
  112. Val_GNU_Power_ABI_HardFloat_DP = 0b01,
  113. Val_GNU_Power_ABI_SoftFloat_DP = 0b10,
  114. Val_GNU_Power_ABI_HardFloat_SP = 0b11,
  115. Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100,
  116. Val_GNU_Power_ABI_LDBL_64 = 0b1000,
  117. Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100,
  118. };
  119. class PPCAsmPrinter : public AsmPrinter {
  120. protected:
  121. // For TLS on AIX, we need to be able to identify TOC entries of specific
  122. // VariantKind so we can add the right relocations when we generate the
  123. // entries. So each entry is represented by a pair of MCSymbol and
  124. // VariantKind. For example, we need to be able to identify the following
  125. // entry as a TLSGD entry so we can add the @m relocation:
  126. // .tc .i[TC],i[TL]@m
  127. // By default, VK_None is used for the VariantKind.
  128. MapVector<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>,
  129. MCSymbol *>
  130. TOC;
  131. const PPCSubtarget *Subtarget = nullptr;
  132. public:
  133. explicit PPCAsmPrinter(TargetMachine &TM,
  134. std::unique_ptr<MCStreamer> Streamer)
  135. : AsmPrinter(TM, std::move(Streamer)) {}
  136. StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
  137. MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym,
  138. MCSymbolRefExpr::VariantKind Kind =
  139. MCSymbolRefExpr::VariantKind::VK_None);
  140. bool doInitialization(Module &M) override {
  141. if (!TOC.empty())
  142. TOC.clear();
  143. return AsmPrinter::doInitialization(M);
  144. }
  145. void emitInstruction(const MachineInstr *MI) override;
  146. /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
  147. /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
  148. /// The \p MI would be INLINEASM ONLY.
  149. void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
  150. void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
  151. bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
  152. const char *ExtraCode, raw_ostream &O) override;
  153. bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
  154. const char *ExtraCode, raw_ostream &O) override;
  155. void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
  156. void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
  157. void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
  158. bool runOnMachineFunction(MachineFunction &MF) override {
  159. Subtarget = &MF.getSubtarget<PPCSubtarget>();
  160. bool Changed = AsmPrinter::runOnMachineFunction(MF);
  161. emitXRayTable();
  162. return Changed;
  163. }
  164. };
  165. /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
  166. class PPCLinuxAsmPrinter : public PPCAsmPrinter {
  167. public:
  168. explicit PPCLinuxAsmPrinter(TargetMachine &TM,
  169. std::unique_ptr<MCStreamer> Streamer)
  170. : PPCAsmPrinter(TM, std::move(Streamer)) {}
  171. StringRef getPassName() const override {
  172. return "Linux PPC Assembly Printer";
  173. }
  174. void emitGNUAttributes(Module &M);
  175. void emitStartOfAsmFile(Module &M) override;
  176. void emitEndOfAsmFile(Module &) override;
  177. void emitFunctionEntryLabel() override;
  178. void emitFunctionBodyStart() override;
  179. void emitFunctionBodyEnd() override;
  180. void emitInstruction(const MachineInstr *MI) override;
  181. };
  182. class PPCAIXAsmPrinter : public PPCAsmPrinter {
  183. private:
  184. /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
  185. /// linkage for them in AIX.
  186. SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
  187. /// A format indicator and unique trailing identifier to form part of the
  188. /// sinit/sterm function names.
  189. std::string FormatIndicatorAndUniqueModId;
  190. // Record a list of GlobalAlias associated with a GlobalObject.
  191. // This is used for AIX's extra-label-at-definition aliasing strategy.
  192. DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>>
  193. GOAliasMap;
  194. uint16_t getNumberOfVRSaved();
  195. void emitTracebackTable();
  196. SmallVector<const GlobalVariable *, 8> TOCDataGlobalVars;
  197. void emitGlobalVariableHelper(const GlobalVariable *);
  198. // Get the offset of an alias based on its AliaseeObject.
  199. uint64_t getAliasOffset(const Constant *C);
  200. public:
  201. PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
  202. : PPCAsmPrinter(TM, std::move(Streamer)) {
  203. if (MAI->isLittleEndian())
  204. report_fatal_error(
  205. "cannot create AIX PPC Assembly Printer for a little-endian target");
  206. }
  207. StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
  208. bool doInitialization(Module &M) override;
  209. void emitXXStructorList(const DataLayout &DL, const Constant *List,
  210. bool IsCtor) override;
  211. void SetupMachineFunction(MachineFunction &MF) override;
  212. void emitGlobalVariable(const GlobalVariable *GV) override;
  213. void emitFunctionDescriptor() override;
  214. void emitFunctionEntryLabel() override;
  215. void emitFunctionBodyEnd() override;
  216. void emitPGORefs();
  217. void emitEndOfAsmFile(Module &) override;
  218. void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
  219. void emitInstruction(const MachineInstr *MI) override;
  220. bool doFinalization(Module &M) override;
  221. void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
  222. };
  223. } // end anonymous namespace
  224. void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
  225. raw_ostream &O) {
  226. // Computing the address of a global symbol, not calling it.
  227. const GlobalValue *GV = MO.getGlobal();
  228. getSymbol(GV)->print(O, MAI);
  229. printOffset(MO.getOffset(), O);
  230. }
  231. void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
  232. raw_ostream &O) {
  233. const DataLayout &DL = getDataLayout();
  234. const MachineOperand &MO = MI->getOperand(OpNo);
  235. switch (MO.getType()) {
  236. case MachineOperand::MO_Register: {
  237. // The MI is INLINEASM ONLY and UseVSXReg is always false.
  238. const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
  239. // Linux assembler (Others?) does not take register mnemonics.
  240. // FIXME - What about special registers used in mfspr/mtspr?
  241. O << PPCRegisterInfo::stripRegisterPrefix(RegName);
  242. return;
  243. }
  244. case MachineOperand::MO_Immediate:
  245. O << MO.getImm();
  246. return;
  247. case MachineOperand::MO_MachineBasicBlock:
  248. MO.getMBB()->getSymbol()->print(O, MAI);
  249. return;
  250. case MachineOperand::MO_ConstantPoolIndex:
  251. O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
  252. << MO.getIndex();
  253. return;
  254. case MachineOperand::MO_BlockAddress:
  255. GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
  256. return;
  257. case MachineOperand::MO_GlobalAddress: {
  258. PrintSymbolOperand(MO, O);
  259. return;
  260. }
  261. default:
  262. O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
  263. return;
  264. }
  265. }
  266. /// PrintAsmOperand - Print out an operand for an inline asm expression.
  267. ///
  268. bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
  269. const char *ExtraCode, raw_ostream &O) {
  270. // Does this asm operand have a single letter operand modifier?
  271. if (ExtraCode && ExtraCode[0]) {
  272. if (ExtraCode[1] != 0) return true; // Unknown modifier.
  273. switch (ExtraCode[0]) {
  274. default:
  275. // See if this is a generic print operand
  276. return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
  277. case 'L': // Write second word of DImode reference.
  278. // Verify that this operand has two consecutive registers.
  279. if (!MI->getOperand(OpNo).isReg() ||
  280. OpNo+1 == MI->getNumOperands() ||
  281. !MI->getOperand(OpNo+1).isReg())
  282. return true;
  283. ++OpNo; // Return the high-part.
  284. break;
  285. case 'I':
  286. // Write 'i' if an integer constant, otherwise nothing. Used to print
  287. // addi vs add, etc.
  288. if (MI->getOperand(OpNo).isImm())
  289. O << "i";
  290. return false;
  291. case 'x':
  292. if(!MI->getOperand(OpNo).isReg())
  293. return true;
  294. // This operand uses VSX numbering.
  295. // If the operand is a VMX register, convert it to a VSX register.
  296. Register Reg = MI->getOperand(OpNo).getReg();
  297. if (PPCInstrInfo::isVRRegister(Reg))
  298. Reg = PPC::VSX32 + (Reg - PPC::V0);
  299. else if (PPCInstrInfo::isVFRegister(Reg))
  300. Reg = PPC::VSX32 + (Reg - PPC::VF0);
  301. const char *RegName;
  302. RegName = PPCInstPrinter::getRegisterName(Reg);
  303. RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
  304. O << RegName;
  305. return false;
  306. }
  307. }
  308. printOperand(MI, OpNo, O);
  309. return false;
  310. }
  311. // At the moment, all inline asm memory operands are a single register.
  312. // In any case, the output of this routine should always be just one
  313. // assembler operand.
  314. bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
  315. const char *ExtraCode,
  316. raw_ostream &O) {
  317. if (ExtraCode && ExtraCode[0]) {
  318. if (ExtraCode[1] != 0) return true; // Unknown modifier.
  319. switch (ExtraCode[0]) {
  320. default: return true; // Unknown modifier.
  321. case 'L': // A memory reference to the upper word of a double word op.
  322. O << getDataLayout().getPointerSize() << "(";
  323. printOperand(MI, OpNo, O);
  324. O << ")";
  325. return false;
  326. case 'y': // A memory reference for an X-form instruction
  327. O << "0, ";
  328. printOperand(MI, OpNo, O);
  329. return false;
  330. case 'I':
  331. // Write 'i' if an integer constant, otherwise nothing. Used to print
  332. // addi vs add, etc.
  333. if (MI->getOperand(OpNo).isImm())
  334. O << "i";
  335. return false;
  336. case 'U': // Print 'u' for update form.
  337. case 'X': // Print 'x' for indexed form.
  338. // FIXME: Currently for PowerPC memory operands are always loaded
  339. // into a register, so we never get an update or indexed form.
  340. // This is bad even for offset forms, since even if we know we
  341. // have a value in -16(r1), we will generate a load into r<n>
  342. // and then load from 0(r<n>). Until that issue is fixed,
  343. // tolerate 'U' and 'X' but don't output anything.
  344. assert(MI->getOperand(OpNo).isReg());
  345. return false;
  346. }
  347. }
  348. assert(MI->getOperand(OpNo).isReg());
  349. O << "0(";
  350. printOperand(MI, OpNo, O);
  351. O << ")";
  352. return false;
  353. }
  354. /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
  355. /// exists for it. If not, create one. Then return a symbol that references
  356. /// the TOC entry.
  357. MCSymbol *
  358. PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym,
  359. MCSymbolRefExpr::VariantKind Kind) {
  360. MCSymbol *&TOCEntry = TOC[{Sym, Kind}];
  361. if (!TOCEntry)
  362. TOCEntry = createTempSymbol("C");
  363. return TOCEntry;
  364. }
  365. void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
  366. unsigned NumNOPBytes = MI.getOperand(1).getImm();
  367. auto &Ctx = OutStreamer->getContext();
  368. MCSymbol *MILabel = Ctx.createTempSymbol();
  369. OutStreamer->emitLabel(MILabel);
  370. SM.recordStackMap(*MILabel, MI);
  371. assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
  372. // Scan ahead to trim the shadow.
  373. const MachineBasicBlock &MBB = *MI.getParent();
  374. MachineBasicBlock::const_iterator MII(MI);
  375. ++MII;
  376. while (NumNOPBytes > 0) {
  377. if (MII == MBB.end() || MII->isCall() ||
  378. MII->getOpcode() == PPC::DBG_VALUE ||
  379. MII->getOpcode() == TargetOpcode::PATCHPOINT ||
  380. MII->getOpcode() == TargetOpcode::STACKMAP)
  381. break;
  382. ++MII;
  383. NumNOPBytes -= 4;
  384. }
  385. // Emit nops.
  386. for (unsigned i = 0; i < NumNOPBytes; i += 4)
  387. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
  388. }
  389. // Lower a patchpoint of the form:
  390. // [<def>], <id>, <numBytes>, <target>, <numArgs>
  391. void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
  392. auto &Ctx = OutStreamer->getContext();
  393. MCSymbol *MILabel = Ctx.createTempSymbol();
  394. OutStreamer->emitLabel(MILabel);
  395. SM.recordPatchPoint(*MILabel, MI);
  396. PatchPointOpers Opers(&MI);
  397. unsigned EncodedBytes = 0;
  398. const MachineOperand &CalleeMO = Opers.getCallTarget();
  399. if (CalleeMO.isImm()) {
  400. int64_t CallTarget = CalleeMO.getImm();
  401. if (CallTarget) {
  402. assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
  403. "High 16 bits of call target should be zero.");
  404. Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
  405. EncodedBytes = 0;
  406. // Materialize the jump address:
  407. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
  408. .addReg(ScratchReg)
  409. .addImm((CallTarget >> 32) & 0xFFFF));
  410. ++EncodedBytes;
  411. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
  412. .addReg(ScratchReg)
  413. .addReg(ScratchReg)
  414. .addImm(32).addImm(16));
  415. ++EncodedBytes;
  416. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
  417. .addReg(ScratchReg)
  418. .addReg(ScratchReg)
  419. .addImm((CallTarget >> 16) & 0xFFFF));
  420. ++EncodedBytes;
  421. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
  422. .addReg(ScratchReg)
  423. .addReg(ScratchReg)
  424. .addImm(CallTarget & 0xFFFF));
  425. // Save the current TOC pointer before the remote call.
  426. int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
  427. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
  428. .addReg(PPC::X2)
  429. .addImm(TOCSaveOffset)
  430. .addReg(PPC::X1));
  431. ++EncodedBytes;
  432. // If we're on ELFv1, then we need to load the actual function pointer
  433. // from the function descriptor.
  434. if (!Subtarget->isELFv2ABI()) {
  435. // Load the new TOC pointer and the function address, but not r11
  436. // (needing this is rare, and loading it here would prevent passing it
  437. // via a 'nest' parameter.
  438. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
  439. .addReg(PPC::X2)
  440. .addImm(8)
  441. .addReg(ScratchReg));
  442. ++EncodedBytes;
  443. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
  444. .addReg(ScratchReg)
  445. .addImm(0)
  446. .addReg(ScratchReg));
  447. ++EncodedBytes;
  448. }
  449. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
  450. .addReg(ScratchReg));
  451. ++EncodedBytes;
  452. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
  453. ++EncodedBytes;
  454. // Restore the TOC pointer after the call.
  455. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
  456. .addReg(PPC::X2)
  457. .addImm(TOCSaveOffset)
  458. .addReg(PPC::X1));
  459. ++EncodedBytes;
  460. }
  461. } else if (CalleeMO.isGlobal()) {
  462. const GlobalValue *GValue = CalleeMO.getGlobal();
  463. MCSymbol *MOSymbol = getSymbol(GValue);
  464. const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
  465. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
  466. .addExpr(SymVar));
  467. EncodedBytes += 2;
  468. }
  469. // Each instruction is 4 bytes.
  470. EncodedBytes *= 4;
  471. // Emit padding.
  472. unsigned NumBytes = Opers.getNumPatchBytes();
  473. assert(NumBytes >= EncodedBytes &&
  474. "Patchpoint can't request size less than the length of a call.");
  475. assert((NumBytes - EncodedBytes) % 4 == 0 &&
  476. "Invalid number of NOP bytes requested!");
  477. for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
  478. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
  479. }
  480. /// This helper function creates the TlsGetAddr MCSymbol for AIX. We will
  481. /// create the csect and use the qual-name symbol instead of creating just the
  482. /// external symbol.
  483. static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx) {
  484. return Ctx
  485. .getXCOFFSection(".__tls_get_addr", SectionKind::getText(),
  486. XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER))
  487. ->getQualNameSymbol();
  488. }
  489. /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
  490. /// call to __tls_get_addr to the current output stream.
  491. void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
  492. MCSymbolRefExpr::VariantKind VK) {
  493. MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
  494. unsigned Opcode = PPC::BL8_NOP_TLS;
  495. assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
  496. if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
  497. MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
  498. Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
  499. Opcode = PPC::BL8_NOTOC_TLS;
  500. }
  501. const Module *M = MF->getFunction().getParent();
  502. assert(MI->getOperand(0).isReg() &&
  503. ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
  504. (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
  505. "GETtls[ld]ADDR[32] must define GPR3");
  506. assert(MI->getOperand(1).isReg() &&
  507. ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
  508. (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
  509. "GETtls[ld]ADDR[32] must read GPR3");
  510. if (Subtarget->isAIXABI()) {
  511. // On AIX, the variable offset should already be in R4 and the region handle
  512. // should already be in R3.
  513. // For TLSGD, which currently is the only supported access model, we only
  514. // need to generate an absolute branch to .__tls_get_addr.
  515. Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
  516. (void)VarOffsetReg;
  517. assert(MI->getOperand(2).isReg() &&
  518. MI->getOperand(2).getReg() == VarOffsetReg &&
  519. "GETtls[ld]ADDR[32] must read GPR4");
  520. MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
  521. const MCExpr *TlsRef = MCSymbolRefExpr::create(
  522. TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
  523. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef));
  524. return;
  525. }
  526. MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr");
  527. if (Subtarget->is32BitELFABI() && isPositionIndependent())
  528. Kind = MCSymbolRefExpr::VK_PLT;
  529. const MCExpr *TlsRef =
  530. MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
  531. // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
  532. if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
  533. M->getPICLevel() == PICLevel::BigPIC)
  534. TlsRef = MCBinaryExpr::createAdd(
  535. TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
  536. const MachineOperand &MO = MI->getOperand(2);
  537. const GlobalValue *GValue = MO.getGlobal();
  538. MCSymbol *MOSymbol = getSymbol(GValue);
  539. const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
  540. EmitToStreamer(*OutStreamer,
  541. MCInstBuilder(Subtarget->isPPC64() ? Opcode
  542. : (unsigned)PPC::BL_TLS)
  543. .addExpr(TlsRef)
  544. .addExpr(SymVar));
  545. }
  546. /// Map a machine operand for a TOC pseudo-machine instruction to its
  547. /// corresponding MCSymbol.
  548. static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
  549. AsmPrinter &AP) {
  550. switch (MO.getType()) {
  551. case MachineOperand::MO_GlobalAddress:
  552. return AP.getSymbol(MO.getGlobal());
  553. case MachineOperand::MO_ConstantPoolIndex:
  554. return AP.GetCPISymbol(MO.getIndex());
  555. case MachineOperand::MO_JumpTableIndex:
  556. return AP.GetJTISymbol(MO.getIndex());
  557. case MachineOperand::MO_BlockAddress:
  558. return AP.GetBlockAddressSymbol(MO.getBlockAddress());
  559. default:
  560. llvm_unreachable("Unexpected operand type to get symbol.");
  561. }
  562. }
  563. /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
  564. /// the current output stream.
  565. ///
  566. void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
  567. PPC_MC::verifyInstructionPredicates(MI->getOpcode(),
  568. getSubtargetInfo().getFeatureBits());
  569. MCInst TmpInst;
  570. const bool IsPPC64 = Subtarget->isPPC64();
  571. const bool IsAIX = Subtarget->isAIXABI();
  572. const Module *M = MF->getFunction().getParent();
  573. PICLevel::Level PL = M->getPICLevel();
  574. #ifndef NDEBUG
  575. // Validate that SPE and FPU are mutually exclusive in codegen
  576. if (!MI->isInlineAsm()) {
  577. for (const MachineOperand &MO: MI->operands()) {
  578. if (MO.isReg()) {
  579. Register Reg = MO.getReg();
  580. if (Subtarget->hasSPE()) {
  581. if (PPC::F4RCRegClass.contains(Reg) ||
  582. PPC::F8RCRegClass.contains(Reg) ||
  583. PPC::VFRCRegClass.contains(Reg) ||
  584. PPC::VRRCRegClass.contains(Reg) ||
  585. PPC::VSFRCRegClass.contains(Reg) ||
  586. PPC::VSSRCRegClass.contains(Reg)
  587. )
  588. llvm_unreachable("SPE targets cannot have FPRegs!");
  589. } else {
  590. if (PPC::SPERCRegClass.contains(Reg))
  591. llvm_unreachable("SPE register found in FPU-targeted code!");
  592. }
  593. }
  594. }
  595. }
  596. #endif
  597. auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
  598. ptrdiff_t OriginalOffset) {
  599. // Apply an offset to the TOC-based expression such that the adjusted
  600. // notional offset from the TOC base (to be encoded into the instruction's D
  601. // or DS field) is the signed 16-bit truncation of the original notional
  602. // offset from the TOC base.
  603. // This is consistent with the treatment used both by XL C/C++ and
  604. // by AIX ld -r.
  605. ptrdiff_t Adjustment =
  606. OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
  607. return MCBinaryExpr::createAdd(
  608. Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
  609. };
  610. auto getTOCEntryLoadingExprForXCOFF =
  611. [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
  612. this](const MCSymbol *MOSymbol, const MCExpr *Expr,
  613. MCSymbolRefExpr::VariantKind VK =
  614. MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
  615. const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
  616. const auto TOCEntryIter = TOC.find({MOSymbol, VK});
  617. assert(TOCEntryIter != TOC.end() &&
  618. "Could not find the TOC entry for this symbol.");
  619. const ptrdiff_t EntryDistanceFromTOCBase =
  620. (TOCEntryIter - TOC.begin()) * EntryByteSize;
  621. constexpr int16_t PositiveTOCRange = INT16_MAX;
  622. if (EntryDistanceFromTOCBase > PositiveTOCRange)
  623. return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
  624. return Expr;
  625. };
  626. auto GetVKForMO = [&](const MachineOperand &MO) {
  627. // For GD TLS access on AIX, we have two TOC entries for the symbol (one for
  628. // the variable offset and the other for the region handle). They are
  629. // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
  630. if (MO.getTargetFlags() & PPCII::MO_TLSGDM_FLAG)
  631. return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
  632. if (MO.getTargetFlags() & PPCII::MO_TLSGD_FLAG)
  633. return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
  634. return MCSymbolRefExpr::VariantKind::VK_None;
  635. };
  636. // Lower multi-instruction pseudo operations.
  637. switch (MI->getOpcode()) {
  638. default: break;
  639. case TargetOpcode::DBG_VALUE:
  640. llvm_unreachable("Should be handled target independently");
  641. case TargetOpcode::STACKMAP:
  642. return LowerSTACKMAP(SM, *MI);
  643. case TargetOpcode::PATCHPOINT:
  644. return LowerPATCHPOINT(SM, *MI);
  645. case PPC::MoveGOTtoLR: {
  646. // Transform %lr = MoveGOTtoLR
  647. // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
  648. // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
  649. // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
  650. // blrl
  651. // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
  652. MCSymbol *GOTSymbol =
  653. OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
  654. const MCExpr *OffsExpr =
  655. MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
  656. MCSymbolRefExpr::VK_PPC_LOCAL,
  657. OutContext),
  658. MCConstantExpr::create(4, OutContext),
  659. OutContext);
  660. // Emit the 'bl'.
  661. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
  662. return;
  663. }
  664. case PPC::MovePCtoLR:
  665. case PPC::MovePCtoLR8: {
  666. // Transform %lr = MovePCtoLR
  667. // Into this, where the label is the PIC base:
  668. // bl L1$pb
  669. // L1$pb:
  670. MCSymbol *PICBase = MF->getPICBaseSymbol();
  671. // Emit the 'bl'.
  672. EmitToStreamer(*OutStreamer,
  673. MCInstBuilder(PPC::BL)
  674. // FIXME: We would like an efficient form for this, so we
  675. // don't have to do a lot of extra uniquing.
  676. .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
  677. // Emit the label.
  678. OutStreamer->emitLabel(PICBase);
  679. return;
  680. }
  681. case PPC::UpdateGBR: {
  682. // Transform %rd = UpdateGBR(%rt, %ri)
  683. // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
  684. // add %rd, %rt, %ri
  685. // or into (if secure plt mode is on):
  686. // addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
  687. // addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
  688. // Get the offset from the GOT Base Register to the GOT
  689. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  690. if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
  691. unsigned PICR = TmpInst.getOperand(0).getReg();
  692. MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
  693. M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
  694. : ".LTOC");
  695. const MCExpr *PB =
  696. MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
  697. const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
  698. MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
  699. const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
  700. EmitToStreamer(
  701. *OutStreamer,
  702. MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
  703. const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
  704. EmitToStreamer(
  705. *OutStreamer,
  706. MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
  707. return;
  708. } else {
  709. MCSymbol *PICOffset =
  710. MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
  711. TmpInst.setOpcode(PPC::LWZ);
  712. const MCExpr *Exp =
  713. MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
  714. const MCExpr *PB =
  715. MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
  716. MCSymbolRefExpr::VK_None,
  717. OutContext);
  718. const MCOperand TR = TmpInst.getOperand(1);
  719. const MCOperand PICR = TmpInst.getOperand(0);
  720. // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
  721. TmpInst.getOperand(1) =
  722. MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
  723. TmpInst.getOperand(0) = TR;
  724. TmpInst.getOperand(2) = PICR;
  725. EmitToStreamer(*OutStreamer, TmpInst);
  726. TmpInst.setOpcode(PPC::ADD4);
  727. TmpInst.getOperand(0) = PICR;
  728. TmpInst.getOperand(1) = TR;
  729. TmpInst.getOperand(2) = PICR;
  730. EmitToStreamer(*OutStreamer, TmpInst);
  731. return;
  732. }
  733. }
  734. case PPC::LWZtoc: {
  735. // Transform %rN = LWZtoc @op1, %r2
  736. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  737. // Change the opcode to LWZ.
  738. TmpInst.setOpcode(PPC::LWZ);
  739. const MachineOperand &MO = MI->getOperand(1);
  740. assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
  741. "Invalid operand for LWZtoc.");
  742. // Map the operand to its corresponding MCSymbol.
  743. const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  744. // Create a reference to the GOT entry for the symbol. The GOT entry will be
  745. // synthesized later.
  746. if (PL == PICLevel::SmallPIC && !IsAIX) {
  747. const MCExpr *Exp =
  748. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
  749. OutContext);
  750. TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
  751. EmitToStreamer(*OutStreamer, TmpInst);
  752. return;
  753. }
  754. MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
  755. // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
  756. // storage allocated in the TOC which contains the address of
  757. // 'MOSymbol'. Said TOC entry will be synthesized later.
  758. MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
  759. const MCExpr *Exp =
  760. MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
  761. // AIX uses the label directly as the lwz displacement operand for
  762. // references into the toc section. The displacement value will be generated
  763. // relative to the toc-base.
  764. if (IsAIX) {
  765. assert(
  766. TM.getCodeModel() == CodeModel::Small &&
  767. "This pseudo should only be selected for 32-bit small code model.");
  768. Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
  769. TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
  770. // Print MO for better readability
  771. if (isVerbose())
  772. OutStreamer->getCommentOS() << MO << '\n';
  773. EmitToStreamer(*OutStreamer, TmpInst);
  774. return;
  775. }
  776. // Create an explicit subtract expression between the local symbol and
  777. // '.LTOC' to manifest the toc-relative offset.
  778. const MCExpr *PB = MCSymbolRefExpr::create(
  779. OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
  780. Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
  781. TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
  782. EmitToStreamer(*OutStreamer, TmpInst);
  783. return;
  784. }
  785. case PPC::ADDItoc:
  786. case PPC::ADDItoc8: {
  787. assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
  788. "PseudoOp only valid for small code model AIX");
  789. // Transform %rN = ADDItoc/8 @op1, %r2.
  790. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  791. // Change the opcode to load address.
  792. TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
  793. const MachineOperand &MO = MI->getOperand(1);
  794. assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
  795. // Map the operand to its corresponding MCSymbol.
  796. const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  797. const MCExpr *Exp =
  798. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_None, OutContext);
  799. TmpInst.getOperand(1) = TmpInst.getOperand(2);
  800. TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
  801. EmitToStreamer(*OutStreamer, TmpInst);
  802. return;
  803. }
  804. case PPC::LDtocJTI:
  805. case PPC::LDtocCPT:
  806. case PPC::LDtocBA:
  807. case PPC::LDtoc: {
  808. // Transform %x3 = LDtoc @min1, %x2
  809. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  810. // Change the opcode to LD.
  811. TmpInst.setOpcode(PPC::LD);
  812. const MachineOperand &MO = MI->getOperand(1);
  813. assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
  814. "Invalid operand!");
  815. // Map the operand to its corresponding MCSymbol.
  816. const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  817. MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
  818. // Map the machine operand to its corresponding MCSymbol, then map the
  819. // global address operand to be a reference to the TOC entry we will
  820. // synthesize later.
  821. MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
  822. MCSymbolRefExpr::VariantKind VKExpr =
  823. IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
  824. const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
  825. TmpInst.getOperand(1) = MCOperand::createExpr(
  826. IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
  827. // Print MO for better readability
  828. if (isVerbose() && IsAIX)
  829. OutStreamer->getCommentOS() << MO << '\n';
  830. EmitToStreamer(*OutStreamer, TmpInst);
  831. return;
  832. }
  833. case PPC::ADDIStocHA: {
  834. assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
  835. "This pseudo should only be selected for 32-bit large code model on"
  836. " AIX.");
  837. // Transform %rd = ADDIStocHA %rA, @sym(%r2)
  838. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  839. // Change the opcode to ADDIS.
  840. TmpInst.setOpcode(PPC::ADDIS);
  841. const MachineOperand &MO = MI->getOperand(2);
  842. assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
  843. "Invalid operand for ADDIStocHA.");
  844. // Map the machine operand to its corresponding MCSymbol.
  845. MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  846. MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
  847. // Always use TOC on AIX. Map the global address operand to be a reference
  848. // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
  849. // reference the storage allocated in the TOC which contains the address of
  850. // 'MOSymbol'.
  851. MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
  852. const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
  853. MCSymbolRefExpr::VK_PPC_U,
  854. OutContext);
  855. TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
  856. EmitToStreamer(*OutStreamer, TmpInst);
  857. return;
  858. }
  859. case PPC::LWZtocL: {
  860. assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
  861. "This pseudo should only be selected for 32-bit large code model on"
  862. " AIX.");
  863. // Transform %rd = LWZtocL @sym, %rs.
  864. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  865. // Change the opcode to lwz.
  866. TmpInst.setOpcode(PPC::LWZ);
  867. const MachineOperand &MO = MI->getOperand(1);
  868. assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
  869. "Invalid operand for LWZtocL.");
  870. // Map the machine operand to its corresponding MCSymbol.
  871. MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  872. MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
  873. // Always use TOC on AIX. Map the global address operand to be a reference
  874. // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
  875. // reference the storage allocated in the TOC which contains the address of
  876. // 'MOSymbol'.
  877. MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
  878. const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
  879. MCSymbolRefExpr::VK_PPC_L,
  880. OutContext);
  881. TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
  882. EmitToStreamer(*OutStreamer, TmpInst);
  883. return;
  884. }
  885. case PPC::ADDIStocHA8: {
  886. // Transform %xd = ADDIStocHA8 %x2, @sym
  887. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  888. // Change the opcode to ADDIS8. If the global address is the address of
  889. // an external symbol, is a jump table address, is a block address, or is a
  890. // constant pool index with large code model enabled, then generate a TOC
  891. // entry and reference that. Otherwise, reference the symbol directly.
  892. TmpInst.setOpcode(PPC::ADDIS8);
  893. const MachineOperand &MO = MI->getOperand(2);
  894. assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
  895. "Invalid operand for ADDIStocHA8!");
  896. const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  897. MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
  898. const bool GlobalToc =
  899. MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
  900. if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
  901. (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
  902. MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK);
  903. VK = IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
  904. const MCExpr *Exp =
  905. MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
  906. if (!MO.isJTI() && MO.getOffset())
  907. Exp = MCBinaryExpr::createAdd(Exp,
  908. MCConstantExpr::create(MO.getOffset(),
  909. OutContext),
  910. OutContext);
  911. TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
  912. EmitToStreamer(*OutStreamer, TmpInst);
  913. return;
  914. }
  915. case PPC::LDtocL: {
  916. // Transform %xd = LDtocL @sym, %xs
  917. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  918. // Change the opcode to LD. If the global address is the address of
  919. // an external symbol, is a jump table address, is a block address, or is
  920. // a constant pool index with large code model enabled, then generate a
  921. // TOC entry and reference that. Otherwise, reference the symbol directly.
  922. TmpInst.setOpcode(PPC::LD);
  923. const MachineOperand &MO = MI->getOperand(1);
  924. assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
  925. MO.isBlockAddress()) &&
  926. "Invalid operand for LDtocL!");
  927. LLVM_DEBUG(assert(
  928. (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
  929. "LDtocL used on symbol that could be accessed directly is "
  930. "invalid. Must match ADDIStocHA8."));
  931. const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
  932. MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
  933. if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
  934. MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK);
  935. VK = IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
  936. const MCExpr *Exp =
  937. MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
  938. TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
  939. EmitToStreamer(*OutStreamer, TmpInst);
  940. return;
  941. }
  942. case PPC::ADDItocL: {
  943. // Transform %xd = ADDItocL %xs, @sym
  944. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  945. // Change the opcode to ADDI8. If the global address is external, then
  946. // generate a TOC entry and reference that. Otherwise, reference the
  947. // symbol directly.
  948. TmpInst.setOpcode(PPC::ADDI8);
  949. const MachineOperand &MO = MI->getOperand(2);
  950. assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
  951. LLVM_DEBUG(assert(
  952. !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
  953. "Interposable definitions must use indirect access."));
  954. const MCExpr *Exp =
  955. MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
  956. MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
  957. TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
  958. EmitToStreamer(*OutStreamer, TmpInst);
  959. return;
  960. }
  961. case PPC::ADDISgotTprelHA: {
  962. // Transform: %xd = ADDISgotTprelHA %x2, @sym
  963. // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
  964. assert(IsPPC64 && "Not supported for 32-bit PowerPC");
  965. const MachineOperand &MO = MI->getOperand(2);
  966. const GlobalValue *GValue = MO.getGlobal();
  967. MCSymbol *MOSymbol = getSymbol(GValue);
  968. const MCExpr *SymGotTprel =
  969. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
  970. OutContext);
  971. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
  972. .addReg(MI->getOperand(0).getReg())
  973. .addReg(MI->getOperand(1).getReg())
  974. .addExpr(SymGotTprel));
  975. return;
  976. }
  977. case PPC::LDgotTprelL:
  978. case PPC::LDgotTprelL32: {
  979. // Transform %xd = LDgotTprelL @sym, %xs
  980. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  981. // Change the opcode to LD.
  982. TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
  983. const MachineOperand &MO = MI->getOperand(1);
  984. const GlobalValue *GValue = MO.getGlobal();
  985. MCSymbol *MOSymbol = getSymbol(GValue);
  986. const MCExpr *Exp = MCSymbolRefExpr::create(
  987. MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
  988. : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
  989. OutContext);
  990. TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
  991. EmitToStreamer(*OutStreamer, TmpInst);
  992. return;
  993. }
  994. case PPC::PPC32PICGOT: {
  995. MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
  996. MCSymbol *GOTRef = OutContext.createTempSymbol();
  997. MCSymbol *NextInstr = OutContext.createTempSymbol();
  998. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
  999. // FIXME: We would like an efficient form for this, so we don't have to do
  1000. // a lot of extra uniquing.
  1001. .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
  1002. const MCExpr *OffsExpr =
  1003. MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
  1004. MCSymbolRefExpr::create(GOTRef, OutContext),
  1005. OutContext);
  1006. OutStreamer->emitLabel(GOTRef);
  1007. OutStreamer->emitValue(OffsExpr, 4);
  1008. OutStreamer->emitLabel(NextInstr);
  1009. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
  1010. .addReg(MI->getOperand(0).getReg()));
  1011. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
  1012. .addReg(MI->getOperand(1).getReg())
  1013. .addImm(0)
  1014. .addReg(MI->getOperand(0).getReg()));
  1015. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
  1016. .addReg(MI->getOperand(0).getReg())
  1017. .addReg(MI->getOperand(1).getReg())
  1018. .addReg(MI->getOperand(0).getReg()));
  1019. return;
  1020. }
  1021. case PPC::PPC32GOT: {
  1022. MCSymbol *GOTSymbol =
  1023. OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
  1024. const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
  1025. GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
  1026. const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
  1027. GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
  1028. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
  1029. .addReg(MI->getOperand(0).getReg())
  1030. .addExpr(SymGotTlsL));
  1031. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
  1032. .addReg(MI->getOperand(0).getReg())
  1033. .addReg(MI->getOperand(0).getReg())
  1034. .addExpr(SymGotTlsHA));
  1035. return;
  1036. }
  1037. case PPC::ADDIStlsgdHA: {
  1038. // Transform: %xd = ADDIStlsgdHA %x2, @sym
  1039. // Into: %xd = ADDIS8 %x2, sym@got@tlsgd@ha
  1040. assert(IsPPC64 && "Not supported for 32-bit PowerPC");
  1041. const MachineOperand &MO = MI->getOperand(2);
  1042. const GlobalValue *GValue = MO.getGlobal();
  1043. MCSymbol *MOSymbol = getSymbol(GValue);
  1044. const MCExpr *SymGotTlsGD =
  1045. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
  1046. OutContext);
  1047. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
  1048. .addReg(MI->getOperand(0).getReg())
  1049. .addReg(MI->getOperand(1).getReg())
  1050. .addExpr(SymGotTlsGD));
  1051. return;
  1052. }
  1053. case PPC::ADDItlsgdL:
  1054. // Transform: %xd = ADDItlsgdL %xs, @sym
  1055. // Into: %xd = ADDI8 %xs, sym@got@tlsgd@l
  1056. case PPC::ADDItlsgdL32: {
  1057. // Transform: %rd = ADDItlsgdL32 %rs, @sym
  1058. // Into: %rd = ADDI %rs, sym@got@tlsgd
  1059. const MachineOperand &MO = MI->getOperand(2);
  1060. const GlobalValue *GValue = MO.getGlobal();
  1061. MCSymbol *MOSymbol = getSymbol(GValue);
  1062. const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
  1063. MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
  1064. : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
  1065. OutContext);
  1066. EmitToStreamer(*OutStreamer,
  1067. MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
  1068. .addReg(MI->getOperand(0).getReg())
  1069. .addReg(MI->getOperand(1).getReg())
  1070. .addExpr(SymGotTlsGD));
  1071. return;
  1072. }
  1073. case PPC::GETtlsADDR:
  1074. // Transform: %x3 = GETtlsADDR %x3, @sym
  1075. // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
  1076. case PPC::GETtlsADDRPCREL:
  1077. case PPC::GETtlsADDR32AIX:
  1078. case PPC::GETtlsADDR64AIX:
  1079. // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64).
  1080. // Into: BLA .__tls_get_addr()
  1081. // Unlike on Linux, there is no symbol or relocation needed for this call.
  1082. case PPC::GETtlsADDR32: {
  1083. // Transform: %r3 = GETtlsADDR32 %r3, @sym
  1084. // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
  1085. EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
  1086. return;
  1087. }
  1088. case PPC::ADDIStlsldHA: {
  1089. // Transform: %xd = ADDIStlsldHA %x2, @sym
  1090. // Into: %xd = ADDIS8 %x2, sym@got@tlsld@ha
  1091. assert(IsPPC64 && "Not supported for 32-bit PowerPC");
  1092. const MachineOperand &MO = MI->getOperand(2);
  1093. const GlobalValue *GValue = MO.getGlobal();
  1094. MCSymbol *MOSymbol = getSymbol(GValue);
  1095. const MCExpr *SymGotTlsLD =
  1096. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
  1097. OutContext);
  1098. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
  1099. .addReg(MI->getOperand(0).getReg())
  1100. .addReg(MI->getOperand(1).getReg())
  1101. .addExpr(SymGotTlsLD));
  1102. return;
  1103. }
  1104. case PPC::ADDItlsldL:
  1105. // Transform: %xd = ADDItlsldL %xs, @sym
  1106. // Into: %xd = ADDI8 %xs, sym@got@tlsld@l
  1107. case PPC::ADDItlsldL32: {
  1108. // Transform: %rd = ADDItlsldL32 %rs, @sym
  1109. // Into: %rd = ADDI %rs, sym@got@tlsld
  1110. const MachineOperand &MO = MI->getOperand(2);
  1111. const GlobalValue *GValue = MO.getGlobal();
  1112. MCSymbol *MOSymbol = getSymbol(GValue);
  1113. const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
  1114. MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
  1115. : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
  1116. OutContext);
  1117. EmitToStreamer(*OutStreamer,
  1118. MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
  1119. .addReg(MI->getOperand(0).getReg())
  1120. .addReg(MI->getOperand(1).getReg())
  1121. .addExpr(SymGotTlsLD));
  1122. return;
  1123. }
  1124. case PPC::GETtlsldADDR:
  1125. // Transform: %x3 = GETtlsldADDR %x3, @sym
  1126. // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
  1127. case PPC::GETtlsldADDRPCREL:
  1128. case PPC::GETtlsldADDR32: {
  1129. // Transform: %r3 = GETtlsldADDR32 %r3, @sym
  1130. // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
  1131. EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
  1132. return;
  1133. }
  1134. case PPC::ADDISdtprelHA:
  1135. // Transform: %xd = ADDISdtprelHA %xs, @sym
  1136. // Into: %xd = ADDIS8 %xs, sym@dtprel@ha
  1137. case PPC::ADDISdtprelHA32: {
  1138. // Transform: %rd = ADDISdtprelHA32 %rs, @sym
  1139. // Into: %rd = ADDIS %rs, sym@dtprel@ha
  1140. const MachineOperand &MO = MI->getOperand(2);
  1141. const GlobalValue *GValue = MO.getGlobal();
  1142. MCSymbol *MOSymbol = getSymbol(GValue);
  1143. const MCExpr *SymDtprel =
  1144. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
  1145. OutContext);
  1146. EmitToStreamer(
  1147. *OutStreamer,
  1148. MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
  1149. .addReg(MI->getOperand(0).getReg())
  1150. .addReg(MI->getOperand(1).getReg())
  1151. .addExpr(SymDtprel));
  1152. return;
  1153. }
  1154. case PPC::PADDIdtprel: {
  1155. // Transform: %rd = PADDIdtprel %rs, @sym
  1156. // Into: %rd = PADDI8 %rs, sym@dtprel
  1157. const MachineOperand &MO = MI->getOperand(2);
  1158. const GlobalValue *GValue = MO.getGlobal();
  1159. MCSymbol *MOSymbol = getSymbol(GValue);
  1160. const MCExpr *SymDtprel = MCSymbolRefExpr::create(
  1161. MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
  1162. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
  1163. .addReg(MI->getOperand(0).getReg())
  1164. .addReg(MI->getOperand(1).getReg())
  1165. .addExpr(SymDtprel));
  1166. return;
  1167. }
  1168. case PPC::ADDIdtprelL:
  1169. // Transform: %xd = ADDIdtprelL %xs, @sym
  1170. // Into: %xd = ADDI8 %xs, sym@dtprel@l
  1171. case PPC::ADDIdtprelL32: {
  1172. // Transform: %rd = ADDIdtprelL32 %rs, @sym
  1173. // Into: %rd = ADDI %rs, sym@dtprel@l
  1174. const MachineOperand &MO = MI->getOperand(2);
  1175. const GlobalValue *GValue = MO.getGlobal();
  1176. MCSymbol *MOSymbol = getSymbol(GValue);
  1177. const MCExpr *SymDtprel =
  1178. MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
  1179. OutContext);
  1180. EmitToStreamer(*OutStreamer,
  1181. MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
  1182. .addReg(MI->getOperand(0).getReg())
  1183. .addReg(MI->getOperand(1).getReg())
  1184. .addExpr(SymDtprel));
  1185. return;
  1186. }
  1187. case PPC::MFOCRF:
  1188. case PPC::MFOCRF8:
  1189. if (!Subtarget->hasMFOCRF()) {
  1190. // Transform: %r3 = MFOCRF %cr7
  1191. // Into: %r3 = MFCR ;; cr7
  1192. unsigned NewOpcode =
  1193. MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
  1194. OutStreamer->AddComment(PPCInstPrinter::
  1195. getRegisterName(MI->getOperand(1).getReg()));
  1196. EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
  1197. .addReg(MI->getOperand(0).getReg()));
  1198. return;
  1199. }
  1200. break;
  1201. case PPC::MTOCRF:
  1202. case PPC::MTOCRF8:
  1203. if (!Subtarget->hasMFOCRF()) {
  1204. // Transform: %cr7 = MTOCRF %r3
  1205. // Into: MTCRF mask, %r3 ;; cr7
  1206. unsigned NewOpcode =
  1207. MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
  1208. unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
  1209. ->getEncodingValue(MI->getOperand(0).getReg());
  1210. OutStreamer->AddComment(PPCInstPrinter::
  1211. getRegisterName(MI->getOperand(0).getReg()));
  1212. EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
  1213. .addImm(Mask)
  1214. .addReg(MI->getOperand(1).getReg()));
  1215. return;
  1216. }
  1217. break;
  1218. case PPC::LD:
  1219. case PPC::STD:
  1220. case PPC::LWA_32:
  1221. case PPC::LWA: {
  1222. // Verify alignment is legal, so we don't create relocations
  1223. // that can't be supported.
  1224. unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
  1225. const MachineOperand &MO = MI->getOperand(OpNum);
  1226. if (MO.isGlobal()) {
  1227. const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
  1228. if (MO.getGlobal()->getPointerAlignment(DL) < 4)
  1229. llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
  1230. }
  1231. // Now process the instruction normally.
  1232. break;
  1233. }
  1234. case PPC::PseudoEIEIO: {
  1235. EmitToStreamer(
  1236. *OutStreamer,
  1237. MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
  1238. EmitToStreamer(
  1239. *OutStreamer,
  1240. MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
  1241. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO));
  1242. return;
  1243. }
  1244. }
  1245. LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
  1246. EmitToStreamer(*OutStreamer, TmpInst);
  1247. }
  1248. void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
  1249. // Emit float ABI into GNU attribute
  1250. Metadata *MD = M.getModuleFlag("float-abi");
  1251. MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
  1252. if (!FloatABI)
  1253. return;
  1254. StringRef flt = FloatABI->getString();
  1255. // TODO: Support emitting soft-fp and hard double/single attributes.
  1256. if (flt == "doubledouble")
  1257. OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
  1258. Val_GNU_Power_ABI_HardFloat_DP |
  1259. Val_GNU_Power_ABI_LDBL_IBM128);
  1260. else if (flt == "ieeequad")
  1261. OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
  1262. Val_GNU_Power_ABI_HardFloat_DP |
  1263. Val_GNU_Power_ABI_LDBL_IEEE128);
  1264. else if (flt == "ieeedouble")
  1265. OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
  1266. Val_GNU_Power_ABI_HardFloat_DP |
  1267. Val_GNU_Power_ABI_LDBL_64);
  1268. }
  1269. void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
  1270. if (!Subtarget->isPPC64())
  1271. return PPCAsmPrinter::emitInstruction(MI);
  1272. switch (MI->getOpcode()) {
  1273. default:
  1274. return PPCAsmPrinter::emitInstruction(MI);
  1275. case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
  1276. // .begin:
  1277. // b .end # lis 0, FuncId[16..32]
  1278. // nop # li 0, FuncId[0..15]
  1279. // std 0, -8(1)
  1280. // mflr 0
  1281. // bl __xray_FunctionEntry
  1282. // mtlr 0
  1283. // .end:
  1284. //
  1285. // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
  1286. // of instructions change.
  1287. MCSymbol *BeginOfSled = OutContext.createTempSymbol();
  1288. MCSymbol *EndOfSled = OutContext.createTempSymbol();
  1289. OutStreamer->emitLabel(BeginOfSled);
  1290. EmitToStreamer(*OutStreamer,
  1291. MCInstBuilder(PPC::B).addExpr(
  1292. MCSymbolRefExpr::create(EndOfSled, OutContext)));
  1293. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
  1294. EmitToStreamer(
  1295. *OutStreamer,
  1296. MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
  1297. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
  1298. EmitToStreamer(*OutStreamer,
  1299. MCInstBuilder(PPC::BL8_NOP)
  1300. .addExpr(MCSymbolRefExpr::create(
  1301. OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
  1302. OutContext)));
  1303. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
  1304. OutStreamer->emitLabel(EndOfSled);
  1305. recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
  1306. break;
  1307. }
  1308. case TargetOpcode::PATCHABLE_RET: {
  1309. unsigned RetOpcode = MI->getOperand(0).getImm();
  1310. MCInst RetInst;
  1311. RetInst.setOpcode(RetOpcode);
  1312. for (const auto &MO : llvm::drop_begin(MI->operands())) {
  1313. MCOperand MCOp;
  1314. if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
  1315. RetInst.addOperand(MCOp);
  1316. }
  1317. bool IsConditional;
  1318. if (RetOpcode == PPC::BCCLR) {
  1319. IsConditional = true;
  1320. } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
  1321. RetOpcode == PPC::TCRETURNai8) {
  1322. break;
  1323. } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
  1324. IsConditional = false;
  1325. } else {
  1326. EmitToStreamer(*OutStreamer, RetInst);
  1327. break;
  1328. }
  1329. MCSymbol *FallthroughLabel;
  1330. if (IsConditional) {
  1331. // Before:
  1332. // bgtlr cr0
  1333. //
  1334. // After:
  1335. // ble cr0, .end
  1336. // .p2align 3
  1337. // .begin:
  1338. // blr # lis 0, FuncId[16..32]
  1339. // nop # li 0, FuncId[0..15]
  1340. // std 0, -8(1)
  1341. // mflr 0
  1342. // bl __xray_FunctionExit
  1343. // mtlr 0
  1344. // blr
  1345. // .end:
  1346. //
  1347. // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
  1348. // of instructions change.
  1349. FallthroughLabel = OutContext.createTempSymbol();
  1350. EmitToStreamer(
  1351. *OutStreamer,
  1352. MCInstBuilder(PPC::BCC)
  1353. .addImm(PPC::InvertPredicate(
  1354. static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
  1355. .addReg(MI->getOperand(2).getReg())
  1356. .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
  1357. RetInst = MCInst();
  1358. RetInst.setOpcode(PPC::BLR8);
  1359. }
  1360. // .p2align 3
  1361. // .begin:
  1362. // b(lr)? # lis 0, FuncId[16..32]
  1363. // nop # li 0, FuncId[0..15]
  1364. // std 0, -8(1)
  1365. // mflr 0
  1366. // bl __xray_FunctionExit
  1367. // mtlr 0
  1368. // b(lr)?
  1369. //
  1370. // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
  1371. // of instructions change.
  1372. OutStreamer->emitCodeAlignment(Align(8), &getSubtargetInfo());
  1373. MCSymbol *BeginOfSled = OutContext.createTempSymbol();
  1374. OutStreamer->emitLabel(BeginOfSled);
  1375. EmitToStreamer(*OutStreamer, RetInst);
  1376. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
  1377. EmitToStreamer(
  1378. *OutStreamer,
  1379. MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
  1380. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
  1381. EmitToStreamer(*OutStreamer,
  1382. MCInstBuilder(PPC::BL8_NOP)
  1383. .addExpr(MCSymbolRefExpr::create(
  1384. OutContext.getOrCreateSymbol("__xray_FunctionExit"),
  1385. OutContext)));
  1386. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
  1387. EmitToStreamer(*OutStreamer, RetInst);
  1388. if (IsConditional)
  1389. OutStreamer->emitLabel(FallthroughLabel);
  1390. recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
  1391. break;
  1392. }
  1393. case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
  1394. llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
  1395. case TargetOpcode::PATCHABLE_TAIL_CALL:
  1396. // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
  1397. // normal function exit from a tail exit.
  1398. llvm_unreachable("Tail call is handled in the normal case. See comments "
  1399. "around this assert.");
  1400. }
  1401. }
  1402. void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
  1403. if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
  1404. PPCTargetStreamer *TS =
  1405. static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
  1406. TS->emitAbiVersion(2);
  1407. }
  1408. if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
  1409. !isPositionIndependent())
  1410. return AsmPrinter::emitStartOfAsmFile(M);
  1411. if (M.getPICLevel() == PICLevel::SmallPIC)
  1412. return AsmPrinter::emitStartOfAsmFile(M);
  1413. OutStreamer->switchSection(OutContext.getELFSection(
  1414. ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
  1415. MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
  1416. MCSymbol *CurrentPos = OutContext.createTempSymbol();
  1417. OutStreamer->emitLabel(CurrentPos);
  1418. // The GOT pointer points to the middle of the GOT, in order to reference the
  1419. // entire 64kB range. 0x8000 is the midpoint.
  1420. const MCExpr *tocExpr =
  1421. MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
  1422. MCConstantExpr::create(0x8000, OutContext),
  1423. OutContext);
  1424. OutStreamer->emitAssignment(TOCSym, tocExpr);
  1425. OutStreamer->switchSection(getObjFileLowering().getTextSection());
  1426. }
  1427. void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
  1428. // linux/ppc32 - Normal entry label.
  1429. if (!Subtarget->isPPC64() &&
  1430. (!isPositionIndependent() ||
  1431. MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
  1432. return AsmPrinter::emitFunctionEntryLabel();
  1433. if (!Subtarget->isPPC64()) {
  1434. const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
  1435. if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
  1436. MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
  1437. MCSymbol *PICBase = MF->getPICBaseSymbol();
  1438. OutStreamer->emitLabel(RelocSymbol);
  1439. const MCExpr *OffsExpr =
  1440. MCBinaryExpr::createSub(
  1441. MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
  1442. OutContext),
  1443. MCSymbolRefExpr::create(PICBase, OutContext),
  1444. OutContext);
  1445. OutStreamer->emitValue(OffsExpr, 4);
  1446. OutStreamer->emitLabel(CurrentFnSym);
  1447. return;
  1448. } else
  1449. return AsmPrinter::emitFunctionEntryLabel();
  1450. }
  1451. // ELFv2 ABI - Normal entry label.
  1452. if (Subtarget->isELFv2ABI()) {
  1453. // In the Large code model, we allow arbitrary displacements between
  1454. // the text section and its associated TOC section. We place the
  1455. // full 8-byte offset to the TOC in memory immediately preceding
  1456. // the function global entry point.
  1457. if (TM.getCodeModel() == CodeModel::Large
  1458. && !MF->getRegInfo().use_empty(PPC::X2)) {
  1459. const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
  1460. MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
  1461. MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
  1462. const MCExpr *TOCDeltaExpr =
  1463. MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
  1464. MCSymbolRefExpr::create(GlobalEPSymbol,
  1465. OutContext),
  1466. OutContext);
  1467. OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
  1468. OutStreamer->emitValue(TOCDeltaExpr, 8);
  1469. }
  1470. return AsmPrinter::emitFunctionEntryLabel();
  1471. }
  1472. // Emit an official procedure descriptor.
  1473. MCSectionSubPair Current = OutStreamer->getCurrentSection();
  1474. MCSectionELF *Section = OutStreamer->getContext().getELFSection(
  1475. ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  1476. OutStreamer->switchSection(Section);
  1477. OutStreamer->emitLabel(CurrentFnSym);
  1478. OutStreamer->emitValueToAlignment(Align(8));
  1479. MCSymbol *Symbol1 = CurrentFnSymForSize;
  1480. // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
  1481. // entry point.
  1482. OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
  1483. 8 /*size*/);
  1484. MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
  1485. // Generates a R_PPC64_TOC relocation for TOC base insertion.
  1486. OutStreamer->emitValue(
  1487. MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
  1488. 8/*size*/);
  1489. // Emit a null environment pointer.
  1490. OutStreamer->emitIntValue(0, 8 /* size */);
  1491. OutStreamer->switchSection(Current.first, Current.second);
  1492. }
  1493. void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
  1494. const DataLayout &DL = getDataLayout();
  1495. bool isPPC64 = DL.getPointerSizeInBits() == 64;
  1496. PPCTargetStreamer *TS =
  1497. static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
  1498. emitGNUAttributes(M);
  1499. if (!TOC.empty()) {
  1500. const char *Name = isPPC64 ? ".toc" : ".got2";
  1501. MCSectionELF *Section = OutContext.getELFSection(
  1502. Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  1503. OutStreamer->switchSection(Section);
  1504. if (!isPPC64)
  1505. OutStreamer->emitValueToAlignment(Align(4));
  1506. for (const auto &TOCMapPair : TOC) {
  1507. const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first;
  1508. MCSymbol *const TOCEntryLabel = TOCMapPair.second;
  1509. OutStreamer->emitLabel(TOCEntryLabel);
  1510. if (isPPC64)
  1511. TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second);
  1512. else
  1513. OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
  1514. }
  1515. }
  1516. PPCAsmPrinter::emitEndOfAsmFile(M);
  1517. }
  1518. /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
  1519. void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
  1520. // In the ELFv2 ABI, in functions that use the TOC register, we need to
  1521. // provide two entry points. The ABI guarantees that when calling the
  1522. // local entry point, r2 is set up by the caller to contain the TOC base
  1523. // for this function, and when calling the global entry point, r12 is set
  1524. // up by the caller to hold the address of the global entry point. We
  1525. // thus emit a prefix sequence along the following lines:
  1526. //
  1527. // func:
  1528. // .Lfunc_gepNN:
  1529. // # global entry point
  1530. // addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
  1531. // addi r2,r2,(.TOC.-.Lfunc_gepNN)@l
  1532. // .Lfunc_lepNN:
  1533. // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
  1534. // # local entry point, followed by function body
  1535. //
  1536. // For the Large code model, we create
  1537. //
  1538. // .Lfunc_tocNN:
  1539. // .quad .TOC.-.Lfunc_gepNN # done by EmitFunctionEntryLabel
  1540. // func:
  1541. // .Lfunc_gepNN:
  1542. // # global entry point
  1543. // ld r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
  1544. // add r2,r2,r12
  1545. // .Lfunc_lepNN:
  1546. // .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
  1547. // # local entry point, followed by function body
  1548. //
  1549. // This ensures we have r2 set up correctly while executing the function
  1550. // body, no matter which entry point is called.
  1551. const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
  1552. const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
  1553. !MF->getRegInfo().use_empty(PPC::R2);
  1554. const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
  1555. UsesX2OrR2 && PPCFI->usesTOCBasePtr();
  1556. const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
  1557. Subtarget->isELFv2ABI() && UsesX2OrR2;
  1558. // Only do all that if the function uses R2 as the TOC pointer
  1559. // in the first place. We don't need the global entry point if the
  1560. // function uses R2 as an allocatable register.
  1561. if (NonPCrelGEPRequired || PCrelGEPRequired) {
  1562. // Note: The logic here must be synchronized with the code in the
  1563. // branch-selection pass which sets the offset of the first block in the
  1564. // function. This matters because it affects the alignment.
  1565. MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
  1566. OutStreamer->emitLabel(GlobalEntryLabel);
  1567. const MCSymbolRefExpr *GlobalEntryLabelExp =
  1568. MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
  1569. if (TM.getCodeModel() != CodeModel::Large) {
  1570. MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
  1571. const MCExpr *TOCDeltaExpr =
  1572. MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
  1573. GlobalEntryLabelExp, OutContext);
  1574. const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
  1575. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
  1576. .addReg(PPC::X2)
  1577. .addReg(PPC::X12)
  1578. .addExpr(TOCDeltaHi));
  1579. const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
  1580. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
  1581. .addReg(PPC::X2)
  1582. .addReg(PPC::X2)
  1583. .addExpr(TOCDeltaLo));
  1584. } else {
  1585. MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
  1586. const MCExpr *TOCOffsetDeltaExpr =
  1587. MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
  1588. GlobalEntryLabelExp, OutContext);
  1589. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
  1590. .addReg(PPC::X2)
  1591. .addExpr(TOCOffsetDeltaExpr)
  1592. .addReg(PPC::X12));
  1593. EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
  1594. .addReg(PPC::X2)
  1595. .addReg(PPC::X2)
  1596. .addReg(PPC::X12));
  1597. }
  1598. MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
  1599. OutStreamer->emitLabel(LocalEntryLabel);
  1600. const MCSymbolRefExpr *LocalEntryLabelExp =
  1601. MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
  1602. const MCExpr *LocalOffsetExp =
  1603. MCBinaryExpr::createSub(LocalEntryLabelExp,
  1604. GlobalEntryLabelExp, OutContext);
  1605. PPCTargetStreamer *TS =
  1606. static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
  1607. TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
  1608. } else if (Subtarget->isUsingPCRelativeCalls()) {
  1609. // When generating the entry point for a function we have a few scenarios
  1610. // based on whether or not that function uses R2 and whether or not that
  1611. // function makes calls (or is a leaf function).
  1612. // 1) A leaf function that does not use R2 (or treats it as callee-saved
  1613. // and preserves it). In this case st_other=0 and both
  1614. // the local and global entry points for the function are the same.
  1615. // No special entry point code is required.
  1616. // 2) A function uses the TOC pointer R2. This function may or may not have
  1617. // calls. In this case st_other=[2,6] and the global and local entry
  1618. // points are different. Code to correctly setup the TOC pointer in R2
  1619. // is put between the global and local entry points. This case is
  1620. // covered by the if statatement above.
  1621. // 3) A function does not use the TOC pointer R2 but does have calls.
  1622. // In this case st_other=1 since we do not know whether or not any
  1623. // of the callees clobber R2. This case is dealt with in this else if
  1624. // block. Tail calls are considered calls and the st_other should also
  1625. // be set to 1 in that case as well.
  1626. // 4) The function does not use the TOC pointer but R2 is used inside
  1627. // the function. In this case st_other=1 once again.
  1628. // 5) This function uses inline asm. We mark R2 as reserved if the function
  1629. // has inline asm as we have to assume that it may be used.
  1630. if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
  1631. MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
  1632. PPCTargetStreamer *TS =
  1633. static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
  1634. TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
  1635. MCConstantExpr::create(1, OutContext));
  1636. }
  1637. }
  1638. }
  1639. /// EmitFunctionBodyEnd - Print the traceback table before the .size
  1640. /// directive.
  1641. ///
  1642. void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
  1643. // Only the 64-bit target requires a traceback table. For now,
  1644. // we only emit the word of zeroes that GDB requires to find
  1645. // the end of the function, and zeroes for the eight-byte
  1646. // mandatory fields.
  1647. // FIXME: We should fill in the eight-byte mandatory fields as described in
  1648. // the PPC64 ELF ABI (this is a low-priority item because GDB does not
  1649. // currently make use of these fields).
  1650. if (Subtarget->isPPC64()) {
  1651. OutStreamer->emitIntValue(0, 4/*size*/);
  1652. OutStreamer->emitIntValue(0, 8/*size*/);
  1653. }
  1654. }
  1655. void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
  1656. MCSymbol *GVSym) const {
  1657. assert(MAI->hasVisibilityOnlyWithLinkage() &&
  1658. "AIX's linkage directives take a visibility setting.");
  1659. MCSymbolAttr LinkageAttr = MCSA_Invalid;
  1660. switch (GV->getLinkage()) {
  1661. case GlobalValue::ExternalLinkage:
  1662. LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
  1663. break;
  1664. case GlobalValue::LinkOnceAnyLinkage:
  1665. case GlobalValue::LinkOnceODRLinkage:
  1666. case GlobalValue::WeakAnyLinkage:
  1667. case GlobalValue::WeakODRLinkage:
  1668. case GlobalValue::ExternalWeakLinkage:
  1669. LinkageAttr = MCSA_Weak;
  1670. break;
  1671. case GlobalValue::AvailableExternallyLinkage:
  1672. LinkageAttr = MCSA_Extern;
  1673. break;
  1674. case GlobalValue::PrivateLinkage:
  1675. return;
  1676. case GlobalValue::InternalLinkage:
  1677. assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
  1678. "InternalLinkage should not have other visibility setting.");
  1679. LinkageAttr = MCSA_LGlobal;
  1680. break;
  1681. case GlobalValue::AppendingLinkage:
  1682. llvm_unreachable("Should never emit this");
  1683. case GlobalValue::CommonLinkage:
  1684. llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
  1685. }
  1686. assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
  1687. MCSymbolAttr VisibilityAttr = MCSA_Invalid;
  1688. if (!TM.getIgnoreXCOFFVisibility()) {
  1689. if (GV->hasDLLExportStorageClass() && !GV->hasDefaultVisibility())
  1690. report_fatal_error(
  1691. "Cannot not be both dllexport and non-default visibility");
  1692. switch (GV->getVisibility()) {
  1693. // TODO: "internal" Visibility needs to go here.
  1694. case GlobalValue::DefaultVisibility:
  1695. if (GV->hasDLLExportStorageClass())
  1696. VisibilityAttr = MAI->getExportedVisibilityAttr();
  1697. break;
  1698. case GlobalValue::HiddenVisibility:
  1699. VisibilityAttr = MAI->getHiddenVisibilityAttr();
  1700. break;
  1701. case GlobalValue::ProtectedVisibility:
  1702. VisibilityAttr = MAI->getProtectedVisibilityAttr();
  1703. break;
  1704. }
  1705. }
  1706. OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
  1707. VisibilityAttr);
  1708. }
  1709. void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
  1710. // Setup CurrentFnDescSym and its containing csect.
  1711. MCSectionXCOFF *FnDescSec =
  1712. cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
  1713. &MF.getFunction(), TM));
  1714. FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
  1715. CurrentFnDescSym = FnDescSec->getQualNameSymbol();
  1716. return AsmPrinter::SetupMachineFunction(MF);
  1717. }
  1718. uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() {
  1719. // Calculate the number of VRs be saved.
  1720. // Vector registers 20 through 31 are marked as reserved and cannot be used
  1721. // in the default ABI.
  1722. const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
  1723. if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
  1724. TM.getAIXExtendedAltivecABI()) {
  1725. const MachineRegisterInfo &MRI = MF->getRegInfo();
  1726. for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg)
  1727. if (MRI.isPhysRegModified(Reg))
  1728. // Number of VRs saved.
  1729. return PPC::V31 - Reg + 1;
  1730. }
  1731. return 0;
  1732. }
  1733. void PPCAIXAsmPrinter::emitFunctionBodyEnd() {
  1734. if (!TM.getXCOFFTracebackTable())
  1735. return;
  1736. emitTracebackTable();
  1737. // If ShouldEmitEHBlock returns true, then the eh info table
  1738. // will be emitted via `AIXException::endFunction`. Otherwise, we
  1739. // need to emit a dumy eh info table when VRs are saved. We could not
  1740. // consolidate these two places into one because there is no easy way
  1741. // to access register information in `AIXException` class.
  1742. if (!TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) &&
  1743. (getNumberOfVRSaved() > 0)) {
  1744. // Emit dummy EH Info Table.
  1745. OutStreamer->switchSection(getObjFileLowering().getCompactUnwindSection());
  1746. MCSymbol *EHInfoLabel =
  1747. TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF);
  1748. OutStreamer->emitLabel(EHInfoLabel);
  1749. // Version number.
  1750. OutStreamer->emitInt32(0);
  1751. const DataLayout &DL = MMI->getModule()->getDataLayout();
  1752. const unsigned PointerSize = DL.getPointerSize();
  1753. // Add necessary paddings in 64 bit mode.
  1754. OutStreamer->emitValueToAlignment(Align(PointerSize));
  1755. OutStreamer->emitIntValue(0, PointerSize);
  1756. OutStreamer->emitIntValue(0, PointerSize);
  1757. OutStreamer->switchSection(MF->getSection());
  1758. }
  1759. }
  1760. void PPCAIXAsmPrinter::emitTracebackTable() {
  1761. // Create a symbol for the end of function.
  1762. MCSymbol *FuncEnd = createTempSymbol(MF->getName());
  1763. OutStreamer->emitLabel(FuncEnd);
  1764. OutStreamer->AddComment("Traceback table begin");
  1765. // Begin with a fullword of zero.
  1766. OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/);
  1767. SmallString<128> CommentString;
  1768. raw_svector_ostream CommentOS(CommentString);
  1769. auto EmitComment = [&]() {
  1770. OutStreamer->AddComment(CommentOS.str());
  1771. CommentString.clear();
  1772. };
  1773. auto EmitCommentAndValue = [&](uint64_t Value, int Size) {
  1774. EmitComment();
  1775. OutStreamer->emitIntValueInHexWithPadding(Value, Size);
  1776. };
  1777. unsigned int Version = 0;
  1778. CommentOS << "Version = " << Version;
  1779. EmitCommentAndValue(Version, 1);
  1780. // There is a lack of information in the IR to assist with determining the
  1781. // source language. AIX exception handling mechanism would only search for
  1782. // personality routine and LSDA area when such language supports exception
  1783. // handling. So to be conservatively correct and allow runtime to do its job,
  1784. // we need to set it to C++ for now.
  1785. TracebackTable::LanguageID LanguageIdentifier =
  1786. TracebackTable::CPlusPlus; // C++
  1787. CommentOS << "Language = "
  1788. << getNameForTracebackTableLanguageId(LanguageIdentifier);
  1789. EmitCommentAndValue(LanguageIdentifier, 1);
  1790. // This is only populated for the third and fourth bytes.
  1791. uint32_t FirstHalfOfMandatoryField = 0;
  1792. // Emit the 3rd byte of the mandatory field.
  1793. // We always set traceback offset bit to true.
  1794. FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask;
  1795. const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
  1796. const MachineRegisterInfo &MRI = MF->getRegInfo();
  1797. // Check the function uses floating-point processor instructions or not
  1798. for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) {
  1799. if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
  1800. FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask;
  1801. break;
  1802. }
  1803. }
  1804. #define GENBOOLCOMMENT(Prefix, V, Field) \
  1805. CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-") \
  1806. << #Field
  1807. #define GENVALUECOMMENT(PrefixAndName, V, Field) \
  1808. CommentOS << (PrefixAndName) << " = " \
  1809. << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >> \
  1810. (TracebackTable::Field##Shift))
  1811. GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage);
  1812. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue);
  1813. EmitComment();
  1814. GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset);
  1815. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure);
  1816. EmitComment();
  1817. GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage);
  1818. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless);
  1819. EmitComment();
  1820. GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent);
  1821. EmitComment();
  1822. GENBOOLCOMMENT("", FirstHalfOfMandatoryField,
  1823. IsFloatingPointOperationLogOrAbortEnabled);
  1824. EmitComment();
  1825. OutStreamer->emitIntValueInHexWithPadding(
  1826. (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
  1827. // Set the 4th byte of the mandatory field.
  1828. FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask;
  1829. const PPCRegisterInfo *RegInfo =
  1830. static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo());
  1831. Register FrameReg = RegInfo->getFrameRegister(*MF);
  1832. if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31))
  1833. FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask;
  1834. const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
  1835. if (!MustSaveCRs.empty())
  1836. FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask;
  1837. if (FI->mustSaveLR())
  1838. FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask;
  1839. GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler);
  1840. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent);
  1841. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed);
  1842. EmitComment();
  1843. GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField,
  1844. OnConditionDirective);
  1845. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved);
  1846. GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved);
  1847. EmitComment();
  1848. OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff),
  1849. 1);
  1850. // Set the 5th byte of mandatory field.
  1851. uint32_t SecondHalfOfMandatoryField = 0;
  1852. // Always store back chain.
  1853. SecondHalfOfMandatoryField |= TracebackTable::IsBackChainStoredMask;
  1854. uint32_t FPRSaved = 0;
  1855. for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) {
  1856. if (MRI.isPhysRegModified(Reg)) {
  1857. FPRSaved = PPC::F31 - Reg + 1;
  1858. break;
  1859. }
  1860. }
  1861. SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) &
  1862. TracebackTable::FPRSavedMask;
  1863. GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored);
  1864. GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup);
  1865. GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved);
  1866. EmitComment();
  1867. OutStreamer->emitIntValueInHexWithPadding(
  1868. (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1);
  1869. // Set the 6th byte of mandatory field.
  1870. // Check whether has Vector Instruction,We only treat instructions uses vector
  1871. // register as vector instructions.
  1872. bool HasVectorInst = false;
  1873. for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg)
  1874. if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
  1875. // Has VMX instruction.
  1876. HasVectorInst = true;
  1877. break;
  1878. }
  1879. if (FI->hasVectorParms() || HasVectorInst)
  1880. SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask;
  1881. uint16_t NumOfVRSaved = getNumberOfVRSaved();
  1882. bool ShouldEmitEHBlock =
  1883. TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) || NumOfVRSaved > 0;
  1884. if (ShouldEmitEHBlock)
  1885. SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask;
  1886. uint32_t GPRSaved = 0;
  1887. // X13 is reserved under 64-bit environment.
  1888. unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13;
  1889. unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31;
  1890. for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) {
  1891. if (MRI.isPhysRegModified(Reg)) {
  1892. GPRSaved = GPREnd - Reg + 1;
  1893. break;
  1894. }
  1895. }
  1896. SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) &
  1897. TracebackTable::GPRSavedMask;
  1898. GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable);
  1899. GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo);
  1900. GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved);
  1901. EmitComment();
  1902. OutStreamer->emitIntValueInHexWithPadding(
  1903. (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1);
  1904. // Set the 7th byte of mandatory field.
  1905. uint32_t NumberOfFixedParms = FI->getFixedParmsNum();
  1906. SecondHalfOfMandatoryField |=
  1907. (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) &
  1908. TracebackTable::NumberOfFixedParmsMask;
  1909. GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField,
  1910. NumberOfFixedParms);
  1911. EmitComment();
  1912. OutStreamer->emitIntValueInHexWithPadding(
  1913. (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
  1914. // Set the 8th byte of mandatory field.
  1915. // Always set parameter on stack.
  1916. SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask;
  1917. uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum();
  1918. SecondHalfOfMandatoryField |=
  1919. (NumberOfFPParms << TracebackTable::NumberOfFloatingPointParmsShift) &
  1920. TracebackTable::NumberOfFloatingPointParmsMask;
  1921. GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField,
  1922. NumberOfFloatingPointParms);
  1923. GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack);
  1924. EmitComment();
  1925. OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff,
  1926. 1);
  1927. // Generate the optional fields of traceback table.
  1928. // Parameter type.
  1929. if (NumberOfFixedParms || NumberOfFPParms) {
  1930. uint32_t ParmsTypeValue = FI->getParmsType();
  1931. Expected<SmallString<32>> ParmsType =
  1932. FI->hasVectorParms()
  1933. ? XCOFF::parseParmsTypeWithVecInfo(
  1934. ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms,
  1935. FI->getVectorParmsNum())
  1936. : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms,
  1937. NumberOfFPParms);
  1938. assert(ParmsType && toString(ParmsType.takeError()).c_str());
  1939. if (ParmsType) {
  1940. CommentOS << "Parameter type = " << ParmsType.get();
  1941. EmitComment();
  1942. }
  1943. OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue,
  1944. sizeof(ParmsTypeValue));
  1945. }
  1946. // Traceback table offset.
  1947. OutStreamer->AddComment("Function size");
  1948. if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) {
  1949. MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol(
  1950. &(MF->getFunction()), TM);
  1951. OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4);
  1952. }
  1953. // Since we unset the Int_Handler.
  1954. if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask)
  1955. report_fatal_error("Hand_Mask not implement yet");
  1956. if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask)
  1957. report_fatal_error("Ctl_Info not implement yet");
  1958. if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) {
  1959. StringRef Name = MF->getName().substr(0, INT16_MAX);
  1960. int16_t NameLength = Name.size();
  1961. CommentOS << "Function name len = "
  1962. << static_cast<unsigned int>(NameLength);
  1963. EmitCommentAndValue(NameLength, 2);
  1964. OutStreamer->AddComment("Function Name");
  1965. OutStreamer->emitBytes(Name);
  1966. }
  1967. if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) {
  1968. uint8_t AllocReg = XCOFF::AllocRegNo;
  1969. OutStreamer->AddComment("AllocaUsed");
  1970. OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg));
  1971. }
  1972. if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) {
  1973. uint16_t VRData = 0;
  1974. if (NumOfVRSaved) {
  1975. // Number of VRs saved.
  1976. VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) &
  1977. TracebackTable::NumberOfVRSavedMask;
  1978. // This bit is supposed to set only when the special register
  1979. // VRSAVE is saved on stack.
  1980. // However, IBM XL compiler sets the bit when any vector registers
  1981. // are saved on the stack. We will follow XL's behavior on AIX
  1982. // so that we don't get surprise behavior change for C code.
  1983. VRData |= TracebackTable::IsVRSavedOnStackMask;
  1984. }
  1985. // Set has_varargs.
  1986. if (FI->getVarArgsFrameIndex())
  1987. VRData |= TracebackTable::HasVarArgsMask;
  1988. // Vector parameters number.
  1989. unsigned VectorParmsNum = FI->getVectorParmsNum();
  1990. VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) &
  1991. TracebackTable::NumberOfVectorParmsMask;
  1992. if (HasVectorInst)
  1993. VRData |= TracebackTable::HasVMXInstructionMask;
  1994. GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved);
  1995. GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack);
  1996. GENBOOLCOMMENT(", ", VRData, HasVarArgs);
  1997. EmitComment();
  1998. OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1);
  1999. GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms);
  2000. GENBOOLCOMMENT(", ", VRData, HasVMXInstruction);
  2001. EmitComment();
  2002. OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1);
  2003. uint32_t VecParmTypeValue = FI->getVecExtParmsType();
  2004. Expected<SmallString<32>> VecParmsType =
  2005. XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum);
  2006. assert(VecParmsType && toString(VecParmsType.takeError()).c_str());
  2007. if (VecParmsType) {
  2008. CommentOS << "Vector Parameter type = " << VecParmsType.get();
  2009. EmitComment();
  2010. }
  2011. OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue,
  2012. sizeof(VecParmTypeValue));
  2013. // Padding 2 bytes.
  2014. CommentOS << "Padding";
  2015. EmitCommentAndValue(0, 2);
  2016. }
  2017. uint8_t ExtensionTableFlag = 0;
  2018. if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) {
  2019. if (ShouldEmitEHBlock)
  2020. ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO;
  2021. if (EnableSSPCanaryBitInTB &&
  2022. TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(MF))
  2023. ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY;
  2024. CommentOS << "ExtensionTableFlag = "
  2025. << getExtendedTBTableFlagString(ExtensionTableFlag);
  2026. EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag));
  2027. }
  2028. if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) {
  2029. auto &Ctx = OutStreamer->getContext();
  2030. MCSymbol *EHInfoSym =
  2031. TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF);
  2032. MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym);
  2033. const MCSymbol *TOCBaseSym =
  2034. cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
  2035. ->getQualNameSymbol();
  2036. const MCExpr *Exp =
  2037. MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx),
  2038. MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
  2039. const DataLayout &DL = getDataLayout();
  2040. OutStreamer->emitValueToAlignment(Align(4));
  2041. OutStreamer->AddComment("EHInfo Table");
  2042. OutStreamer->emitValue(Exp, DL.getPointerSize());
  2043. }
  2044. #undef GENBOOLCOMMENT
  2045. #undef GENVALUECOMMENT
  2046. }
  2047. static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) {
  2048. return GV->hasAppendingLinkage() &&
  2049. StringSwitch<bool>(GV->getName())
  2050. // TODO: Linker could still eliminate the GV if we just skip
  2051. // handling llvm.used array. Skipping them for now until we or the
  2052. // AIX OS team come up with a good solution.
  2053. .Case("llvm.used", true)
  2054. // It's correct to just skip llvm.compiler.used array here.
  2055. .Case("llvm.compiler.used", true)
  2056. .Default(false);
  2057. }
  2058. static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
  2059. return StringSwitch<bool>(GV->getName())
  2060. .Cases("llvm.global_ctors", "llvm.global_dtors", true)
  2061. .Default(false);
  2062. }
  2063. uint64_t PPCAIXAsmPrinter::getAliasOffset(const Constant *C) {
  2064. if (auto *GA = dyn_cast<GlobalAlias>(C))
  2065. return getAliasOffset(GA->getAliasee());
  2066. if (auto *CE = dyn_cast<ConstantExpr>(C)) {
  2067. const MCExpr *LowC = lowerConstant(CE);
  2068. const MCBinaryExpr *CBE = dyn_cast<MCBinaryExpr>(LowC);
  2069. if (!CBE)
  2070. return 0;
  2071. if (CBE->getOpcode() != MCBinaryExpr::Add)
  2072. report_fatal_error("Only adding an offset is supported now.");
  2073. auto *RHS = dyn_cast<MCConstantExpr>(CBE->getRHS());
  2074. if (!RHS)
  2075. report_fatal_error("Unable to get the offset of alias.");
  2076. return RHS->getValue();
  2077. }
  2078. return 0;
  2079. }
  2080. void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
  2081. // Special LLVM global arrays have been handled at the initialization.
  2082. if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV))
  2083. return;
  2084. // If the Global Variable has the toc-data attribute, it needs to be emitted
  2085. // when we emit the .toc section.
  2086. if (GV->hasAttribute("toc-data")) {
  2087. TOCDataGlobalVars.push_back(GV);
  2088. return;
  2089. }
  2090. emitGlobalVariableHelper(GV);
  2091. }
  2092. void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) {
  2093. assert(!GV->getName().startswith("llvm.") &&
  2094. "Unhandled intrinsic global variable.");
  2095. if (GV->hasComdat())
  2096. report_fatal_error("COMDAT not yet supported by AIX.");
  2097. MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
  2098. if (GV->isDeclarationForLinker()) {
  2099. emitLinkage(GV, GVSym);
  2100. return;
  2101. }
  2102. SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
  2103. if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() &&
  2104. !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS.
  2105. report_fatal_error("Encountered a global variable kind that is "
  2106. "not supported yet.");
  2107. // Print GV in verbose mode
  2108. if (isVerbose()) {
  2109. if (GV->hasInitializer()) {
  2110. GV->printAsOperand(OutStreamer->getCommentOS(),
  2111. /*PrintType=*/false, GV->getParent());
  2112. OutStreamer->getCommentOS() << '\n';
  2113. }
  2114. }
  2115. MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
  2116. getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
  2117. // Switch to the containing csect.
  2118. OutStreamer->switchSection(Csect);
  2119. const DataLayout &DL = GV->getParent()->getDataLayout();
  2120. // Handle common and zero-initialized local symbols.
  2121. if (GV->hasCommonLinkage() || GVKind.isBSSLocal() ||
  2122. GVKind.isThreadBSSLocal()) {
  2123. Align Alignment = GV->getAlign().value_or(DL.getPreferredAlign(GV));
  2124. uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
  2125. GVSym->setStorageClass(
  2126. TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
  2127. if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal())
  2128. OutStreamer->emitXCOFFLocalCommonSymbol(
  2129. OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
  2130. GVSym, Alignment);
  2131. else
  2132. OutStreamer->emitCommonSymbol(GVSym, Size, Alignment);
  2133. return;
  2134. }
  2135. MCSymbol *EmittedInitSym = GVSym;
  2136. // Emit linkage for the global variable and its aliases.
  2137. emitLinkage(GV, EmittedInitSym);
  2138. for (const GlobalAlias *GA : GOAliasMap[GV])
  2139. emitLinkage(GA, getSymbol(GA));
  2140. emitAlignment(getGVAlignment(GV, DL), GV);
  2141. // When -fdata-sections is enabled, every GlobalVariable will
  2142. // be put into its own csect; therefore, label is not necessary here.
  2143. if (!TM.getDataSections() || GV->hasSection())
  2144. OutStreamer->emitLabel(EmittedInitSym);
  2145. // No alias to emit.
  2146. if (!GOAliasMap[GV].size()) {
  2147. emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
  2148. return;
  2149. }
  2150. // Aliases with the same offset should be aligned. Record the list of aliases
  2151. // associated with the offset.
  2152. AliasMapTy AliasList;
  2153. for (const GlobalAlias *GA : GOAliasMap[GV])
  2154. AliasList[getAliasOffset(GA->getAliasee())].push_back(GA);
  2155. // Emit alias label and element value for global variable.
  2156. emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer(),
  2157. &AliasList);
  2158. }
  2159. void PPCAIXAsmPrinter::emitFunctionDescriptor() {
  2160. const DataLayout &DL = getDataLayout();
  2161. const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
  2162. MCSectionSubPair Current = OutStreamer->getCurrentSection();
  2163. // Emit function descriptor.
  2164. OutStreamer->switchSection(
  2165. cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
  2166. // Emit aliasing label for function descriptor csect.
  2167. for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
  2168. OutStreamer->emitLabel(getSymbol(Alias));
  2169. // Emit function entry point address.
  2170. OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
  2171. PointerSize);
  2172. // Emit TOC base address.
  2173. const MCSymbol *TOCBaseSym =
  2174. cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
  2175. ->getQualNameSymbol();
  2176. OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
  2177. PointerSize);
  2178. // Emit a null environment pointer.
  2179. OutStreamer->emitIntValue(0, PointerSize);
  2180. OutStreamer->switchSection(Current.first, Current.second);
  2181. }
  2182. void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
  2183. // It's not necessary to emit the label when we have individual
  2184. // function in its own csect.
  2185. if (!TM.getFunctionSections())
  2186. PPCAsmPrinter::emitFunctionEntryLabel();
  2187. // Emit aliasing label for function entry point label.
  2188. for (const GlobalAlias *Alias : GOAliasMap[&MF->getFunction()])
  2189. OutStreamer->emitLabel(
  2190. getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
  2191. }
  2192. void PPCAIXAsmPrinter::emitPGORefs() {
  2193. if (OutContext.hasXCOFFSection(
  2194. "__llvm_prf_cnts",
  2195. XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) {
  2196. MCSection *CntsSection = OutContext.getXCOFFSection(
  2197. "__llvm_prf_cnts", SectionKind::getData(),
  2198. XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD),
  2199. /*MultiSymbolsAllowed*/ true);
  2200. OutStreamer->switchSection(CntsSection);
  2201. if (OutContext.hasXCOFFSection(
  2202. "__llvm_prf_data",
  2203. XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)))
  2204. OutStreamer->emitXCOFFRefDirective("__llvm_prf_data[RW]");
  2205. if (OutContext.hasXCOFFSection(
  2206. "__llvm_prf_names",
  2207. XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD)))
  2208. OutStreamer->emitXCOFFRefDirective("__llvm_prf_names[RO]");
  2209. if (OutContext.hasXCOFFSection(
  2210. "__llvm_prf_vnds",
  2211. XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)))
  2212. OutStreamer->emitXCOFFRefDirective("__llvm_prf_vnds[RW]");
  2213. }
  2214. }
  2215. void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
  2216. // If there are no functions and there are no toc-data definitions in this
  2217. // module, we will never need to reference the TOC base.
  2218. if (M.empty() && TOCDataGlobalVars.empty())
  2219. return;
  2220. emitPGORefs();
  2221. // Switch to section to emit TOC base.
  2222. OutStreamer->switchSection(getObjFileLowering().getTOCBaseSection());
  2223. PPCTargetStreamer *TS =
  2224. static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
  2225. for (auto &I : TOC) {
  2226. MCSectionXCOFF *TCEntry;
  2227. // Setup the csect for the current TC entry. If the variant kind is
  2228. // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a
  2229. // new symbol to prefix the name with a dot.
  2230. if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM) {
  2231. SmallString<128> Name;
  2232. StringRef Prefix = ".";
  2233. Name += Prefix;
  2234. Name += cast<MCSymbolXCOFF>(I.first.first)->getSymbolTableName();
  2235. MCSymbol *S = OutContext.getOrCreateSymbol(Name);
  2236. TCEntry = cast<MCSectionXCOFF>(
  2237. getObjFileLowering().getSectionForTOCEntry(S, TM));
  2238. } else {
  2239. TCEntry = cast<MCSectionXCOFF>(
  2240. getObjFileLowering().getSectionForTOCEntry(I.first.first, TM));
  2241. }
  2242. OutStreamer->switchSection(TCEntry);
  2243. OutStreamer->emitLabel(I.second);
  2244. TS->emitTCEntry(*I.first.first, I.first.second);
  2245. }
  2246. for (const auto *GV : TOCDataGlobalVars)
  2247. emitGlobalVariableHelper(GV);
  2248. }
  2249. bool PPCAIXAsmPrinter::doInitialization(Module &M) {
  2250. const bool Result = PPCAsmPrinter::doInitialization(M);
  2251. auto setCsectAlignment = [this](const GlobalObject *GO) {
  2252. // Declarations have 0 alignment which is set by default.
  2253. if (GO->isDeclarationForLinker())
  2254. return;
  2255. SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
  2256. MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
  2257. getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
  2258. Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
  2259. Csect->ensureMinAlignment(GOAlign);
  2260. };
  2261. // We need to know, up front, the alignment of csects for the assembly path,
  2262. // because once a .csect directive gets emitted, we could not change the
  2263. // alignment value on it.
  2264. for (const auto &G : M.globals()) {
  2265. if (isSpecialLLVMGlobalArrayToSkip(&G))
  2266. continue;
  2267. if (isSpecialLLVMGlobalArrayForStaticInit(&G)) {
  2268. // Generate a format indicator and a unique module id to be a part of
  2269. // the sinit and sterm function names.
  2270. if (FormatIndicatorAndUniqueModId.empty()) {
  2271. std::string UniqueModuleId = getUniqueModuleId(&M);
  2272. if (UniqueModuleId != "")
  2273. // TODO: Use source file full path to generate the unique module id
  2274. // and add a format indicator as a part of function name in case we
  2275. // will support more than one format.
  2276. FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
  2277. else
  2278. // Use the Pid and current time as the unique module id when we cannot
  2279. // generate one based on a module's strong external symbols.
  2280. // FIXME: Adjust the comment accordingly after we use source file full
  2281. // path instead.
  2282. FormatIndicatorAndUniqueModId =
  2283. "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) +
  2284. "_" + llvm::itostr(time(nullptr));
  2285. }
  2286. emitSpecialLLVMGlobal(&G);
  2287. continue;
  2288. }
  2289. setCsectAlignment(&G);
  2290. }
  2291. for (const auto &F : M)
  2292. setCsectAlignment(&F);
  2293. // Construct an aliasing list for each GlobalObject.
  2294. for (const auto &Alias : M.aliases()) {
  2295. const GlobalObject *Base = Alias.getAliaseeObject();
  2296. if (!Base)
  2297. report_fatal_error(
  2298. "alias without a base object is not yet supported on AIX");
  2299. GOAliasMap[Base].push_back(&Alias);
  2300. }
  2301. return Result;
  2302. }
  2303. void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
  2304. switch (MI->getOpcode()) {
  2305. default:
  2306. break;
  2307. case PPC::TW:
  2308. case PPC::TWI:
  2309. case PPC::TD:
  2310. case PPC::TDI: {
  2311. if (MI->getNumOperands() < 5)
  2312. break;
  2313. const MachineOperand &LangMO = MI->getOperand(3);
  2314. const MachineOperand &ReasonMO = MI->getOperand(4);
  2315. if (!LangMO.isImm() || !ReasonMO.isImm())
  2316. break;
  2317. MCSymbol *TempSym = OutContext.createNamedTempSymbol();
  2318. OutStreamer->emitLabel(TempSym);
  2319. OutStreamer->emitXCOFFExceptDirective(CurrentFnSym, TempSym,
  2320. LangMO.getImm(), ReasonMO.getImm(),
  2321. Subtarget->isPPC64() ? MI->getMF()->getInstructionCount() * 8 :
  2322. MI->getMF()->getInstructionCount() * 4,
  2323. MMI->hasDebugInfo());
  2324. break;
  2325. }
  2326. case PPC::GETtlsADDR64AIX:
  2327. case PPC::GETtlsADDR32AIX: {
  2328. // The reference to .__tls_get_addr is unknown to the assembler
  2329. // so we need to emit an external symbol reference.
  2330. MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
  2331. ExtSymSDNodeSymbols.insert(TlsGetAddr);
  2332. break;
  2333. }
  2334. case PPC::BL8:
  2335. case PPC::BL:
  2336. case PPC::BL8_NOP:
  2337. case PPC::BL_NOP: {
  2338. const MachineOperand &MO = MI->getOperand(0);
  2339. if (MO.isSymbol()) {
  2340. MCSymbolXCOFF *S =
  2341. cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
  2342. ExtSymSDNodeSymbols.insert(S);
  2343. }
  2344. } break;
  2345. case PPC::BL_TLS:
  2346. case PPC::BL8_TLS:
  2347. case PPC::BL8_TLS_:
  2348. case PPC::BL8_NOP_TLS:
  2349. report_fatal_error("TLS call not yet implemented");
  2350. case PPC::TAILB:
  2351. case PPC::TAILB8:
  2352. case PPC::TAILBA:
  2353. case PPC::TAILBA8:
  2354. case PPC::TAILBCTR:
  2355. case PPC::TAILBCTR8:
  2356. if (MI->getOperand(0).isSymbol())
  2357. report_fatal_error("Tail call for extern symbol not yet supported.");
  2358. break;
  2359. case PPC::DST:
  2360. case PPC::DST64:
  2361. case PPC::DSTT:
  2362. case PPC::DSTT64:
  2363. case PPC::DSTST:
  2364. case PPC::DSTST64:
  2365. case PPC::DSTSTT:
  2366. case PPC::DSTSTT64:
  2367. EmitToStreamer(
  2368. *OutStreamer,
  2369. MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0));
  2370. return;
  2371. }
  2372. return PPCAsmPrinter::emitInstruction(MI);
  2373. }
  2374. bool PPCAIXAsmPrinter::doFinalization(Module &M) {
  2375. // Do streamer related finalization for DWARF.
  2376. if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo())
  2377. OutStreamer->doFinalizationAtSectionEnd(
  2378. OutStreamer->getContext().getObjectFileInfo()->getTextSection());
  2379. for (MCSymbol *Sym : ExtSymSDNodeSymbols)
  2380. OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
  2381. return PPCAsmPrinter::doFinalization(M);
  2382. }
  2383. static unsigned mapToSinitPriority(int P) {
  2384. if (P < 0 || P > 65535)
  2385. report_fatal_error("invalid init priority");
  2386. if (P <= 20)
  2387. return P;
  2388. if (P < 81)
  2389. return 20 + (P - 20) * 16;
  2390. if (P <= 1124)
  2391. return 1004 + (P - 81);
  2392. if (P < 64512)
  2393. return 2047 + (P - 1124) * 33878;
  2394. return 2147482625u + (P - 64512);
  2395. }
  2396. static std::string convertToSinitPriority(int Priority) {
  2397. // This helper function converts clang init priority to values used in sinit
  2398. // and sterm functions.
  2399. //
  2400. // The conversion strategies are:
  2401. // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
  2402. // reserved priority range [0, 1023] by
  2403. // - directly mapping the first 21 and the last 20 elements of the ranges
  2404. // - linear interpolating the intermediate values with a step size of 16.
  2405. //
  2406. // We map the non reserved clang/gnu priority range of [101, 65535] into the
  2407. // sinit/sterm priority range [1024, 2147483648] by:
  2408. // - directly mapping the first and the last 1024 elements of the ranges
  2409. // - linear interpolating the intermediate values with a step size of 33878.
  2410. unsigned int P = mapToSinitPriority(Priority);
  2411. std::string PrioritySuffix;
  2412. llvm::raw_string_ostream os(PrioritySuffix);
  2413. os << llvm::format_hex_no_prefix(P, 8);
  2414. os.flush();
  2415. return PrioritySuffix;
  2416. }
  2417. void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
  2418. const Constant *List, bool IsCtor) {
  2419. SmallVector<Structor, 8> Structors;
  2420. preprocessXXStructorList(DL, List, Structors);
  2421. if (Structors.empty())
  2422. return;
  2423. unsigned Index = 0;
  2424. for (Structor &S : Structors) {
  2425. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
  2426. S.Func = CE->getOperand(0);
  2427. llvm::GlobalAlias::create(
  2428. GlobalValue::ExternalLinkage,
  2429. (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
  2430. llvm::Twine(convertToSinitPriority(S.Priority)) +
  2431. llvm::Twine("_", FormatIndicatorAndUniqueModId) +
  2432. llvm::Twine("_", llvm::utostr(Index++)),
  2433. cast<Function>(S.Func));
  2434. }
  2435. }
  2436. void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV,
  2437. unsigned Encoding) {
  2438. if (GV) {
  2439. MCSymbol *TypeInfoSym = TM.getSymbol(GV);
  2440. MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym);
  2441. const MCSymbol *TOCBaseSym =
  2442. cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
  2443. ->getQualNameSymbol();
  2444. auto &Ctx = OutStreamer->getContext();
  2445. const MCExpr *Exp =
  2446. MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx),
  2447. MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
  2448. OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding));
  2449. } else
  2450. OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding));
  2451. }
  2452. // Return a pass that prints the PPC assembly code for a MachineFunction to the
  2453. // given output stream.
  2454. static AsmPrinter *
  2455. createPPCAsmPrinterPass(TargetMachine &tm,
  2456. std::unique_ptr<MCStreamer> &&Streamer) {
  2457. if (tm.getTargetTriple().isOSAIX())
  2458. return new PPCAIXAsmPrinter(tm, std::move(Streamer));
  2459. return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
  2460. }
  2461. // Force static initialization.
  2462. extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
  2463. TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
  2464. createPPCAsmPrinterPass);
  2465. TargetRegistry::RegisterAsmPrinter(getThePPC32LETarget(),
  2466. createPPCAsmPrinterPass);
  2467. TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
  2468. createPPCAsmPrinterPass);
  2469. TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
  2470. createPPCAsmPrinterPass);
  2471. }