PPCAsmPrinter.cpp 105 KB

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