CBackend.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697
  1. //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This library converts LLVM code to C code, compilable by GCC and other C
  11. // compilers.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CTargetMachine.h"
  15. #include "llvm/CallingConv.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/DerivedTypes.h"
  18. #include "llvm/Module.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Pass.h"
  21. #include "llvm/PassManager.h"
  22. #include "llvm/TypeSymbolTable.h"
  23. #include "llvm/Intrinsics.h"
  24. #include "llvm/IntrinsicInst.h"
  25. #include "llvm/InlineAsm.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/Analysis/ConstantsScanner.h"
  29. #include "llvm/Analysis/FindUsedTypes.h"
  30. #include "llvm/Analysis/LoopInfo.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/CodeGen/Passes.h"
  33. #include "llvm/CodeGen/IntrinsicLowering.h"
  34. #include "llvm/Transforms/Scalar.h"
  35. #include "llvm/Target/TargetAsmInfo.h"
  36. #include "llvm/Target/TargetData.h"
  37. #include "llvm/Target/TargetRegistry.h"
  38. #include "llvm/Support/CallSite.h"
  39. #include "llvm/Support/CFG.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/FormattedStream.h"
  42. #include "llvm/Support/GetElementPtrTypeIterator.h"
  43. #include "llvm/Support/InstVisitor.h"
  44. #include "llvm/Support/Mangler.h"
  45. #include "llvm/Support/MathExtras.h"
  46. #include "llvm/System/Host.h"
  47. #include "llvm/Config/config.h"
  48. #include <algorithm>
  49. #include <sstream>
  50. using namespace llvm;
  51. extern "C" void LLVMInitializeCBackendTarget() {
  52. // Register the target.
  53. RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
  54. }
  55. namespace {
  56. /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
  57. /// any unnamed structure types that are used by the program, and merges
  58. /// external functions with the same name.
  59. ///
  60. class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
  61. public:
  62. static char ID;
  63. CBackendNameAllUsedStructsAndMergeFunctions()
  64. : ModulePass(&ID) {}
  65. void getAnalysisUsage(AnalysisUsage &AU) const {
  66. AU.addRequired<FindUsedTypes>();
  67. }
  68. virtual const char *getPassName() const {
  69. return "C backend type canonicalizer";
  70. }
  71. virtual bool runOnModule(Module &M);
  72. };
  73. char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
  74. /// CWriter - This class is the main chunk of code that converts an LLVM
  75. /// module to a C translation unit.
  76. class CWriter : public FunctionPass, public InstVisitor<CWriter> {
  77. formatted_raw_ostream &Out;
  78. IntrinsicLowering *IL;
  79. Mangler *Mang;
  80. LoopInfo *LI;
  81. const Module *TheModule;
  82. const TargetAsmInfo* TAsm;
  83. const TargetData* TD;
  84. std::map<const Type *, std::string> TypeNames;
  85. std::map<const ConstantFP *, unsigned> FPConstantMap;
  86. std::set<Function*> intrinsicPrototypesAlreadyGenerated;
  87. std::set<const Argument*> ByValParams;
  88. unsigned FPCounter;
  89. unsigned OpaqueCounter;
  90. DenseMap<const Value*, unsigned> AnonValueNumbers;
  91. unsigned NextAnonValueNumber;
  92. public:
  93. static char ID;
  94. explicit CWriter(formatted_raw_ostream &o)
  95. : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0),
  96. TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
  97. FPCounter = 0;
  98. }
  99. virtual const char *getPassName() const { return "C backend"; }
  100. void getAnalysisUsage(AnalysisUsage &AU) const {
  101. AU.addRequired<LoopInfo>();
  102. AU.setPreservesAll();
  103. }
  104. virtual bool doInitialization(Module &M);
  105. bool runOnFunction(Function &F) {
  106. // Do not codegen any 'available_externally' functions at all, they have
  107. // definitions outside the translation unit.
  108. if (F.hasAvailableExternallyLinkage())
  109. return false;
  110. LI = &getAnalysis<LoopInfo>();
  111. // Get rid of intrinsics we can't handle.
  112. lowerIntrinsics(F);
  113. // Output all floating point constants that cannot be printed accurately.
  114. printFloatingPointConstants(F);
  115. printFunction(F);
  116. return false;
  117. }
  118. virtual bool doFinalization(Module &M) {
  119. // Free memory...
  120. delete IL;
  121. delete TD;
  122. delete Mang;
  123. FPConstantMap.clear();
  124. TypeNames.clear();
  125. ByValParams.clear();
  126. intrinsicPrototypesAlreadyGenerated.clear();
  127. return false;
  128. }
  129. raw_ostream &printType(formatted_raw_ostream &Out,
  130. const Type *Ty,
  131. bool isSigned = false,
  132. const std::string &VariableName = "",
  133. bool IgnoreName = false,
  134. const AttrListPtr &PAL = AttrListPtr());
  135. std::ostream &printType(std::ostream &Out, const Type *Ty,
  136. bool isSigned = false,
  137. const std::string &VariableName = "",
  138. bool IgnoreName = false,
  139. const AttrListPtr &PAL = AttrListPtr());
  140. raw_ostream &printSimpleType(formatted_raw_ostream &Out,
  141. const Type *Ty,
  142. bool isSigned,
  143. const std::string &NameSoFar = "");
  144. std::ostream &printSimpleType(std::ostream &Out, const Type *Ty,
  145. bool isSigned,
  146. const std::string &NameSoFar = "");
  147. void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
  148. const AttrListPtr &PAL,
  149. const PointerType *Ty);
  150. /// writeOperandDeref - Print the result of dereferencing the specified
  151. /// operand with '*'. This is equivalent to printing '*' then using
  152. /// writeOperand, but avoids excess syntax in some cases.
  153. void writeOperandDeref(Value *Operand) {
  154. if (isAddressExposed(Operand)) {
  155. // Already something with an address exposed.
  156. writeOperandInternal(Operand);
  157. } else {
  158. Out << "*(";
  159. writeOperand(Operand);
  160. Out << ")";
  161. }
  162. }
  163. void writeOperand(Value *Operand, bool Static = false);
  164. void writeInstComputationInline(Instruction &I);
  165. void writeOperandInternal(Value *Operand, bool Static = false);
  166. void writeOperandWithCast(Value* Operand, unsigned Opcode);
  167. void writeOperandWithCast(Value* Operand, const ICmpInst &I);
  168. bool writeInstructionCast(const Instruction &I);
  169. void writeMemoryAccess(Value *Operand, const Type *OperandType,
  170. bool IsVolatile, unsigned Alignment);
  171. private :
  172. std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
  173. void lowerIntrinsics(Function &F);
  174. void printModule(Module *M);
  175. void printModuleTypes(const TypeSymbolTable &ST);
  176. void printContainedStructs(const Type *Ty, std::set<const Type *> &);
  177. void printFloatingPointConstants(Function &F);
  178. void printFloatingPointConstants(const Constant *C);
  179. void printFunctionSignature(const Function *F, bool Prototype);
  180. void printFunction(Function &);
  181. void printBasicBlock(BasicBlock *BB);
  182. void printLoop(Loop *L);
  183. void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
  184. void printConstant(Constant *CPV, bool Static);
  185. void printConstantWithCast(Constant *CPV, unsigned Opcode);
  186. bool printConstExprCast(const ConstantExpr *CE, bool Static);
  187. void printConstantArray(ConstantArray *CPA, bool Static);
  188. void printConstantVector(ConstantVector *CV, bool Static);
  189. /// isAddressExposed - Return true if the specified value's name needs to
  190. /// have its address taken in order to get a C value of the correct type.
  191. /// This happens for global variables, byval parameters, and direct allocas.
  192. bool isAddressExposed(const Value *V) const {
  193. if (const Argument *A = dyn_cast<Argument>(V))
  194. return ByValParams.count(A);
  195. return isa<GlobalVariable>(V) || isDirectAlloca(V);
  196. }
  197. // isInlinableInst - Attempt to inline instructions into their uses to build
  198. // trees as much as possible. To do this, we have to consistently decide
  199. // what is acceptable to inline, so that variable declarations don't get
  200. // printed and an extra copy of the expr is not emitted.
  201. //
  202. static bool isInlinableInst(const Instruction &I) {
  203. // Always inline cmp instructions, even if they are shared by multiple
  204. // expressions. GCC generates horrible code if we don't.
  205. if (isa<CmpInst>(I))
  206. return true;
  207. // Must be an expression, must be used exactly once. If it is dead, we
  208. // emit it inline where it would go.
  209. if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
  210. isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
  211. isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
  212. isa<InsertValueInst>(I))
  213. // Don't inline a load across a store or other bad things!
  214. return false;
  215. // Must not be used in inline asm, extractelement, or shufflevector.
  216. if (I.hasOneUse()) {
  217. const Instruction &User = cast<Instruction>(*I.use_back());
  218. if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
  219. isa<ShuffleVectorInst>(User))
  220. return false;
  221. }
  222. // Only inline instruction it if it's use is in the same BB as the inst.
  223. return I.getParent() == cast<Instruction>(I.use_back())->getParent();
  224. }
  225. // isDirectAlloca - Define fixed sized allocas in the entry block as direct
  226. // variables which are accessed with the & operator. This causes GCC to
  227. // generate significantly better code than to emit alloca calls directly.
  228. //
  229. static const AllocaInst *isDirectAlloca(const Value *V) {
  230. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  231. if (!AI) return false;
  232. if (AI->isArrayAllocation())
  233. return 0; // FIXME: we can also inline fixed size array allocas!
  234. if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
  235. return 0;
  236. return AI;
  237. }
  238. // isInlineAsm - Check if the instruction is a call to an inline asm chunk
  239. static bool isInlineAsm(const Instruction& I) {
  240. if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
  241. return true;
  242. return false;
  243. }
  244. // Instruction visitation functions
  245. friend class InstVisitor<CWriter>;
  246. void visitReturnInst(ReturnInst &I);
  247. void visitBranchInst(BranchInst &I);
  248. void visitSwitchInst(SwitchInst &I);
  249. void visitInvokeInst(InvokeInst &I) {
  250. llvm_unreachable("Lowerinvoke pass didn't work!");
  251. }
  252. void visitUnwindInst(UnwindInst &I) {
  253. llvm_unreachable("Lowerinvoke pass didn't work!");
  254. }
  255. void visitUnreachableInst(UnreachableInst &I);
  256. void visitPHINode(PHINode &I);
  257. void visitBinaryOperator(Instruction &I);
  258. void visitICmpInst(ICmpInst &I);
  259. void visitFCmpInst(FCmpInst &I);
  260. void visitCastInst (CastInst &I);
  261. void visitSelectInst(SelectInst &I);
  262. void visitCallInst (CallInst &I);
  263. void visitInlineAsm(CallInst &I);
  264. bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
  265. void visitMallocInst(MallocInst &I);
  266. void visitAllocaInst(AllocaInst &I);
  267. void visitFreeInst (FreeInst &I);
  268. void visitLoadInst (LoadInst &I);
  269. void visitStoreInst (StoreInst &I);
  270. void visitGetElementPtrInst(GetElementPtrInst &I);
  271. void visitVAArgInst (VAArgInst &I);
  272. void visitInsertElementInst(InsertElementInst &I);
  273. void visitExtractElementInst(ExtractElementInst &I);
  274. void visitShuffleVectorInst(ShuffleVectorInst &SVI);
  275. void visitInsertValueInst(InsertValueInst &I);
  276. void visitExtractValueInst(ExtractValueInst &I);
  277. void visitInstruction(Instruction &I) {
  278. #ifndef NDEBUG
  279. cerr << "C Writer does not know about " << I;
  280. #endif
  281. llvm_unreachable(0);
  282. }
  283. void outputLValue(Instruction *I) {
  284. Out << " " << GetValueName(I) << " = ";
  285. }
  286. bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
  287. void printPHICopiesForSuccessor(BasicBlock *CurBlock,
  288. BasicBlock *Successor, unsigned Indent);
  289. void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
  290. unsigned Indent);
  291. void printGEPExpression(Value *Ptr, gep_type_iterator I,
  292. gep_type_iterator E, bool Static);
  293. std::string GetValueName(const Value *Operand);
  294. };
  295. }
  296. char CWriter::ID = 0;
  297. /// This method inserts names for any unnamed structure types that are used by
  298. /// the program, and removes names from structure types that are not used by the
  299. /// program.
  300. ///
  301. bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
  302. // Get a set of types that are used by the program...
  303. std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
  304. // Loop over the module symbol table, removing types from UT that are
  305. // already named, and removing names for types that are not used.
  306. //
  307. TypeSymbolTable &TST = M.getTypeSymbolTable();
  308. for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
  309. TI != TE; ) {
  310. TypeSymbolTable::iterator I = TI++;
  311. // If this isn't a struct or array type, remove it from our set of types
  312. // to name. This simplifies emission later.
  313. if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
  314. !isa<ArrayType>(I->second)) {
  315. TST.remove(I);
  316. } else {
  317. // If this is not used, remove it from the symbol table.
  318. std::set<const Type *>::iterator UTI = UT.find(I->second);
  319. if (UTI == UT.end())
  320. TST.remove(I);
  321. else
  322. UT.erase(UTI); // Only keep one name for this type.
  323. }
  324. }
  325. // UT now contains types that are not named. Loop over it, naming
  326. // structure types.
  327. //
  328. bool Changed = false;
  329. unsigned RenameCounter = 0;
  330. for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
  331. I != E; ++I)
  332. if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
  333. while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
  334. ++RenameCounter;
  335. Changed = true;
  336. }
  337. // Loop over all external functions and globals. If we have two with
  338. // identical names, merge them.
  339. // FIXME: This code should disappear when we don't allow values with the same
  340. // names when they have different types!
  341. std::map<std::string, GlobalValue*> ExtSymbols;
  342. for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
  343. Function *GV = I++;
  344. if (GV->isDeclaration() && GV->hasName()) {
  345. std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
  346. = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
  347. if (!X.second) {
  348. // Found a conflict, replace this global with the previous one.
  349. GlobalValue *OldGV = X.first->second;
  350. GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
  351. GV->eraseFromParent();
  352. Changed = true;
  353. }
  354. }
  355. }
  356. // Do the same for globals.
  357. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  358. I != E;) {
  359. GlobalVariable *GV = I++;
  360. if (GV->isDeclaration() && GV->hasName()) {
  361. std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
  362. = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
  363. if (!X.second) {
  364. // Found a conflict, replace this global with the previous one.
  365. GlobalValue *OldGV = X.first->second;
  366. GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
  367. GV->eraseFromParent();
  368. Changed = true;
  369. }
  370. }
  371. }
  372. return Changed;
  373. }
  374. /// printStructReturnPointerFunctionType - This is like printType for a struct
  375. /// return type, except, instead of printing the type as void (*)(Struct*, ...)
  376. /// print it as "Struct (*)(...)", for struct return functions.
  377. void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
  378. const AttrListPtr &PAL,
  379. const PointerType *TheTy) {
  380. const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
  381. std::stringstream FunctionInnards;
  382. FunctionInnards << " (*) (";
  383. bool PrintedType = false;
  384. FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
  385. const Type *RetTy = cast<PointerType>(I->get())->getElementType();
  386. unsigned Idx = 1;
  387. for (++I, ++Idx; I != E; ++I, ++Idx) {
  388. if (PrintedType)
  389. FunctionInnards << ", ";
  390. const Type *ArgTy = *I;
  391. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  392. assert(isa<PointerType>(ArgTy));
  393. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  394. }
  395. printType(FunctionInnards, ArgTy,
  396. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
  397. PrintedType = true;
  398. }
  399. if (FTy->isVarArg()) {
  400. if (PrintedType)
  401. FunctionInnards << ", ...";
  402. } else if (!PrintedType) {
  403. FunctionInnards << "void";
  404. }
  405. FunctionInnards << ')';
  406. std::string tstr = FunctionInnards.str();
  407. printType(Out, RetTy,
  408. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
  409. }
  410. raw_ostream &
  411. CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
  412. bool isSigned,
  413. const std::string &NameSoFar) {
  414. assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
  415. "Invalid type for printSimpleType");
  416. switch (Ty->getTypeID()) {
  417. case Type::VoidTyID: return Out << "void " << NameSoFar;
  418. case Type::IntegerTyID: {
  419. unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
  420. if (NumBits == 1)
  421. return Out << "bool " << NameSoFar;
  422. else if (NumBits <= 8)
  423. return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
  424. else if (NumBits <= 16)
  425. return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
  426. else if (NumBits <= 32)
  427. return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
  428. else if (NumBits <= 64)
  429. return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
  430. else {
  431. assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
  432. return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
  433. }
  434. }
  435. case Type::FloatTyID: return Out << "float " << NameSoFar;
  436. case Type::DoubleTyID: return Out << "double " << NameSoFar;
  437. // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
  438. // present matches host 'long double'.
  439. case Type::X86_FP80TyID:
  440. case Type::PPC_FP128TyID:
  441. case Type::FP128TyID: return Out << "long double " << NameSoFar;
  442. case Type::VectorTyID: {
  443. const VectorType *VTy = cast<VectorType>(Ty);
  444. return printSimpleType(Out, VTy->getElementType(), isSigned,
  445. " __attribute__((vector_size(" +
  446. utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
  447. }
  448. default:
  449. #ifndef NDEBUG
  450. cerr << "Unknown primitive type: " << *Ty << "\n";
  451. #endif
  452. llvm_unreachable(0);
  453. }
  454. }
  455. std::ostream &
  456. CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
  457. const std::string &NameSoFar) {
  458. assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) &&
  459. "Invalid type for printSimpleType");
  460. switch (Ty->getTypeID()) {
  461. case Type::VoidTyID: return Out << "void " << NameSoFar;
  462. case Type::IntegerTyID: {
  463. unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
  464. if (NumBits == 1)
  465. return Out << "bool " << NameSoFar;
  466. else if (NumBits <= 8)
  467. return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
  468. else if (NumBits <= 16)
  469. return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
  470. else if (NumBits <= 32)
  471. return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
  472. else if (NumBits <= 64)
  473. return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
  474. else {
  475. assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
  476. return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
  477. }
  478. }
  479. case Type::FloatTyID: return Out << "float " << NameSoFar;
  480. case Type::DoubleTyID: return Out << "double " << NameSoFar;
  481. // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
  482. // present matches host 'long double'.
  483. case Type::X86_FP80TyID:
  484. case Type::PPC_FP128TyID:
  485. case Type::FP128TyID: return Out << "long double " << NameSoFar;
  486. case Type::VectorTyID: {
  487. const VectorType *VTy = cast<VectorType>(Ty);
  488. return printSimpleType(Out, VTy->getElementType(), isSigned,
  489. " __attribute__((vector_size(" +
  490. utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
  491. }
  492. default:
  493. #ifndef NDEBUG
  494. cerr << "Unknown primitive type: " << *Ty << "\n";
  495. #endif
  496. llvm_unreachable(0);
  497. }
  498. }
  499. // Pass the Type* and the variable name and this prints out the variable
  500. // declaration.
  501. //
  502. raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
  503. const Type *Ty,
  504. bool isSigned, const std::string &NameSoFar,
  505. bool IgnoreName, const AttrListPtr &PAL) {
  506. if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
  507. printSimpleType(Out, Ty, isSigned, NameSoFar);
  508. return Out;
  509. }
  510. // Check to see if the type is named.
  511. if (!IgnoreName || isa<OpaqueType>(Ty)) {
  512. std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
  513. if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
  514. }
  515. switch (Ty->getTypeID()) {
  516. case Type::FunctionTyID: {
  517. const FunctionType *FTy = cast<FunctionType>(Ty);
  518. std::stringstream FunctionInnards;
  519. FunctionInnards << " (" << NameSoFar << ") (";
  520. unsigned Idx = 1;
  521. for (FunctionType::param_iterator I = FTy->param_begin(),
  522. E = FTy->param_end(); I != E; ++I) {
  523. const Type *ArgTy = *I;
  524. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  525. assert(isa<PointerType>(ArgTy));
  526. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  527. }
  528. if (I != FTy->param_begin())
  529. FunctionInnards << ", ";
  530. printType(FunctionInnards, ArgTy,
  531. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
  532. ++Idx;
  533. }
  534. if (FTy->isVarArg()) {
  535. if (FTy->getNumParams())
  536. FunctionInnards << ", ...";
  537. } else if (!FTy->getNumParams()) {
  538. FunctionInnards << "void";
  539. }
  540. FunctionInnards << ')';
  541. std::string tstr = FunctionInnards.str();
  542. printType(Out, FTy->getReturnType(),
  543. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
  544. return Out;
  545. }
  546. case Type::StructTyID: {
  547. const StructType *STy = cast<StructType>(Ty);
  548. Out << NameSoFar + " {\n";
  549. unsigned Idx = 0;
  550. for (StructType::element_iterator I = STy->element_begin(),
  551. E = STy->element_end(); I != E; ++I) {
  552. Out << " ";
  553. printType(Out, *I, false, "field" + utostr(Idx++));
  554. Out << ";\n";
  555. }
  556. Out << '}';
  557. if (STy->isPacked())
  558. Out << " __attribute__ ((packed))";
  559. return Out;
  560. }
  561. case Type::PointerTyID: {
  562. const PointerType *PTy = cast<PointerType>(Ty);
  563. std::string ptrName = "*" + NameSoFar;
  564. if (isa<ArrayType>(PTy->getElementType()) ||
  565. isa<VectorType>(PTy->getElementType()))
  566. ptrName = "(" + ptrName + ")";
  567. if (!PAL.isEmpty())
  568. // Must be a function ptr cast!
  569. return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
  570. return printType(Out, PTy->getElementType(), false, ptrName);
  571. }
  572. case Type::ArrayTyID: {
  573. const ArrayType *ATy = cast<ArrayType>(Ty);
  574. unsigned NumElements = ATy->getNumElements();
  575. if (NumElements == 0) NumElements = 1;
  576. // Arrays are wrapped in structs to allow them to have normal
  577. // value semantics (avoiding the array "decay").
  578. Out << NameSoFar << " { ";
  579. printType(Out, ATy->getElementType(), false,
  580. "array[" + utostr(NumElements) + "]");
  581. return Out << "; }";
  582. }
  583. case Type::OpaqueTyID: {
  584. std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
  585. assert(TypeNames.find(Ty) == TypeNames.end());
  586. TypeNames[Ty] = TyName;
  587. return Out << TyName << ' ' << NameSoFar;
  588. }
  589. default:
  590. llvm_unreachable("Unhandled case in getTypeProps!");
  591. }
  592. return Out;
  593. }
  594. // Pass the Type* and the variable name and this prints out the variable
  595. // declaration.
  596. //
  597. std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
  598. bool isSigned, const std::string &NameSoFar,
  599. bool IgnoreName, const AttrListPtr &PAL) {
  600. if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
  601. printSimpleType(Out, Ty, isSigned, NameSoFar);
  602. return Out;
  603. }
  604. // Check to see if the type is named.
  605. if (!IgnoreName || isa<OpaqueType>(Ty)) {
  606. std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
  607. if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
  608. }
  609. switch (Ty->getTypeID()) {
  610. case Type::FunctionTyID: {
  611. const FunctionType *FTy = cast<FunctionType>(Ty);
  612. std::stringstream FunctionInnards;
  613. FunctionInnards << " (" << NameSoFar << ") (";
  614. unsigned Idx = 1;
  615. for (FunctionType::param_iterator I = FTy->param_begin(),
  616. E = FTy->param_end(); I != E; ++I) {
  617. const Type *ArgTy = *I;
  618. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  619. assert(isa<PointerType>(ArgTy));
  620. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  621. }
  622. if (I != FTy->param_begin())
  623. FunctionInnards << ", ";
  624. printType(FunctionInnards, ArgTy,
  625. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
  626. ++Idx;
  627. }
  628. if (FTy->isVarArg()) {
  629. if (FTy->getNumParams())
  630. FunctionInnards << ", ...";
  631. } else if (!FTy->getNumParams()) {
  632. FunctionInnards << "void";
  633. }
  634. FunctionInnards << ')';
  635. std::string tstr = FunctionInnards.str();
  636. printType(Out, FTy->getReturnType(),
  637. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
  638. return Out;
  639. }
  640. case Type::StructTyID: {
  641. const StructType *STy = cast<StructType>(Ty);
  642. Out << NameSoFar + " {\n";
  643. unsigned Idx = 0;
  644. for (StructType::element_iterator I = STy->element_begin(),
  645. E = STy->element_end(); I != E; ++I) {
  646. Out << " ";
  647. printType(Out, *I, false, "field" + utostr(Idx++));
  648. Out << ";\n";
  649. }
  650. Out << '}';
  651. if (STy->isPacked())
  652. Out << " __attribute__ ((packed))";
  653. return Out;
  654. }
  655. case Type::PointerTyID: {
  656. const PointerType *PTy = cast<PointerType>(Ty);
  657. std::string ptrName = "*" + NameSoFar;
  658. if (isa<ArrayType>(PTy->getElementType()) ||
  659. isa<VectorType>(PTy->getElementType()))
  660. ptrName = "(" + ptrName + ")";
  661. if (!PAL.isEmpty())
  662. // Must be a function ptr cast!
  663. return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
  664. return printType(Out, PTy->getElementType(), false, ptrName);
  665. }
  666. case Type::ArrayTyID: {
  667. const ArrayType *ATy = cast<ArrayType>(Ty);
  668. unsigned NumElements = ATy->getNumElements();
  669. if (NumElements == 0) NumElements = 1;
  670. // Arrays are wrapped in structs to allow them to have normal
  671. // value semantics (avoiding the array "decay").
  672. Out << NameSoFar << " { ";
  673. printType(Out, ATy->getElementType(), false,
  674. "array[" + utostr(NumElements) + "]");
  675. return Out << "; }";
  676. }
  677. case Type::OpaqueTyID: {
  678. std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
  679. assert(TypeNames.find(Ty) == TypeNames.end());
  680. TypeNames[Ty] = TyName;
  681. return Out << TyName << ' ' << NameSoFar;
  682. }
  683. default:
  684. llvm_unreachable("Unhandled case in getTypeProps!");
  685. }
  686. return Out;
  687. }
  688. void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
  689. // As a special case, print the array as a string if it is an array of
  690. // ubytes or an array of sbytes with positive values.
  691. //
  692. const Type *ETy = CPA->getType()->getElementType();
  693. bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
  694. ETy == Type::getInt8Ty(CPA->getContext()));
  695. // Make sure the last character is a null char, as automatically added by C
  696. if (isString && (CPA->getNumOperands() == 0 ||
  697. !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
  698. isString = false;
  699. if (isString) {
  700. Out << '\"';
  701. // Keep track of whether the last number was a hexadecimal escape
  702. bool LastWasHex = false;
  703. // Do not include the last character, which we know is null
  704. for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
  705. unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
  706. // Print it out literally if it is a printable character. The only thing
  707. // to be careful about is when the last letter output was a hex escape
  708. // code, in which case we have to be careful not to print out hex digits
  709. // explicitly (the C compiler thinks it is a continuation of the previous
  710. // character, sheesh...)
  711. //
  712. if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
  713. LastWasHex = false;
  714. if (C == '"' || C == '\\')
  715. Out << "\\" << (char)C;
  716. else
  717. Out << (char)C;
  718. } else {
  719. LastWasHex = false;
  720. switch (C) {
  721. case '\n': Out << "\\n"; break;
  722. case '\t': Out << "\\t"; break;
  723. case '\r': Out << "\\r"; break;
  724. case '\v': Out << "\\v"; break;
  725. case '\a': Out << "\\a"; break;
  726. case '\"': Out << "\\\""; break;
  727. case '\'': Out << "\\\'"; break;
  728. default:
  729. Out << "\\x";
  730. Out << (char)(( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
  731. Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
  732. LastWasHex = true;
  733. break;
  734. }
  735. }
  736. }
  737. Out << '\"';
  738. } else {
  739. Out << '{';
  740. if (CPA->getNumOperands()) {
  741. Out << ' ';
  742. printConstant(cast<Constant>(CPA->getOperand(0)), Static);
  743. for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
  744. Out << ", ";
  745. printConstant(cast<Constant>(CPA->getOperand(i)), Static);
  746. }
  747. }
  748. Out << " }";
  749. }
  750. }
  751. void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
  752. Out << '{';
  753. if (CP->getNumOperands()) {
  754. Out << ' ';
  755. printConstant(cast<Constant>(CP->getOperand(0)), Static);
  756. for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
  757. Out << ", ";
  758. printConstant(cast<Constant>(CP->getOperand(i)), Static);
  759. }
  760. }
  761. Out << " }";
  762. }
  763. // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
  764. // textually as a double (rather than as a reference to a stack-allocated
  765. // variable). We decide this by converting CFP to a string and back into a
  766. // double, and then checking whether the conversion results in a bit-equal
  767. // double to the original value of CFP. This depends on us and the target C
  768. // compiler agreeing on the conversion process (which is pretty likely since we
  769. // only deal in IEEE FP).
  770. //
  771. static bool isFPCSafeToPrint(const ConstantFP *CFP) {
  772. bool ignored;
  773. // Do long doubles in hex for now.
  774. if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
  775. CFP->getType() != Type::getDoubleTy(CFP->getContext()))
  776. return false;
  777. APFloat APF = APFloat(CFP->getValueAPF()); // copy
  778. if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
  779. APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
  780. #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
  781. char Buffer[100];
  782. sprintf(Buffer, "%a", APF.convertToDouble());
  783. if (!strncmp(Buffer, "0x", 2) ||
  784. !strncmp(Buffer, "-0x", 3) ||
  785. !strncmp(Buffer, "+0x", 3))
  786. return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
  787. return false;
  788. #else
  789. std::string StrVal = ftostr(APF);
  790. while (StrVal[0] == ' ')
  791. StrVal.erase(StrVal.begin());
  792. // Check to make sure that the stringized number is not some string like "Inf"
  793. // or NaN. Check that the string matches the "[-+]?[0-9]" regex.
  794. if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
  795. ((StrVal[0] == '-' || StrVal[0] == '+') &&
  796. (StrVal[1] >= '0' && StrVal[1] <= '9')))
  797. // Reparse stringized version!
  798. return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
  799. return false;
  800. #endif
  801. }
  802. /// Print out the casting for a cast operation. This does the double casting
  803. /// necessary for conversion to the destination type, if necessary.
  804. /// @brief Print a cast
  805. void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
  806. // Print the destination type cast
  807. switch (opc) {
  808. case Instruction::UIToFP:
  809. case Instruction::SIToFP:
  810. case Instruction::IntToPtr:
  811. case Instruction::Trunc:
  812. case Instruction::BitCast:
  813. case Instruction::FPExt:
  814. case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
  815. Out << '(';
  816. printType(Out, DstTy);
  817. Out << ')';
  818. break;
  819. case Instruction::ZExt:
  820. case Instruction::PtrToInt:
  821. case Instruction::FPToUI: // For these, make sure we get an unsigned dest
  822. Out << '(';
  823. printSimpleType(Out, DstTy, false);
  824. Out << ')';
  825. break;
  826. case Instruction::SExt:
  827. case Instruction::FPToSI: // For these, make sure we get a signed dest
  828. Out << '(';
  829. printSimpleType(Out, DstTy, true);
  830. Out << ')';
  831. break;
  832. default:
  833. llvm_unreachable("Invalid cast opcode");
  834. }
  835. // Print the source type cast
  836. switch (opc) {
  837. case Instruction::UIToFP:
  838. case Instruction::ZExt:
  839. Out << '(';
  840. printSimpleType(Out, SrcTy, false);
  841. Out << ')';
  842. break;
  843. case Instruction::SIToFP:
  844. case Instruction::SExt:
  845. Out << '(';
  846. printSimpleType(Out, SrcTy, true);
  847. Out << ')';
  848. break;
  849. case Instruction::IntToPtr:
  850. case Instruction::PtrToInt:
  851. // Avoid "cast to pointer from integer of different size" warnings
  852. Out << "(unsigned long)";
  853. break;
  854. case Instruction::Trunc:
  855. case Instruction::BitCast:
  856. case Instruction::FPExt:
  857. case Instruction::FPTrunc:
  858. case Instruction::FPToSI:
  859. case Instruction::FPToUI:
  860. break; // These don't need a source cast.
  861. default:
  862. llvm_unreachable("Invalid cast opcode");
  863. break;
  864. }
  865. }
  866. // printConstant - The LLVM Constant to C Constant converter.
  867. void CWriter::printConstant(Constant *CPV, bool Static) {
  868. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
  869. switch (CE->getOpcode()) {
  870. case Instruction::Trunc:
  871. case Instruction::ZExt:
  872. case Instruction::SExt:
  873. case Instruction::FPTrunc:
  874. case Instruction::FPExt:
  875. case Instruction::UIToFP:
  876. case Instruction::SIToFP:
  877. case Instruction::FPToUI:
  878. case Instruction::FPToSI:
  879. case Instruction::PtrToInt:
  880. case Instruction::IntToPtr:
  881. case Instruction::BitCast:
  882. Out << "(";
  883. printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
  884. if (CE->getOpcode() == Instruction::SExt &&
  885. CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
  886. // Make sure we really sext from bool here by subtracting from 0
  887. Out << "0-";
  888. }
  889. printConstant(CE->getOperand(0), Static);
  890. if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
  891. (CE->getOpcode() == Instruction::Trunc ||
  892. CE->getOpcode() == Instruction::FPToUI ||
  893. CE->getOpcode() == Instruction::FPToSI ||
  894. CE->getOpcode() == Instruction::PtrToInt)) {
  895. // Make sure we really truncate to bool here by anding with 1
  896. Out << "&1u";
  897. }
  898. Out << ')';
  899. return;
  900. case Instruction::GetElementPtr:
  901. Out << "(";
  902. printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
  903. gep_type_end(CPV), Static);
  904. Out << ")";
  905. return;
  906. case Instruction::Select:
  907. Out << '(';
  908. printConstant(CE->getOperand(0), Static);
  909. Out << '?';
  910. printConstant(CE->getOperand(1), Static);
  911. Out << ':';
  912. printConstant(CE->getOperand(2), Static);
  913. Out << ')';
  914. return;
  915. case Instruction::Add:
  916. case Instruction::FAdd:
  917. case Instruction::Sub:
  918. case Instruction::FSub:
  919. case Instruction::Mul:
  920. case Instruction::FMul:
  921. case Instruction::SDiv:
  922. case Instruction::UDiv:
  923. case Instruction::FDiv:
  924. case Instruction::URem:
  925. case Instruction::SRem:
  926. case Instruction::FRem:
  927. case Instruction::And:
  928. case Instruction::Or:
  929. case Instruction::Xor:
  930. case Instruction::ICmp:
  931. case Instruction::Shl:
  932. case Instruction::LShr:
  933. case Instruction::AShr:
  934. {
  935. Out << '(';
  936. bool NeedsClosingParens = printConstExprCast(CE, Static);
  937. printConstantWithCast(CE->getOperand(0), CE->getOpcode());
  938. switch (CE->getOpcode()) {
  939. case Instruction::Add:
  940. case Instruction::FAdd: Out << " + "; break;
  941. case Instruction::Sub:
  942. case Instruction::FSub: Out << " - "; break;
  943. case Instruction::Mul:
  944. case Instruction::FMul: Out << " * "; break;
  945. case Instruction::URem:
  946. case Instruction::SRem:
  947. case Instruction::FRem: Out << " % "; break;
  948. case Instruction::UDiv:
  949. case Instruction::SDiv:
  950. case Instruction::FDiv: Out << " / "; break;
  951. case Instruction::And: Out << " & "; break;
  952. case Instruction::Or: Out << " | "; break;
  953. case Instruction::Xor: Out << " ^ "; break;
  954. case Instruction::Shl: Out << " << "; break;
  955. case Instruction::LShr:
  956. case Instruction::AShr: Out << " >> "; break;
  957. case Instruction::ICmp:
  958. switch (CE->getPredicate()) {
  959. case ICmpInst::ICMP_EQ: Out << " == "; break;
  960. case ICmpInst::ICMP_NE: Out << " != "; break;
  961. case ICmpInst::ICMP_SLT:
  962. case ICmpInst::ICMP_ULT: Out << " < "; break;
  963. case ICmpInst::ICMP_SLE:
  964. case ICmpInst::ICMP_ULE: Out << " <= "; break;
  965. case ICmpInst::ICMP_SGT:
  966. case ICmpInst::ICMP_UGT: Out << " > "; break;
  967. case ICmpInst::ICMP_SGE:
  968. case ICmpInst::ICMP_UGE: Out << " >= "; break;
  969. default: llvm_unreachable("Illegal ICmp predicate");
  970. }
  971. break;
  972. default: llvm_unreachable("Illegal opcode here!");
  973. }
  974. printConstantWithCast(CE->getOperand(1), CE->getOpcode());
  975. if (NeedsClosingParens)
  976. Out << "))";
  977. Out << ')';
  978. return;
  979. }
  980. case Instruction::FCmp: {
  981. Out << '(';
  982. bool NeedsClosingParens = printConstExprCast(CE, Static);
  983. if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
  984. Out << "0";
  985. else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
  986. Out << "1";
  987. else {
  988. const char* op = 0;
  989. switch (CE->getPredicate()) {
  990. default: llvm_unreachable("Illegal FCmp predicate");
  991. case FCmpInst::FCMP_ORD: op = "ord"; break;
  992. case FCmpInst::FCMP_UNO: op = "uno"; break;
  993. case FCmpInst::FCMP_UEQ: op = "ueq"; break;
  994. case FCmpInst::FCMP_UNE: op = "une"; break;
  995. case FCmpInst::FCMP_ULT: op = "ult"; break;
  996. case FCmpInst::FCMP_ULE: op = "ule"; break;
  997. case FCmpInst::FCMP_UGT: op = "ugt"; break;
  998. case FCmpInst::FCMP_UGE: op = "uge"; break;
  999. case FCmpInst::FCMP_OEQ: op = "oeq"; break;
  1000. case FCmpInst::FCMP_ONE: op = "one"; break;
  1001. case FCmpInst::FCMP_OLT: op = "olt"; break;
  1002. case FCmpInst::FCMP_OLE: op = "ole"; break;
  1003. case FCmpInst::FCMP_OGT: op = "ogt"; break;
  1004. case FCmpInst::FCMP_OGE: op = "oge"; break;
  1005. }
  1006. Out << "llvm_fcmp_" << op << "(";
  1007. printConstantWithCast(CE->getOperand(0), CE->getOpcode());
  1008. Out << ", ";
  1009. printConstantWithCast(CE->getOperand(1), CE->getOpcode());
  1010. Out << ")";
  1011. }
  1012. if (NeedsClosingParens)
  1013. Out << "))";
  1014. Out << ')';
  1015. return;
  1016. }
  1017. default:
  1018. #ifndef NDEBUG
  1019. cerr << "CWriter Error: Unhandled constant expression: "
  1020. << *CE << "\n";
  1021. #endif
  1022. llvm_unreachable(0);
  1023. }
  1024. } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
  1025. Out << "((";
  1026. printType(Out, CPV->getType()); // sign doesn't matter
  1027. Out << ")/*UNDEF*/";
  1028. if (!isa<VectorType>(CPV->getType())) {
  1029. Out << "0)";
  1030. } else {
  1031. Out << "{})";
  1032. }
  1033. return;
  1034. }
  1035. if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
  1036. const Type* Ty = CI->getType();
  1037. if (Ty == Type::getInt1Ty(CPV->getContext()))
  1038. Out << (CI->getZExtValue() ? '1' : '0');
  1039. else if (Ty == Type::getInt32Ty(CPV->getContext()))
  1040. Out << CI->getZExtValue() << 'u';
  1041. else if (Ty->getPrimitiveSizeInBits() > 32)
  1042. Out << CI->getZExtValue() << "ull";
  1043. else {
  1044. Out << "((";
  1045. printSimpleType(Out, Ty, false) << ')';
  1046. if (CI->isMinValue(true))
  1047. Out << CI->getZExtValue() << 'u';
  1048. else
  1049. Out << CI->getSExtValue();
  1050. Out << ')';
  1051. }
  1052. return;
  1053. }
  1054. switch (CPV->getType()->getTypeID()) {
  1055. case Type::FloatTyID:
  1056. case Type::DoubleTyID:
  1057. case Type::X86_FP80TyID:
  1058. case Type::PPC_FP128TyID:
  1059. case Type::FP128TyID: {
  1060. ConstantFP *FPC = cast<ConstantFP>(CPV);
  1061. std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
  1062. if (I != FPConstantMap.end()) {
  1063. // Because of FP precision problems we must load from a stack allocated
  1064. // value that holds the value in hex.
  1065. Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
  1066. "float" :
  1067. FPC->getType() == Type::getDoubleTy(CPV->getContext()) ?
  1068. "double" :
  1069. "long double")
  1070. << "*)&FPConstant" << I->second << ')';
  1071. } else {
  1072. double V;
  1073. if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
  1074. V = FPC->getValueAPF().convertToFloat();
  1075. else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
  1076. V = FPC->getValueAPF().convertToDouble();
  1077. else {
  1078. // Long double. Convert the number to double, discarding precision.
  1079. // This is not awesome, but it at least makes the CBE output somewhat
  1080. // useful.
  1081. APFloat Tmp = FPC->getValueAPF();
  1082. bool LosesInfo;
  1083. Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
  1084. V = Tmp.convertToDouble();
  1085. }
  1086. if (IsNAN(V)) {
  1087. // The value is NaN
  1088. // FIXME the actual NaN bits should be emitted.
  1089. // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
  1090. // it's 0x7ff4.
  1091. const unsigned long QuietNaN = 0x7ff8UL;
  1092. //const unsigned long SignalNaN = 0x7ff4UL;
  1093. // We need to grab the first part of the FP #
  1094. char Buffer[100];
  1095. uint64_t ll = DoubleToBits(V);
  1096. sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
  1097. std::string Num(&Buffer[0], &Buffer[6]);
  1098. unsigned long Val = strtoul(Num.c_str(), 0, 16);
  1099. if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
  1100. Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
  1101. << Buffer << "\") /*nan*/ ";
  1102. else
  1103. Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
  1104. << Buffer << "\") /*nan*/ ";
  1105. } else if (IsInf(V)) {
  1106. // The value is Inf
  1107. if (V < 0) Out << '-';
  1108. Out << "LLVM_INF" <<
  1109. (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
  1110. << " /*inf*/ ";
  1111. } else {
  1112. std::string Num;
  1113. #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
  1114. // Print out the constant as a floating point number.
  1115. char Buffer[100];
  1116. sprintf(Buffer, "%a", V);
  1117. Num = Buffer;
  1118. #else
  1119. Num = ftostr(FPC->getValueAPF());
  1120. #endif
  1121. Out << Num;
  1122. }
  1123. }
  1124. break;
  1125. }
  1126. case Type::ArrayTyID:
  1127. // Use C99 compound expression literal initializer syntax.
  1128. if (!Static) {
  1129. Out << "(";
  1130. printType(Out, CPV->getType());
  1131. Out << ")";
  1132. }
  1133. Out << "{ "; // Arrays are wrapped in struct types.
  1134. if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
  1135. printConstantArray(CA, Static);
  1136. } else {
  1137. assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
  1138. const ArrayType *AT = cast<ArrayType>(CPV->getType());
  1139. Out << '{';
  1140. if (AT->getNumElements()) {
  1141. Out << ' ';
  1142. Constant *CZ = Constant::getNullValue(AT->getElementType());
  1143. printConstant(CZ, Static);
  1144. for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
  1145. Out << ", ";
  1146. printConstant(CZ, Static);
  1147. }
  1148. }
  1149. Out << " }";
  1150. }
  1151. Out << " }"; // Arrays are wrapped in struct types.
  1152. break;
  1153. case Type::VectorTyID:
  1154. // Use C99 compound expression literal initializer syntax.
  1155. if (!Static) {
  1156. Out << "(";
  1157. printType(Out, CPV->getType());
  1158. Out << ")";
  1159. }
  1160. if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
  1161. printConstantVector(CV, Static);
  1162. } else {
  1163. assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
  1164. const VectorType *VT = cast<VectorType>(CPV->getType());
  1165. Out << "{ ";
  1166. Constant *CZ = Constant::getNullValue(VT->getElementType());
  1167. printConstant(CZ, Static);
  1168. for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
  1169. Out << ", ";
  1170. printConstant(CZ, Static);
  1171. }
  1172. Out << " }";
  1173. }
  1174. break;
  1175. case Type::StructTyID:
  1176. // Use C99 compound expression literal initializer syntax.
  1177. if (!Static) {
  1178. Out << "(";
  1179. printType(Out, CPV->getType());
  1180. Out << ")";
  1181. }
  1182. if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
  1183. const StructType *ST = cast<StructType>(CPV->getType());
  1184. Out << '{';
  1185. if (ST->getNumElements()) {
  1186. Out << ' ';
  1187. printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
  1188. for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
  1189. Out << ", ";
  1190. printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
  1191. }
  1192. }
  1193. Out << " }";
  1194. } else {
  1195. Out << '{';
  1196. if (CPV->getNumOperands()) {
  1197. Out << ' ';
  1198. printConstant(cast<Constant>(CPV->getOperand(0)), Static);
  1199. for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
  1200. Out << ", ";
  1201. printConstant(cast<Constant>(CPV->getOperand(i)), Static);
  1202. }
  1203. }
  1204. Out << " }";
  1205. }
  1206. break;
  1207. case Type::PointerTyID:
  1208. if (isa<ConstantPointerNull>(CPV)) {
  1209. Out << "((";
  1210. printType(Out, CPV->getType()); // sign doesn't matter
  1211. Out << ")/*NULL*/0)";
  1212. break;
  1213. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
  1214. writeOperand(GV, Static);
  1215. break;
  1216. }
  1217. // FALL THROUGH
  1218. default:
  1219. #ifndef NDEBUG
  1220. cerr << "Unknown constant type: " << *CPV << "\n";
  1221. #endif
  1222. llvm_unreachable(0);
  1223. }
  1224. }
  1225. // Some constant expressions need to be casted back to the original types
  1226. // because their operands were casted to the expected type. This function takes
  1227. // care of detecting that case and printing the cast for the ConstantExpr.
  1228. bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
  1229. bool NeedsExplicitCast = false;
  1230. const Type *Ty = CE->getOperand(0)->getType();
  1231. bool TypeIsSigned = false;
  1232. switch (CE->getOpcode()) {
  1233. case Instruction::Add:
  1234. case Instruction::Sub:
  1235. case Instruction::Mul:
  1236. // We need to cast integer arithmetic so that it is always performed
  1237. // as unsigned, to avoid undefined behavior on overflow.
  1238. case Instruction::LShr:
  1239. case Instruction::URem:
  1240. case Instruction::UDiv: NeedsExplicitCast = true; break;
  1241. case Instruction::AShr:
  1242. case Instruction::SRem:
  1243. case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
  1244. case Instruction::SExt:
  1245. Ty = CE->getType();
  1246. NeedsExplicitCast = true;
  1247. TypeIsSigned = true;
  1248. break;
  1249. case Instruction::ZExt:
  1250. case Instruction::Trunc:
  1251. case Instruction::FPTrunc:
  1252. case Instruction::FPExt:
  1253. case Instruction::UIToFP:
  1254. case Instruction::SIToFP:
  1255. case Instruction::FPToUI:
  1256. case Instruction::FPToSI:
  1257. case Instruction::PtrToInt:
  1258. case Instruction::IntToPtr:
  1259. case Instruction::BitCast:
  1260. Ty = CE->getType();
  1261. NeedsExplicitCast = true;
  1262. break;
  1263. default: break;
  1264. }
  1265. if (NeedsExplicitCast) {
  1266. Out << "((";
  1267. if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
  1268. printSimpleType(Out, Ty, TypeIsSigned);
  1269. else
  1270. printType(Out, Ty); // not integer, sign doesn't matter
  1271. Out << ")(";
  1272. }
  1273. return NeedsExplicitCast;
  1274. }
  1275. // Print a constant assuming that it is the operand for a given Opcode. The
  1276. // opcodes that care about sign need to cast their operands to the expected
  1277. // type before the operation proceeds. This function does the casting.
  1278. void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
  1279. // Extract the operand's type, we'll need it.
  1280. const Type* OpTy = CPV->getType();
  1281. // Indicate whether to do the cast or not.
  1282. bool shouldCast = false;
  1283. bool typeIsSigned = false;
  1284. // Based on the Opcode for which this Constant is being written, determine
  1285. // the new type to which the operand should be casted by setting the value
  1286. // of OpTy. If we change OpTy, also set shouldCast to true so it gets
  1287. // casted below.
  1288. switch (Opcode) {
  1289. default:
  1290. // for most instructions, it doesn't matter
  1291. break;
  1292. case Instruction::Add:
  1293. case Instruction::Sub:
  1294. case Instruction::Mul:
  1295. // We need to cast integer arithmetic so that it is always performed
  1296. // as unsigned, to avoid undefined behavior on overflow.
  1297. case Instruction::LShr:
  1298. case Instruction::UDiv:
  1299. case Instruction::URem:
  1300. shouldCast = true;
  1301. break;
  1302. case Instruction::AShr:
  1303. case Instruction::SDiv:
  1304. case Instruction::SRem:
  1305. shouldCast = true;
  1306. typeIsSigned = true;
  1307. break;
  1308. }
  1309. // Write out the casted constant if we should, otherwise just write the
  1310. // operand.
  1311. if (shouldCast) {
  1312. Out << "((";
  1313. printSimpleType(Out, OpTy, typeIsSigned);
  1314. Out << ")";
  1315. printConstant(CPV, false);
  1316. Out << ")";
  1317. } else
  1318. printConstant(CPV, false);
  1319. }
  1320. std::string CWriter::GetValueName(const Value *Operand) {
  1321. // Mangle globals with the standard mangler interface for LLC compatibility.
  1322. if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
  1323. return Mang->getMangledName(GV);
  1324. std::string Name = Operand->getName();
  1325. if (Name.empty()) { // Assign unique names to local temporaries.
  1326. unsigned &No = AnonValueNumbers[Operand];
  1327. if (No == 0)
  1328. No = ++NextAnonValueNumber;
  1329. Name = "tmp__" + utostr(No);
  1330. }
  1331. std::string VarName;
  1332. VarName.reserve(Name.capacity());
  1333. for (std::string::iterator I = Name.begin(), E = Name.end();
  1334. I != E; ++I) {
  1335. char ch = *I;
  1336. if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
  1337. (ch >= '0' && ch <= '9') || ch == '_')) {
  1338. char buffer[5];
  1339. sprintf(buffer, "_%x_", ch);
  1340. VarName += buffer;
  1341. } else
  1342. VarName += ch;
  1343. }
  1344. return "llvm_cbe_" + VarName;
  1345. }
  1346. /// writeInstComputationInline - Emit the computation for the specified
  1347. /// instruction inline, with no destination provided.
  1348. void CWriter::writeInstComputationInline(Instruction &I) {
  1349. // We can't currently support integer types other than 1, 8, 16, 32, 64.
  1350. // Validate this.
  1351. const Type *Ty = I.getType();
  1352. if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
  1353. Ty!=Type::getInt8Ty(I.getContext()) &&
  1354. Ty!=Type::getInt16Ty(I.getContext()) &&
  1355. Ty!=Type::getInt32Ty(I.getContext()) &&
  1356. Ty!=Type::getInt64Ty(I.getContext()))) {
  1357. llvm_report_error("The C backend does not currently support integer "
  1358. "types of widths other than 1, 8, 16, 32, 64.\n"
  1359. "This is being tracked as PR 4158.");
  1360. }
  1361. // If this is a non-trivial bool computation, make sure to truncate down to
  1362. // a 1 bit value. This is important because we want "add i1 x, y" to return
  1363. // "0" when x and y are true, not "2" for example.
  1364. bool NeedBoolTrunc = false;
  1365. if (I.getType() == Type::getInt1Ty(I.getContext()) &&
  1366. !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
  1367. NeedBoolTrunc = true;
  1368. if (NeedBoolTrunc)
  1369. Out << "((";
  1370. visit(I);
  1371. if (NeedBoolTrunc)
  1372. Out << ")&1)";
  1373. }
  1374. void CWriter::writeOperandInternal(Value *Operand, bool Static) {
  1375. if (Instruction *I = dyn_cast<Instruction>(Operand))
  1376. // Should we inline this instruction to build a tree?
  1377. if (isInlinableInst(*I) && !isDirectAlloca(I)) {
  1378. Out << '(';
  1379. writeInstComputationInline(*I);
  1380. Out << ')';
  1381. return;
  1382. }
  1383. Constant* CPV = dyn_cast<Constant>(Operand);
  1384. if (CPV && !isa<GlobalValue>(CPV))
  1385. printConstant(CPV, Static);
  1386. else
  1387. Out << GetValueName(Operand);
  1388. }
  1389. void CWriter::writeOperand(Value *Operand, bool Static) {
  1390. bool isAddressImplicit = isAddressExposed(Operand);
  1391. if (isAddressImplicit)
  1392. Out << "(&"; // Global variables are referenced as their addresses by llvm
  1393. writeOperandInternal(Operand, Static);
  1394. if (isAddressImplicit)
  1395. Out << ')';
  1396. }
  1397. // Some instructions need to have their result value casted back to the
  1398. // original types because their operands were casted to the expected type.
  1399. // This function takes care of detecting that case and printing the cast
  1400. // for the Instruction.
  1401. bool CWriter::writeInstructionCast(const Instruction &I) {
  1402. const Type *Ty = I.getOperand(0)->getType();
  1403. switch (I.getOpcode()) {
  1404. case Instruction::Add:
  1405. case Instruction::Sub:
  1406. case Instruction::Mul:
  1407. // We need to cast integer arithmetic so that it is always performed
  1408. // as unsigned, to avoid undefined behavior on overflow.
  1409. case Instruction::LShr:
  1410. case Instruction::URem:
  1411. case Instruction::UDiv:
  1412. Out << "((";
  1413. printSimpleType(Out, Ty, false);
  1414. Out << ")(";
  1415. return true;
  1416. case Instruction::AShr:
  1417. case Instruction::SRem:
  1418. case Instruction::SDiv:
  1419. Out << "((";
  1420. printSimpleType(Out, Ty, true);
  1421. Out << ")(";
  1422. return true;
  1423. default: break;
  1424. }
  1425. return false;
  1426. }
  1427. // Write the operand with a cast to another type based on the Opcode being used.
  1428. // This will be used in cases where an instruction has specific type
  1429. // requirements (usually signedness) for its operands.
  1430. void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
  1431. // Extract the operand's type, we'll need it.
  1432. const Type* OpTy = Operand->getType();
  1433. // Indicate whether to do the cast or not.
  1434. bool shouldCast = false;
  1435. // Indicate whether the cast should be to a signed type or not.
  1436. bool castIsSigned = false;
  1437. // Based on the Opcode for which this Operand is being written, determine
  1438. // the new type to which the operand should be casted by setting the value
  1439. // of OpTy. If we change OpTy, also set shouldCast to true.
  1440. switch (Opcode) {
  1441. default:
  1442. // for most instructions, it doesn't matter
  1443. break;
  1444. case Instruction::Add:
  1445. case Instruction::Sub:
  1446. case Instruction::Mul:
  1447. // We need to cast integer arithmetic so that it is always performed
  1448. // as unsigned, to avoid undefined behavior on overflow.
  1449. case Instruction::LShr:
  1450. case Instruction::UDiv:
  1451. case Instruction::URem: // Cast to unsigned first
  1452. shouldCast = true;
  1453. castIsSigned = false;
  1454. break;
  1455. case Instruction::GetElementPtr:
  1456. case Instruction::AShr:
  1457. case Instruction::SDiv:
  1458. case Instruction::SRem: // Cast to signed first
  1459. shouldCast = true;
  1460. castIsSigned = true;
  1461. break;
  1462. }
  1463. // Write out the casted operand if we should, otherwise just write the
  1464. // operand.
  1465. if (shouldCast) {
  1466. Out << "((";
  1467. printSimpleType(Out, OpTy, castIsSigned);
  1468. Out << ")";
  1469. writeOperand(Operand);
  1470. Out << ")";
  1471. } else
  1472. writeOperand(Operand);
  1473. }
  1474. // Write the operand with a cast to another type based on the icmp predicate
  1475. // being used.
  1476. void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
  1477. // This has to do a cast to ensure the operand has the right signedness.
  1478. // Also, if the operand is a pointer, we make sure to cast to an integer when
  1479. // doing the comparison both for signedness and so that the C compiler doesn't
  1480. // optimize things like "p < NULL" to false (p may contain an integer value
  1481. // f.e.).
  1482. bool shouldCast = Cmp.isRelational();
  1483. // Write out the casted operand if we should, otherwise just write the
  1484. // operand.
  1485. if (!shouldCast) {
  1486. writeOperand(Operand);
  1487. return;
  1488. }
  1489. // Should this be a signed comparison? If so, convert to signed.
  1490. bool castIsSigned = Cmp.isSignedPredicate();
  1491. // If the operand was a pointer, convert to a large integer type.
  1492. const Type* OpTy = Operand->getType();
  1493. if (isa<PointerType>(OpTy))
  1494. OpTy = TD->getIntPtrType(Operand->getContext());
  1495. Out << "((";
  1496. printSimpleType(Out, OpTy, castIsSigned);
  1497. Out << ")";
  1498. writeOperand(Operand);
  1499. Out << ")";
  1500. }
  1501. // generateCompilerSpecificCode - This is where we add conditional compilation
  1502. // directives to cater to specific compilers as need be.
  1503. //
  1504. static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
  1505. const TargetData *TD) {
  1506. // Alloca is hard to get, and we don't want to include stdlib.h here.
  1507. Out << "/* get a declaration for alloca */\n"
  1508. << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
  1509. << "#define alloca(x) __builtin_alloca((x))\n"
  1510. << "#define _alloca(x) __builtin_alloca((x))\n"
  1511. << "#elif defined(__APPLE__)\n"
  1512. << "extern void *__builtin_alloca(unsigned long);\n"
  1513. << "#define alloca(x) __builtin_alloca(x)\n"
  1514. << "#define longjmp _longjmp\n"
  1515. << "#define setjmp _setjmp\n"
  1516. << "#elif defined(__sun__)\n"
  1517. << "#if defined(__sparcv9)\n"
  1518. << "extern void *__builtin_alloca(unsigned long);\n"
  1519. << "#else\n"
  1520. << "extern void *__builtin_alloca(unsigned int);\n"
  1521. << "#endif\n"
  1522. << "#define alloca(x) __builtin_alloca(x)\n"
  1523. << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
  1524. << "#define alloca(x) __builtin_alloca(x)\n"
  1525. << "#elif defined(_MSC_VER)\n"
  1526. << "#define inline _inline\n"
  1527. << "#define alloca(x) _alloca(x)\n"
  1528. << "#else\n"
  1529. << "#include <alloca.h>\n"
  1530. << "#endif\n\n";
  1531. // We output GCC specific attributes to preserve 'linkonce'ness on globals.
  1532. // If we aren't being compiled with GCC, just drop these attributes.
  1533. Out << "#ifndef __GNUC__ /* Can only support \"linkonce\" vars with GCC */\n"
  1534. << "#define __attribute__(X)\n"
  1535. << "#endif\n\n";
  1536. // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
  1537. Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
  1538. << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
  1539. << "#elif defined(__GNUC__)\n"
  1540. << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
  1541. << "#else\n"
  1542. << "#define __EXTERNAL_WEAK__\n"
  1543. << "#endif\n\n";
  1544. // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
  1545. Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
  1546. << "#define __ATTRIBUTE_WEAK__\n"
  1547. << "#elif defined(__GNUC__)\n"
  1548. << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
  1549. << "#else\n"
  1550. << "#define __ATTRIBUTE_WEAK__\n"
  1551. << "#endif\n\n";
  1552. // Add hidden visibility support. FIXME: APPLE_CC?
  1553. Out << "#if defined(__GNUC__)\n"
  1554. << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
  1555. << "#endif\n\n";
  1556. // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
  1557. // From the GCC documentation:
  1558. //
  1559. // double __builtin_nan (const char *str)
  1560. //
  1561. // This is an implementation of the ISO C99 function nan.
  1562. //
  1563. // Since ISO C99 defines this function in terms of strtod, which we do
  1564. // not implement, a description of the parsing is in order. The string is
  1565. // parsed as by strtol; that is, the base is recognized by leading 0 or
  1566. // 0x prefixes. The number parsed is placed in the significand such that
  1567. // the least significant bit of the number is at the least significant
  1568. // bit of the significand. The number is truncated to fit the significand
  1569. // field provided. The significand is forced to be a quiet NaN.
  1570. //
  1571. // This function, if given a string literal, is evaluated early enough
  1572. // that it is considered a compile-time constant.
  1573. //
  1574. // float __builtin_nanf (const char *str)
  1575. //
  1576. // Similar to __builtin_nan, except the return type is float.
  1577. //
  1578. // double __builtin_inf (void)
  1579. //
  1580. // Similar to __builtin_huge_val, except a warning is generated if the
  1581. // target floating-point format does not support infinities. This
  1582. // function is suitable for implementing the ISO C99 macro INFINITY.
  1583. //
  1584. // float __builtin_inff (void)
  1585. //
  1586. // Similar to __builtin_inf, except the return type is float.
  1587. Out << "#ifdef __GNUC__\n"
  1588. << "#define LLVM_NAN(NanStr) __builtin_nan(NanStr) /* Double */\n"
  1589. << "#define LLVM_NANF(NanStr) __builtin_nanf(NanStr) /* Float */\n"
  1590. << "#define LLVM_NANS(NanStr) __builtin_nans(NanStr) /* Double */\n"
  1591. << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
  1592. << "#define LLVM_INF __builtin_inf() /* Double */\n"
  1593. << "#define LLVM_INFF __builtin_inff() /* Float */\n"
  1594. << "#define LLVM_PREFETCH(addr,rw,locality) "
  1595. "__builtin_prefetch(addr,rw,locality)\n"
  1596. << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
  1597. << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
  1598. << "#define LLVM_ASM __asm__\n"
  1599. << "#else\n"
  1600. << "#define LLVM_NAN(NanStr) ((double)0.0) /* Double */\n"
  1601. << "#define LLVM_NANF(NanStr) 0.0F /* Float */\n"
  1602. << "#define LLVM_NANS(NanStr) ((double)0.0) /* Double */\n"
  1603. << "#define LLVM_NANSF(NanStr) 0.0F /* Float */\n"
  1604. << "#define LLVM_INF ((double)0.0) /* Double */\n"
  1605. << "#define LLVM_INFF 0.0F /* Float */\n"
  1606. << "#define LLVM_PREFETCH(addr,rw,locality) /* PREFETCH */\n"
  1607. << "#define __ATTRIBUTE_CTOR__\n"
  1608. << "#define __ATTRIBUTE_DTOR__\n"
  1609. << "#define LLVM_ASM(X)\n"
  1610. << "#endif\n\n";
  1611. Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
  1612. << "#define __builtin_stack_save() 0 /* not implemented */\n"
  1613. << "#define __builtin_stack_restore(X) /* noop */\n"
  1614. << "#endif\n\n";
  1615. // Output typedefs for 128-bit integers. If these are needed with a
  1616. // 32-bit target or with a C compiler that doesn't support mode(TI),
  1617. // more drastic measures will be needed.
  1618. Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
  1619. << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
  1620. << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
  1621. << "#endif\n\n";
  1622. // Output target-specific code that should be inserted into main.
  1623. Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
  1624. }
  1625. /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
  1626. /// the StaticTors set.
  1627. static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
  1628. ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
  1629. if (!InitList) return;
  1630. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  1631. if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
  1632. if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
  1633. if (CS->getOperand(1)->isNullValue())
  1634. return; // Found a null terminator, exit printing.
  1635. Constant *FP = CS->getOperand(1);
  1636. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
  1637. if (CE->isCast())
  1638. FP = CE->getOperand(0);
  1639. if (Function *F = dyn_cast<Function>(FP))
  1640. StaticTors.insert(F);
  1641. }
  1642. }
  1643. enum SpecialGlobalClass {
  1644. NotSpecial = 0,
  1645. GlobalCtors, GlobalDtors,
  1646. NotPrinted
  1647. };
  1648. /// getGlobalVariableClass - If this is a global that is specially recognized
  1649. /// by LLVM, return a code that indicates how we should handle it.
  1650. static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
  1651. // If this is a global ctors/dtors list, handle it now.
  1652. if (GV->hasAppendingLinkage() && GV->use_empty()) {
  1653. if (GV->getName() == "llvm.global_ctors")
  1654. return GlobalCtors;
  1655. else if (GV->getName() == "llvm.global_dtors")
  1656. return GlobalDtors;
  1657. }
  1658. // Otherwise, it it is other metadata, don't print it. This catches things
  1659. // like debug information.
  1660. if (GV->getSection() == "llvm.metadata")
  1661. return NotPrinted;
  1662. return NotSpecial;
  1663. }
  1664. // PrintEscapedString - Print each character of the specified string, escaping
  1665. // it if it is not printable or if it is an escape char.
  1666. static void PrintEscapedString(const char *Str, unsigned Length,
  1667. raw_ostream &Out) {
  1668. for (unsigned i = 0; i != Length; ++i) {
  1669. unsigned char C = Str[i];
  1670. if (isprint(C) && C != '\\' && C != '"')
  1671. Out << C;
  1672. else if (C == '\\')
  1673. Out << "\\\\";
  1674. else if (C == '\"')
  1675. Out << "\\\"";
  1676. else if (C == '\t')
  1677. Out << "\\t";
  1678. else
  1679. Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
  1680. }
  1681. }
  1682. // PrintEscapedString - Print each character of the specified string, escaping
  1683. // it if it is not printable or if it is an escape char.
  1684. static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
  1685. PrintEscapedString(Str.c_str(), Str.size(), Out);
  1686. }
  1687. bool CWriter::doInitialization(Module &M) {
  1688. FunctionPass::doInitialization(M);
  1689. // Initialize
  1690. TheModule = &M;
  1691. TD = new TargetData(&M);
  1692. IL = new IntrinsicLowering(*TD);
  1693. IL->AddPrototypes(M);
  1694. // Ensure that all structure types have names...
  1695. Mang = new Mangler(M);
  1696. Mang->markCharUnacceptable('.');
  1697. // Keep track of which functions are static ctors/dtors so they can have
  1698. // an attribute added to their prototypes.
  1699. std::set<Function*> StaticCtors, StaticDtors;
  1700. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1701. I != E; ++I) {
  1702. switch (getGlobalVariableClass(I)) {
  1703. default: break;
  1704. case GlobalCtors:
  1705. FindStaticTors(I, StaticCtors);
  1706. break;
  1707. case GlobalDtors:
  1708. FindStaticTors(I, StaticDtors);
  1709. break;
  1710. }
  1711. }
  1712. // get declaration for alloca
  1713. Out << "/* Provide Declarations */\n";
  1714. Out << "#include <stdarg.h>\n"; // Varargs support
  1715. Out << "#include <setjmp.h>\n"; // Unwind support
  1716. generateCompilerSpecificCode(Out, TD);
  1717. // Provide a definition for `bool' if not compiling with a C++ compiler.
  1718. Out << "\n"
  1719. << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
  1720. << "\n\n/* Support for floating point constants */\n"
  1721. << "typedef unsigned long long ConstantDoubleTy;\n"
  1722. << "typedef unsigned int ConstantFloatTy;\n"
  1723. << "typedef struct { unsigned long long f1; unsigned short f2; "
  1724. "unsigned short pad[3]; } ConstantFP80Ty;\n"
  1725. // This is used for both kinds of 128-bit long double; meaning differs.
  1726. << "typedef struct { unsigned long long f1; unsigned long long f2; }"
  1727. " ConstantFP128Ty;\n"
  1728. << "\n\n/* Global Declarations */\n";
  1729. // First output all the declarations for the program, because C requires
  1730. // Functions & globals to be declared before they are used.
  1731. //
  1732. if (!M.getModuleInlineAsm().empty()) {
  1733. Out << "/* Module asm statements */\n"
  1734. << "asm(";
  1735. // Split the string into lines, to make it easier to read the .ll file.
  1736. std::string Asm = M.getModuleInlineAsm();
  1737. size_t CurPos = 0;
  1738. size_t NewLine = Asm.find_first_of('\n', CurPos);
  1739. while (NewLine != std::string::npos) {
  1740. // We found a newline, print the portion of the asm string from the
  1741. // last newline up to this newline.
  1742. Out << "\"";
  1743. PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
  1744. Out);
  1745. Out << "\\n\"\n";
  1746. CurPos = NewLine+1;
  1747. NewLine = Asm.find_first_of('\n', CurPos);
  1748. }
  1749. Out << "\"";
  1750. PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
  1751. Out << "\");\n"
  1752. << "/* End Module asm statements */\n";
  1753. }
  1754. // Loop over the symbol table, emitting all named constants...
  1755. printModuleTypes(M.getTypeSymbolTable());
  1756. // Global variable declarations...
  1757. if (!M.global_empty()) {
  1758. Out << "\n/* External Global Variable Declarations */\n";
  1759. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1760. I != E; ++I) {
  1761. if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() ||
  1762. I->hasCommonLinkage())
  1763. Out << "extern ";
  1764. else if (I->hasDLLImportLinkage())
  1765. Out << "__declspec(dllimport) ";
  1766. else
  1767. continue; // Internal Global
  1768. // Thread Local Storage
  1769. if (I->isThreadLocal())
  1770. Out << "__thread ";
  1771. printType(Out, I->getType()->getElementType(), false, GetValueName(I));
  1772. if (I->hasExternalWeakLinkage())
  1773. Out << " __EXTERNAL_WEAK__";
  1774. Out << ";\n";
  1775. }
  1776. }
  1777. // Function declarations
  1778. Out << "\n/* Function Declarations */\n";
  1779. Out << "double fmod(double, double);\n"; // Support for FP rem
  1780. Out << "float fmodf(float, float);\n";
  1781. Out << "long double fmodl(long double, long double);\n";
  1782. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
  1783. // Don't print declarations for intrinsic functions.
  1784. if (!I->isIntrinsic() && I->getName() != "setjmp" &&
  1785. I->getName() != "longjmp" && I->getName() != "_setjmp") {
  1786. if (I->hasExternalWeakLinkage())
  1787. Out << "extern ";
  1788. printFunctionSignature(I, true);
  1789. if (I->hasWeakLinkage() || I->hasLinkOnceLinkage())
  1790. Out << " __ATTRIBUTE_WEAK__";
  1791. if (I->hasExternalWeakLinkage())
  1792. Out << " __EXTERNAL_WEAK__";
  1793. if (StaticCtors.count(I))
  1794. Out << " __ATTRIBUTE_CTOR__";
  1795. if (StaticDtors.count(I))
  1796. Out << " __ATTRIBUTE_DTOR__";
  1797. if (I->hasHiddenVisibility())
  1798. Out << " __HIDDEN__";
  1799. if (I->hasName() && I->getName()[0] == 1)
  1800. Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
  1801. Out << ";\n";
  1802. }
  1803. }
  1804. // Output the global variable declarations
  1805. if (!M.global_empty()) {
  1806. Out << "\n\n/* Global Variable Declarations */\n";
  1807. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1808. I != E; ++I)
  1809. if (!I->isDeclaration()) {
  1810. // Ignore special globals, such as debug info.
  1811. if (getGlobalVariableClass(I))
  1812. continue;
  1813. if (I->hasLocalLinkage())
  1814. Out << "static ";
  1815. else
  1816. Out << "extern ";
  1817. // Thread Local Storage
  1818. if (I->isThreadLocal())
  1819. Out << "__thread ";
  1820. printType(Out, I->getType()->getElementType(), false,
  1821. GetValueName(I));
  1822. if (I->hasLinkOnceLinkage())
  1823. Out << " __attribute__((common))";
  1824. else if (I->hasCommonLinkage()) // FIXME is this right?
  1825. Out << " __ATTRIBUTE_WEAK__";
  1826. else if (I->hasWeakLinkage())
  1827. Out << " __ATTRIBUTE_WEAK__";
  1828. else if (I->hasExternalWeakLinkage())
  1829. Out << " __EXTERNAL_WEAK__";
  1830. if (I->hasHiddenVisibility())
  1831. Out << " __HIDDEN__";
  1832. Out << ";\n";
  1833. }
  1834. }
  1835. // Output the global variable definitions and contents...
  1836. if (!M.global_empty()) {
  1837. Out << "\n\n/* Global Variable Definitions and Initialization */\n";
  1838. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  1839. I != E; ++I)
  1840. if (!I->isDeclaration()) {
  1841. // Ignore special globals, such as debug info.
  1842. if (getGlobalVariableClass(I))
  1843. continue;
  1844. if (I->hasLocalLinkage())
  1845. Out << "static ";
  1846. else if (I->hasDLLImportLinkage())
  1847. Out << "__declspec(dllimport) ";
  1848. else if (I->hasDLLExportLinkage())
  1849. Out << "__declspec(dllexport) ";
  1850. // Thread Local Storage
  1851. if (I->isThreadLocal())
  1852. Out << "__thread ";
  1853. printType(Out, I->getType()->getElementType(), false,
  1854. GetValueName(I));
  1855. if (I->hasLinkOnceLinkage())
  1856. Out << " __attribute__((common))";
  1857. else if (I->hasWeakLinkage())
  1858. Out << " __ATTRIBUTE_WEAK__";
  1859. else if (I->hasCommonLinkage())
  1860. Out << " __ATTRIBUTE_WEAK__";
  1861. if (I->hasHiddenVisibility())
  1862. Out << " __HIDDEN__";
  1863. // If the initializer is not null, emit the initializer. If it is null,
  1864. // we try to avoid emitting large amounts of zeros. The problem with
  1865. // this, however, occurs when the variable has weak linkage. In this
  1866. // case, the assembler will complain about the variable being both weak
  1867. // and common, so we disable this optimization.
  1868. // FIXME common linkage should avoid this problem.
  1869. if (!I->getInitializer()->isNullValue()) {
  1870. Out << " = " ;
  1871. writeOperand(I->getInitializer(), true);
  1872. } else if (I->hasWeakLinkage()) {
  1873. // We have to specify an initializer, but it doesn't have to be
  1874. // complete. If the value is an aggregate, print out { 0 }, and let
  1875. // the compiler figure out the rest of the zeros.
  1876. Out << " = " ;
  1877. if (isa<StructType>(I->getInitializer()->getType()) ||
  1878. isa<VectorType>(I->getInitializer()->getType())) {
  1879. Out << "{ 0 }";
  1880. } else if (isa<ArrayType>(I->getInitializer()->getType())) {
  1881. // As with structs and vectors, but with an extra set of braces
  1882. // because arrays are wrapped in structs.
  1883. Out << "{ { 0 } }";
  1884. } else {
  1885. // Just print it out normally.
  1886. writeOperand(I->getInitializer(), true);
  1887. }
  1888. }
  1889. Out << ";\n";
  1890. }
  1891. }
  1892. if (!M.empty())
  1893. Out << "\n\n/* Function Bodies */\n";
  1894. // Emit some helper functions for dealing with FCMP instruction's
  1895. // predicates
  1896. Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
  1897. Out << "return X == X && Y == Y; }\n";
  1898. Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
  1899. Out << "return X != X || Y != Y; }\n";
  1900. Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
  1901. Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
  1902. Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
  1903. Out << "return X != Y; }\n";
  1904. Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
  1905. Out << "return X < Y || llvm_fcmp_uno(X, Y); }\n";
  1906. Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
  1907. Out << "return X > Y || llvm_fcmp_uno(X, Y); }\n";
  1908. Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
  1909. Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
  1910. Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
  1911. Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
  1912. Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
  1913. Out << "return X == Y ; }\n";
  1914. Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
  1915. Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
  1916. Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
  1917. Out << "return X < Y ; }\n";
  1918. Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
  1919. Out << "return X > Y ; }\n";
  1920. Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
  1921. Out << "return X <= Y ; }\n";
  1922. Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
  1923. Out << "return X >= Y ; }\n";
  1924. return false;
  1925. }
  1926. /// Output all floating point constants that cannot be printed accurately...
  1927. void CWriter::printFloatingPointConstants(Function &F) {
  1928. // Scan the module for floating point constants. If any FP constant is used
  1929. // in the function, we want to redirect it here so that we do not depend on
  1930. // the precision of the printed form, unless the printed form preserves
  1931. // precision.
  1932. //
  1933. for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
  1934. I != E; ++I)
  1935. printFloatingPointConstants(*I);
  1936. Out << '\n';
  1937. }
  1938. void CWriter::printFloatingPointConstants(const Constant *C) {
  1939. // If this is a constant expression, recursively check for constant fp values.
  1940. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1941. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
  1942. printFloatingPointConstants(CE->getOperand(i));
  1943. return;
  1944. }
  1945. // Otherwise, check for a FP constant that we need to print.
  1946. const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
  1947. if (FPC == 0 ||
  1948. // Do not put in FPConstantMap if safe.
  1949. isFPCSafeToPrint(FPC) ||
  1950. // Already printed this constant?
  1951. FPConstantMap.count(FPC))
  1952. return;
  1953. FPConstantMap[FPC] = FPCounter; // Number the FP constants
  1954. if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
  1955. double Val = FPC->getValueAPF().convertToDouble();
  1956. uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
  1957. Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
  1958. << " = 0x" << utohexstr(i)
  1959. << "ULL; /* " << Val << " */\n";
  1960. } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
  1961. float Val = FPC->getValueAPF().convertToFloat();
  1962. uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
  1963. getZExtValue();
  1964. Out << "static const ConstantFloatTy FPConstant" << FPCounter++
  1965. << " = 0x" << utohexstr(i)
  1966. << "U; /* " << Val << " */\n";
  1967. } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
  1968. // api needed to prevent premature destruction
  1969. APInt api = FPC->getValueAPF().bitcastToAPInt();
  1970. const uint64_t *p = api.getRawData();
  1971. Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
  1972. << " = { 0x" << utohexstr(p[0])
  1973. << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
  1974. << "}; /* Long double constant */\n";
  1975. } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext())) {
  1976. APInt api = FPC->getValueAPF().bitcastToAPInt();
  1977. const uint64_t *p = api.getRawData();
  1978. Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
  1979. << " = { 0x"
  1980. << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
  1981. << "}; /* Long double constant */\n";
  1982. } else {
  1983. llvm_unreachable("Unknown float type!");
  1984. }
  1985. }
  1986. /// printSymbolTable - Run through symbol table looking for type names. If a
  1987. /// type name is found, emit its declaration...
  1988. ///
  1989. void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
  1990. Out << "/* Helper union for bitcasts */\n";
  1991. Out << "typedef union {\n";
  1992. Out << " unsigned int Int32;\n";
  1993. Out << " unsigned long long Int64;\n";
  1994. Out << " float Float;\n";
  1995. Out << " double Double;\n";
  1996. Out << "} llvmBitCastUnion;\n";
  1997. // We are only interested in the type plane of the symbol table.
  1998. TypeSymbolTable::const_iterator I = TST.begin();
  1999. TypeSymbolTable::const_iterator End = TST.end();
  2000. // If there are no type names, exit early.
  2001. if (I == End) return;
  2002. // Print out forward declarations for structure types before anything else!
  2003. Out << "/* Structure forward decls */\n";
  2004. for (; I != End; ++I) {
  2005. std::string Name = "struct l_" + Mang->makeNameProper(I->first);
  2006. Out << Name << ";\n";
  2007. TypeNames.insert(std::make_pair(I->second, Name));
  2008. }
  2009. Out << '\n';
  2010. // Now we can print out typedefs. Above, we guaranteed that this can only be
  2011. // for struct or opaque types.
  2012. Out << "/* Typedefs */\n";
  2013. for (I = TST.begin(); I != End; ++I) {
  2014. std::string Name = "l_" + Mang->makeNameProper(I->first);
  2015. Out << "typedef ";
  2016. printType(Out, I->second, false, Name);
  2017. Out << ";\n";
  2018. }
  2019. Out << '\n';
  2020. // Keep track of which structures have been printed so far...
  2021. std::set<const Type *> StructPrinted;
  2022. // Loop over all structures then push them into the stack so they are
  2023. // printed in the correct order.
  2024. //
  2025. Out << "/* Structure contents */\n";
  2026. for (I = TST.begin(); I != End; ++I)
  2027. if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
  2028. // Only print out used types!
  2029. printContainedStructs(I->second, StructPrinted);
  2030. }
  2031. // Push the struct onto the stack and recursively push all structs
  2032. // this one depends on.
  2033. //
  2034. // TODO: Make this work properly with vector types
  2035. //
  2036. void CWriter::printContainedStructs(const Type *Ty,
  2037. std::set<const Type*> &StructPrinted) {
  2038. // Don't walk through pointers.
  2039. if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
  2040. // Print all contained types first.
  2041. for (Type::subtype_iterator I = Ty->subtype_begin(),
  2042. E = Ty->subtype_end(); I != E; ++I)
  2043. printContainedStructs(*I, StructPrinted);
  2044. if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
  2045. // Check to see if we have already printed this struct.
  2046. if (StructPrinted.insert(Ty).second) {
  2047. // Print structure type out.
  2048. std::string Name = TypeNames[Ty];
  2049. printType(Out, Ty, false, Name, true);
  2050. Out << ";\n\n";
  2051. }
  2052. }
  2053. }
  2054. void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
  2055. /// isStructReturn - Should this function actually return a struct by-value?
  2056. bool isStructReturn = F->hasStructRetAttr();
  2057. if (F->hasLocalLinkage()) Out << "static ";
  2058. if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
  2059. if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";
  2060. switch (F->getCallingConv()) {
  2061. case CallingConv::X86_StdCall:
  2062. Out << "__attribute__((stdcall)) ";
  2063. break;
  2064. case CallingConv::X86_FastCall:
  2065. Out << "__attribute__((fastcall)) ";
  2066. break;
  2067. }
  2068. // Loop over the arguments, printing them...
  2069. const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
  2070. const AttrListPtr &PAL = F->getAttributes();
  2071. std::stringstream FunctionInnards;
  2072. // Print out the name...
  2073. FunctionInnards << GetValueName(F) << '(';
  2074. bool PrintedArg = false;
  2075. if (!F->isDeclaration()) {
  2076. if (!F->arg_empty()) {
  2077. Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
  2078. unsigned Idx = 1;
  2079. // If this is a struct-return function, don't print the hidden
  2080. // struct-return argument.
  2081. if (isStructReturn) {
  2082. assert(I != E && "Invalid struct return function!");
  2083. ++I;
  2084. ++Idx;
  2085. }
  2086. std::string ArgName;
  2087. for (; I != E; ++I) {
  2088. if (PrintedArg) FunctionInnards << ", ";
  2089. if (I->hasName() || !Prototype)
  2090. ArgName = GetValueName(I);
  2091. else
  2092. ArgName = "";
  2093. const Type *ArgTy = I->getType();
  2094. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  2095. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  2096. ByValParams.insert(I);
  2097. }
  2098. printType(FunctionInnards, ArgTy,
  2099. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
  2100. ArgName);
  2101. PrintedArg = true;
  2102. ++Idx;
  2103. }
  2104. }
  2105. } else {
  2106. // Loop over the arguments, printing them.
  2107. FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
  2108. unsigned Idx = 1;
  2109. // If this is a struct-return function, don't print the hidden
  2110. // struct-return argument.
  2111. if (isStructReturn) {
  2112. assert(I != E && "Invalid struct return function!");
  2113. ++I;
  2114. ++Idx;
  2115. }
  2116. for (; I != E; ++I) {
  2117. if (PrintedArg) FunctionInnards << ", ";
  2118. const Type *ArgTy = *I;
  2119. if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
  2120. assert(isa<PointerType>(ArgTy));
  2121. ArgTy = cast<PointerType>(ArgTy)->getElementType();
  2122. }
  2123. printType(FunctionInnards, ArgTy,
  2124. /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
  2125. PrintedArg = true;
  2126. ++Idx;
  2127. }
  2128. }
  2129. // Finish printing arguments... if this is a vararg function, print the ...,
  2130. // unless there are no known types, in which case, we just emit ().
  2131. //
  2132. if (FT->isVarArg() && PrintedArg) {
  2133. if (PrintedArg) FunctionInnards << ", ";
  2134. FunctionInnards << "..."; // Output varargs portion of signature!
  2135. } else if (!FT->isVarArg() && !PrintedArg) {
  2136. FunctionInnards << "void"; // ret() -> ret(void) in C.
  2137. }
  2138. FunctionInnards << ')';
  2139. // Get the return tpe for the function.
  2140. const Type *RetTy;
  2141. if (!isStructReturn)
  2142. RetTy = F->getReturnType();
  2143. else {
  2144. // If this is a struct-return function, print the struct-return type.
  2145. RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
  2146. }
  2147. // Print out the return type and the signature built above.
  2148. printType(Out, RetTy,
  2149. /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
  2150. FunctionInnards.str());
  2151. }
  2152. static inline bool isFPIntBitCast(const Instruction &I) {
  2153. if (!isa<BitCastInst>(I))
  2154. return false;
  2155. const Type *SrcTy = I.getOperand(0)->getType();
  2156. const Type *DstTy = I.getType();
  2157. return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
  2158. (DstTy->isFloatingPoint() && SrcTy->isInteger());
  2159. }
  2160. void CWriter::printFunction(Function &F) {
  2161. /// isStructReturn - Should this function actually return a struct by-value?
  2162. bool isStructReturn = F.hasStructRetAttr();
  2163. printFunctionSignature(&F, false);
  2164. Out << " {\n";
  2165. // If this is a struct return function, handle the result with magic.
  2166. if (isStructReturn) {
  2167. const Type *StructTy =
  2168. cast<PointerType>(F.arg_begin()->getType())->getElementType();
  2169. Out << " ";
  2170. printType(Out, StructTy, false, "StructReturn");
  2171. Out << "; /* Struct return temporary */\n";
  2172. Out << " ";
  2173. printType(Out, F.arg_begin()->getType(), false,
  2174. GetValueName(F.arg_begin()));
  2175. Out << " = &StructReturn;\n";
  2176. }
  2177. bool PrintedVar = false;
  2178. // print local variable information for the function
  2179. for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
  2180. if (const AllocaInst *AI = isDirectAlloca(&*I)) {
  2181. Out << " ";
  2182. printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
  2183. Out << "; /* Address-exposed local */\n";
  2184. PrintedVar = true;
  2185. } else if (I->getType() != Type::getVoidTy(F.getContext()) &&
  2186. !isInlinableInst(*I)) {
  2187. Out << " ";
  2188. printType(Out, I->getType(), false, GetValueName(&*I));
  2189. Out << ";\n";
  2190. if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
  2191. Out << " ";
  2192. printType(Out, I->getType(), false,
  2193. GetValueName(&*I)+"__PHI_TEMPORARY");
  2194. Out << ";\n";
  2195. }
  2196. PrintedVar = true;
  2197. }
  2198. // We need a temporary for the BitCast to use so it can pluck a value out
  2199. // of a union to do the BitCast. This is separate from the need for a
  2200. // variable to hold the result of the BitCast.
  2201. if (isFPIntBitCast(*I)) {
  2202. Out << " llvmBitCastUnion " << GetValueName(&*I)
  2203. << "__BITCAST_TEMPORARY;\n";
  2204. PrintedVar = true;
  2205. }
  2206. }
  2207. if (PrintedVar)
  2208. Out << '\n';
  2209. if (F.hasExternalLinkage() && F.getName() == "main")
  2210. Out << " CODE_FOR_MAIN();\n";
  2211. // print the basic blocks
  2212. for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
  2213. if (Loop *L = LI->getLoopFor(BB)) {
  2214. if (L->getHeader() == BB && L->getParentLoop() == 0)
  2215. printLoop(L);
  2216. } else {
  2217. printBasicBlock(BB);
  2218. }
  2219. }
  2220. Out << "}\n\n";
  2221. }
  2222. void CWriter::printLoop(Loop *L) {
  2223. Out << " do { /* Syntactic loop '" << L->getHeader()->getName()
  2224. << "' to make GCC happy */\n";
  2225. for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
  2226. BasicBlock *BB = L->getBlocks()[i];
  2227. Loop *BBLoop = LI->getLoopFor(BB);
  2228. if (BBLoop == L)
  2229. printBasicBlock(BB);
  2230. else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
  2231. printLoop(BBLoop);
  2232. }
  2233. Out << " } while (1); /* end of syntactic loop '"
  2234. << L->getHeader()->getName() << "' */\n";
  2235. }
  2236. void CWriter::printBasicBlock(BasicBlock *BB) {
  2237. // Don't print the label for the basic block if there are no uses, or if
  2238. // the only terminator use is the predecessor basic block's terminator.
  2239. // We have to scan the use list because PHI nodes use basic blocks too but
  2240. // do not require a label to be generated.
  2241. //
  2242. bool NeedsLabel = false;
  2243. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  2244. if (isGotoCodeNecessary(*PI, BB)) {
  2245. NeedsLabel = true;
  2246. break;
  2247. }
  2248. if (NeedsLabel) Out << GetValueName(BB) << ":\n";
  2249. // Output all of the instructions in the basic block...
  2250. for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
  2251. ++II) {
  2252. if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
  2253. if (II->getType() != Type::getVoidTy(BB->getContext()) &&
  2254. !isInlineAsm(*II))
  2255. outputLValue(II);
  2256. else
  2257. Out << " ";
  2258. writeInstComputationInline(*II);
  2259. Out << ";\n";
  2260. }
  2261. }
  2262. // Don't emit prefix or suffix for the terminator.
  2263. visit(*BB->getTerminator());
  2264. }
  2265. // Specific Instruction type classes... note that all of the casts are
  2266. // necessary because we use the instruction classes as opaque types...
  2267. //
  2268. void CWriter::visitReturnInst(ReturnInst &I) {
  2269. // If this is a struct return function, return the temporary struct.
  2270. bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
  2271. if (isStructReturn) {
  2272. Out << " return StructReturn;\n";
  2273. return;
  2274. }
  2275. // Don't output a void return if this is the last basic block in the function
  2276. if (I.getNumOperands() == 0 &&
  2277. &*--I.getParent()->getParent()->end() == I.getParent() &&
  2278. !I.getParent()->size() == 1) {
  2279. return;
  2280. }
  2281. if (I.getNumOperands() > 1) {
  2282. Out << " {\n";
  2283. Out << " ";
  2284. printType(Out, I.getParent()->getParent()->getReturnType());
  2285. Out << " llvm_cbe_mrv_temp = {\n";
  2286. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
  2287. Out << " ";
  2288. writeOperand(I.getOperand(i));
  2289. if (i != e - 1)
  2290. Out << ",";
  2291. Out << "\n";
  2292. }
  2293. Out << " };\n";
  2294. Out << " return llvm_cbe_mrv_temp;\n";
  2295. Out << " }\n";
  2296. return;
  2297. }
  2298. Out << " return";
  2299. if (I.getNumOperands()) {
  2300. Out << ' ';
  2301. writeOperand(I.getOperand(0));
  2302. }
  2303. Out << ";\n";
  2304. }
  2305. void CWriter::visitSwitchInst(SwitchInst &SI) {
  2306. Out << " switch (";
  2307. writeOperand(SI.getOperand(0));
  2308. Out << ") {\n default:\n";
  2309. printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
  2310. printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
  2311. Out << ";\n";
  2312. for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
  2313. Out << " case ";
  2314. writeOperand(SI.getOperand(i));
  2315. Out << ":\n";
  2316. BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
  2317. printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
  2318. printBranchToBlock(SI.getParent(), Succ, 2);
  2319. if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
  2320. Out << " break;\n";
  2321. }
  2322. Out << " }\n";
  2323. }
  2324. void CWriter::visitUnreachableInst(UnreachableInst &I) {
  2325. Out << " /*UNREACHABLE*/;\n";
  2326. }
  2327. bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
  2328. /// FIXME: This should be reenabled, but loop reordering safe!!
  2329. return true;
  2330. if (next(Function::iterator(From)) != Function::iterator(To))
  2331. return true; // Not the direct successor, we need a goto.
  2332. //isa<SwitchInst>(From->getTerminator())
  2333. if (LI->getLoopFor(From) != LI->getLoopFor(To))
  2334. return true;
  2335. return false;
  2336. }
  2337. void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
  2338. BasicBlock *Successor,
  2339. unsigned Indent) {
  2340. for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
  2341. PHINode *PN = cast<PHINode>(I);
  2342. // Now we have to do the printing.
  2343. Value *IV = PN->getIncomingValueForBlock(CurBlock);
  2344. if (!isa<UndefValue>(IV)) {
  2345. Out << std::string(Indent, ' ');
  2346. Out << " " << GetValueName(I) << "__PHI_TEMPORARY = ";
  2347. writeOperand(IV);
  2348. Out << "; /* for PHI node */\n";
  2349. }
  2350. }
  2351. }
  2352. void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
  2353. unsigned Indent) {
  2354. if (isGotoCodeNecessary(CurBB, Succ)) {
  2355. Out << std::string(Indent, ' ') << " goto ";
  2356. writeOperand(Succ);
  2357. Out << ";\n";
  2358. }
  2359. }
  2360. // Branch instruction printing - Avoid printing out a branch to a basic block
  2361. // that immediately succeeds the current one.
  2362. //
  2363. void CWriter::visitBranchInst(BranchInst &I) {
  2364. if (I.isConditional()) {
  2365. if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
  2366. Out << " if (";
  2367. writeOperand(I.getCondition());
  2368. Out << ") {\n";
  2369. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
  2370. printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
  2371. if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
  2372. Out << " } else {\n";
  2373. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
  2374. printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
  2375. }
  2376. } else {
  2377. // First goto not necessary, assume second one is...
  2378. Out << " if (!";
  2379. writeOperand(I.getCondition());
  2380. Out << ") {\n";
  2381. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
  2382. printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
  2383. }
  2384. Out << " }\n";
  2385. } else {
  2386. printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
  2387. printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
  2388. }
  2389. Out << "\n";
  2390. }
  2391. // PHI nodes get copied into temporary values at the end of predecessor basic
  2392. // blocks. We now need to copy these temporary values into the REAL value for
  2393. // the PHI.
  2394. void CWriter::visitPHINode(PHINode &I) {
  2395. writeOperand(&I);
  2396. Out << "__PHI_TEMPORARY";
  2397. }
  2398. void CWriter::visitBinaryOperator(Instruction &I) {
  2399. // binary instructions, shift instructions, setCond instructions.
  2400. assert(!isa<PointerType>(I.getType()));
  2401. // We must cast the results of binary operations which might be promoted.
  2402. bool needsCast = false;
  2403. if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
  2404. (I.getType() == Type::getInt16Ty(I.getContext()))
  2405. || (I.getType() == Type::getFloatTy(I.getContext()))) {
  2406. needsCast = true;
  2407. Out << "((";
  2408. printType(Out, I.getType(), false);
  2409. Out << ")(";
  2410. }
  2411. // If this is a negation operation, print it out as such. For FP, we don't
  2412. // want to print "-0.0 - X".
  2413. if (BinaryOperator::isNeg(&I)) {
  2414. Out << "-(";
  2415. writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
  2416. Out << ")";
  2417. } else if (BinaryOperator::isFNeg(&I)) {
  2418. Out << "-(";
  2419. writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
  2420. Out << ")";
  2421. } else if (I.getOpcode() == Instruction::FRem) {
  2422. // Output a call to fmod/fmodf instead of emitting a%b
  2423. if (I.getType() == Type::getFloatTy(I.getContext()))
  2424. Out << "fmodf(";
  2425. else if (I.getType() == Type::getDoubleTy(I.getContext()))
  2426. Out << "fmod(";
  2427. else // all 3 flavors of long double
  2428. Out << "fmodl(";
  2429. writeOperand(I.getOperand(0));
  2430. Out << ", ";
  2431. writeOperand(I.getOperand(1));
  2432. Out << ")";
  2433. } else {
  2434. // Write out the cast of the instruction's value back to the proper type
  2435. // if necessary.
  2436. bool NeedsClosingParens = writeInstructionCast(I);
  2437. // Certain instructions require the operand to be forced to a specific type
  2438. // so we use writeOperandWithCast here instead of writeOperand. Similarly
  2439. // below for operand 1
  2440. writeOperandWithCast(I.getOperand(0), I.getOpcode());
  2441. switch (I.getOpcode()) {
  2442. case Instruction::Add:
  2443. case Instruction::FAdd: Out << " + "; break;
  2444. case Instruction::Sub:
  2445. case Instruction::FSub: Out << " - "; break;
  2446. case Instruction::Mul:
  2447. case Instruction::FMul: Out << " * "; break;
  2448. case Instruction::URem:
  2449. case Instruction::SRem:
  2450. case Instruction::FRem: Out << " % "; break;
  2451. case Instruction::UDiv:
  2452. case Instruction::SDiv:
  2453. case Instruction::FDiv: Out << " / "; break;
  2454. case Instruction::And: Out << " & "; break;
  2455. case Instruction::Or: Out << " | "; break;
  2456. case Instruction::Xor: Out << " ^ "; break;
  2457. case Instruction::Shl : Out << " << "; break;
  2458. case Instruction::LShr:
  2459. case Instruction::AShr: Out << " >> "; break;
  2460. default:
  2461. #ifndef NDEBUG
  2462. cerr << "Invalid operator type!" << I;
  2463. #endif
  2464. llvm_unreachable(0);
  2465. }
  2466. writeOperandWithCast(I.getOperand(1), I.getOpcode());
  2467. if (NeedsClosingParens)
  2468. Out << "))";
  2469. }
  2470. if (needsCast) {
  2471. Out << "))";
  2472. }
  2473. }
  2474. void CWriter::visitICmpInst(ICmpInst &I) {
  2475. // We must cast the results of icmp which might be promoted.
  2476. bool needsCast = false;
  2477. // Write out the cast of the instruction's value back to the proper type
  2478. // if necessary.
  2479. bool NeedsClosingParens = writeInstructionCast(I);
  2480. // Certain icmp predicate require the operand to be forced to a specific type
  2481. // so we use writeOperandWithCast here instead of writeOperand. Similarly
  2482. // below for operand 1
  2483. writeOperandWithCast(I.getOperand(0), I);
  2484. switch (I.getPredicate()) {
  2485. case ICmpInst::ICMP_EQ: Out << " == "; break;
  2486. case ICmpInst::ICMP_NE: Out << " != "; break;
  2487. case ICmpInst::ICMP_ULE:
  2488. case ICmpInst::ICMP_SLE: Out << " <= "; break;
  2489. case ICmpInst::ICMP_UGE:
  2490. case ICmpInst::ICMP_SGE: Out << " >= "; break;
  2491. case ICmpInst::ICMP_ULT:
  2492. case ICmpInst::ICMP_SLT: Out << " < "; break;
  2493. case ICmpInst::ICMP_UGT:
  2494. case ICmpInst::ICMP_SGT: Out << " > "; break;
  2495. default:
  2496. #ifndef NDEBUG
  2497. cerr << "Invalid icmp predicate!" << I;
  2498. #endif
  2499. llvm_unreachable(0);
  2500. }
  2501. writeOperandWithCast(I.getOperand(1), I);
  2502. if (NeedsClosingParens)
  2503. Out << "))";
  2504. if (needsCast) {
  2505. Out << "))";
  2506. }
  2507. }
  2508. void CWriter::visitFCmpInst(FCmpInst &I) {
  2509. if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
  2510. Out << "0";
  2511. return;
  2512. }
  2513. if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
  2514. Out << "1";
  2515. return;
  2516. }
  2517. const char* op = 0;
  2518. switch (I.getPredicate()) {
  2519. default: llvm_unreachable("Illegal FCmp predicate");
  2520. case FCmpInst::FCMP_ORD: op = "ord"; break;
  2521. case FCmpInst::FCMP_UNO: op = "uno"; break;
  2522. case FCmpInst::FCMP_UEQ: op = "ueq"; break;
  2523. case FCmpInst::FCMP_UNE: op = "une"; break;
  2524. case FCmpInst::FCMP_ULT: op = "ult"; break;
  2525. case FCmpInst::FCMP_ULE: op = "ule"; break;
  2526. case FCmpInst::FCMP_UGT: op = "ugt"; break;
  2527. case FCmpInst::FCMP_UGE: op = "uge"; break;
  2528. case FCmpInst::FCMP_OEQ: op = "oeq"; break;
  2529. case FCmpInst::FCMP_ONE: op = "one"; break;
  2530. case FCmpInst::FCMP_OLT: op = "olt"; break;
  2531. case FCmpInst::FCMP_OLE: op = "ole"; break;
  2532. case FCmpInst::FCMP_OGT: op = "ogt"; break;
  2533. case FCmpInst::FCMP_OGE: op = "oge"; break;
  2534. }
  2535. Out << "llvm_fcmp_" << op << "(";
  2536. // Write the first operand
  2537. writeOperand(I.getOperand(0));
  2538. Out << ", ";
  2539. // Write the second operand
  2540. writeOperand(I.getOperand(1));
  2541. Out << ")";
  2542. }
  2543. static const char * getFloatBitCastField(const Type *Ty) {
  2544. switch (Ty->getTypeID()) {
  2545. default: llvm_unreachable("Invalid Type");
  2546. case Type::FloatTyID: return "Float";
  2547. case Type::DoubleTyID: return "Double";
  2548. case Type::IntegerTyID: {
  2549. unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
  2550. if (NumBits <= 32)
  2551. return "Int32";
  2552. else
  2553. return "Int64";
  2554. }
  2555. }
  2556. }
  2557. void CWriter::visitCastInst(CastInst &I) {
  2558. const Type *DstTy = I.getType();
  2559. const Type *SrcTy = I.getOperand(0)->getType();
  2560. if (isFPIntBitCast(I)) {
  2561. Out << '(';
  2562. // These int<->float and long<->double casts need to be handled specially
  2563. Out << GetValueName(&I) << "__BITCAST_TEMPORARY."
  2564. << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
  2565. writeOperand(I.getOperand(0));
  2566. Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
  2567. << getFloatBitCastField(I.getType());
  2568. Out << ')';
  2569. return;
  2570. }
  2571. Out << '(';
  2572. printCast(I.getOpcode(), SrcTy, DstTy);
  2573. // Make a sext from i1 work by subtracting the i1 from 0 (an int).
  2574. if (SrcTy == Type::getInt1Ty(I.getContext()) &&
  2575. I.getOpcode() == Instruction::SExt)
  2576. Out << "0-";
  2577. writeOperand(I.getOperand(0));
  2578. if (DstTy == Type::getInt1Ty(I.getContext()) &&
  2579. (I.getOpcode() == Instruction::Trunc ||
  2580. I.getOpcode() == Instruction::FPToUI ||
  2581. I.getOpcode() == Instruction::FPToSI ||
  2582. I.getOpcode() == Instruction::PtrToInt)) {
  2583. // Make sure we really get a trunc to bool by anding the operand with 1
  2584. Out << "&1u";
  2585. }
  2586. Out << ')';
  2587. }
  2588. void CWriter::visitSelectInst(SelectInst &I) {
  2589. Out << "((";
  2590. writeOperand(I.getCondition());
  2591. Out << ") ? (";
  2592. writeOperand(I.getTrueValue());
  2593. Out << ") : (";
  2594. writeOperand(I.getFalseValue());
  2595. Out << "))";
  2596. }
  2597. void CWriter::lowerIntrinsics(Function &F) {
  2598. // This is used to keep track of intrinsics that get generated to a lowered
  2599. // function. We must generate the prototypes before the function body which
  2600. // will only be expanded on first use (by the loop below).
  2601. std::vector<Function*> prototypesToGen;
  2602. // Examine all the instructions in this function to find the intrinsics that
  2603. // need to be lowered.
  2604. for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
  2605. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
  2606. if (CallInst *CI = dyn_cast<CallInst>(I++))
  2607. if (Function *F = CI->getCalledFunction())
  2608. switch (F->getIntrinsicID()) {
  2609. case Intrinsic::not_intrinsic:
  2610. case Intrinsic::memory_barrier:
  2611. case Intrinsic::vastart:
  2612. case Intrinsic::vacopy:
  2613. case Intrinsic::vaend:
  2614. case Intrinsic::returnaddress:
  2615. case Intrinsic::frameaddress:
  2616. case Intrinsic::setjmp:
  2617. case Intrinsic::longjmp:
  2618. case Intrinsic::prefetch:
  2619. case Intrinsic::dbg_stoppoint:
  2620. case Intrinsic::powi:
  2621. case Intrinsic::x86_sse_cmp_ss:
  2622. case Intrinsic::x86_sse_cmp_ps:
  2623. case Intrinsic::x86_sse2_cmp_sd:
  2624. case Intrinsic::x86_sse2_cmp_pd:
  2625. case Intrinsic::ppc_altivec_lvsl:
  2626. // We directly implement these intrinsics
  2627. break;
  2628. default:
  2629. // If this is an intrinsic that directly corresponds to a GCC
  2630. // builtin, we handle it.
  2631. const char *BuiltinName = "";
  2632. #define GET_GCC_BUILTIN_NAME
  2633. #include "llvm/Intrinsics.gen"
  2634. #undef GET_GCC_BUILTIN_NAME
  2635. // If we handle it, don't lower it.
  2636. if (BuiltinName[0]) break;
  2637. // All other intrinsic calls we must lower.
  2638. Instruction *Before = 0;
  2639. if (CI != &BB->front())
  2640. Before = prior(BasicBlock::iterator(CI));
  2641. IL->LowerIntrinsicCall(CI);
  2642. if (Before) { // Move iterator to instruction after call
  2643. I = Before; ++I;
  2644. } else {
  2645. I = BB->begin();
  2646. }
  2647. // If the intrinsic got lowered to another call, and that call has
  2648. // a definition then we need to make sure its prototype is emitted
  2649. // before any calls to it.
  2650. if (CallInst *Call = dyn_cast<CallInst>(I))
  2651. if (Function *NewF = Call->getCalledFunction())
  2652. if (!NewF->isDeclaration())
  2653. prototypesToGen.push_back(NewF);
  2654. break;
  2655. }
  2656. // We may have collected some prototypes to emit in the loop above.
  2657. // Emit them now, before the function that uses them is emitted. But,
  2658. // be careful not to emit them twice.
  2659. std::vector<Function*>::iterator I = prototypesToGen.begin();
  2660. std::vector<Function*>::iterator E = prototypesToGen.end();
  2661. for ( ; I != E; ++I) {
  2662. if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
  2663. Out << '\n';
  2664. printFunctionSignature(*I, true);
  2665. Out << ";\n";
  2666. }
  2667. }
  2668. }
  2669. void CWriter::visitCallInst(CallInst &I) {
  2670. if (isa<InlineAsm>(I.getOperand(0)))
  2671. return visitInlineAsm(I);
  2672. bool WroteCallee = false;
  2673. // Handle intrinsic function calls first...
  2674. if (Function *F = I.getCalledFunction())
  2675. if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
  2676. if (visitBuiltinCall(I, ID, WroteCallee))
  2677. return;
  2678. Value *Callee = I.getCalledValue();
  2679. const PointerType *PTy = cast<PointerType>(Callee->getType());
  2680. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  2681. // If this is a call to a struct-return function, assign to the first
  2682. // parameter instead of passing it to the call.
  2683. const AttrListPtr &PAL = I.getAttributes();
  2684. bool hasByVal = I.hasByValArgument();
  2685. bool isStructRet = I.hasStructRetAttr();
  2686. if (isStructRet) {
  2687. writeOperandDeref(I.getOperand(1));
  2688. Out << " = ";
  2689. }
  2690. if (I.isTailCall()) Out << " /*tail*/ ";
  2691. if (!WroteCallee) {
  2692. // If this is an indirect call to a struct return function, we need to cast
  2693. // the pointer. Ditto for indirect calls with byval arguments.
  2694. bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
  2695. // GCC is a real PITA. It does not permit codegening casts of functions to
  2696. // function pointers if they are in a call (it generates a trap instruction
  2697. // instead!). We work around this by inserting a cast to void* in between
  2698. // the function and the function pointer cast. Unfortunately, we can't just
  2699. // form the constant expression here, because the folder will immediately
  2700. // nuke it.
  2701. //
  2702. // Note finally, that this is completely unsafe. ANSI C does not guarantee
  2703. // that void* and function pointers have the same size. :( To deal with this
  2704. // in the common case, we handle casts where the number of arguments passed
  2705. // match exactly.
  2706. //
  2707. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
  2708. if (CE->isCast())
  2709. if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
  2710. NeedsCast = true;
  2711. Callee = RF;
  2712. }
  2713. if (NeedsCast) {
  2714. // Ok, just cast the pointer type.
  2715. Out << "((";
  2716. if (isStructRet)
  2717. printStructReturnPointerFunctionType(Out, PAL,
  2718. cast<PointerType>(I.getCalledValue()->getType()));
  2719. else if (hasByVal)
  2720. printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
  2721. else
  2722. printType(Out, I.getCalledValue()->getType());
  2723. Out << ")(void*)";
  2724. }
  2725. writeOperand(Callee);
  2726. if (NeedsCast) Out << ')';
  2727. }
  2728. Out << '(';
  2729. unsigned NumDeclaredParams = FTy->getNumParams();
  2730. CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
  2731. unsigned ArgNo = 0;
  2732. if (isStructRet) { // Skip struct return argument.
  2733. ++AI;
  2734. ++ArgNo;
  2735. }
  2736. bool PrintedArg = false;
  2737. for (; AI != AE; ++AI, ++ArgNo) {
  2738. if (PrintedArg) Out << ", ";
  2739. if (ArgNo < NumDeclaredParams &&
  2740. (*AI)->getType() != FTy->getParamType(ArgNo)) {
  2741. Out << '(';
  2742. printType(Out, FTy->getParamType(ArgNo),
  2743. /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
  2744. Out << ')';
  2745. }
  2746. // Check if the argument is expected to be passed by value.
  2747. if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
  2748. writeOperandDeref(*AI);
  2749. else
  2750. writeOperand(*AI);
  2751. PrintedArg = true;
  2752. }
  2753. Out << ')';
  2754. }
  2755. /// visitBuiltinCall - Handle the call to the specified builtin. Returns true
  2756. /// if the entire call is handled, return false it it wasn't handled, and
  2757. /// optionally set 'WroteCallee' if the callee has already been printed out.
  2758. bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
  2759. bool &WroteCallee) {
  2760. switch (ID) {
  2761. default: {
  2762. // If this is an intrinsic that directly corresponds to a GCC
  2763. // builtin, we emit it here.
  2764. const char *BuiltinName = "";
  2765. Function *F = I.getCalledFunction();
  2766. #define GET_GCC_BUILTIN_NAME
  2767. #include "llvm/Intrinsics.gen"
  2768. #undef GET_GCC_BUILTIN_NAME
  2769. assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
  2770. Out << BuiltinName;
  2771. WroteCallee = true;
  2772. return false;
  2773. }
  2774. case Intrinsic::memory_barrier:
  2775. Out << "__sync_synchronize()";
  2776. return true;
  2777. case Intrinsic::vastart:
  2778. Out << "0; ";
  2779. Out << "va_start(*(va_list*)";
  2780. writeOperand(I.getOperand(1));
  2781. Out << ", ";
  2782. // Output the last argument to the enclosing function.
  2783. if (I.getParent()->getParent()->arg_empty()) {
  2784. std::string msg;
  2785. raw_string_ostream Msg(msg);
  2786. Msg << "The C backend does not currently support zero "
  2787. << "argument varargs functions, such as '"
  2788. << I.getParent()->getParent()->getName() << "'!";
  2789. llvm_report_error(Msg.str());
  2790. }
  2791. writeOperand(--I.getParent()->getParent()->arg_end());
  2792. Out << ')';
  2793. return true;
  2794. case Intrinsic::vaend:
  2795. if (!isa<ConstantPointerNull>(I.getOperand(1))) {
  2796. Out << "0; va_end(*(va_list*)";
  2797. writeOperand(I.getOperand(1));
  2798. Out << ')';
  2799. } else {
  2800. Out << "va_end(*(va_list*)0)";
  2801. }
  2802. return true;
  2803. case Intrinsic::vacopy:
  2804. Out << "0; ";
  2805. Out << "va_copy(*(va_list*)";
  2806. writeOperand(I.getOperand(1));
  2807. Out << ", *(va_list*)";
  2808. writeOperand(I.getOperand(2));
  2809. Out << ')';
  2810. return true;
  2811. case Intrinsic::returnaddress:
  2812. Out << "__builtin_return_address(";
  2813. writeOperand(I.getOperand(1));
  2814. Out << ')';
  2815. return true;
  2816. case Intrinsic::frameaddress:
  2817. Out << "__builtin_frame_address(";
  2818. writeOperand(I.getOperand(1));
  2819. Out << ')';
  2820. return true;
  2821. case Intrinsic::powi:
  2822. Out << "__builtin_powi(";
  2823. writeOperand(I.getOperand(1));
  2824. Out << ", ";
  2825. writeOperand(I.getOperand(2));
  2826. Out << ')';
  2827. return true;
  2828. case Intrinsic::setjmp:
  2829. Out << "setjmp(*(jmp_buf*)";
  2830. writeOperand(I.getOperand(1));
  2831. Out << ')';
  2832. return true;
  2833. case Intrinsic::longjmp:
  2834. Out << "longjmp(*(jmp_buf*)";
  2835. writeOperand(I.getOperand(1));
  2836. Out << ", ";
  2837. writeOperand(I.getOperand(2));
  2838. Out << ')';
  2839. return true;
  2840. case Intrinsic::prefetch:
  2841. Out << "LLVM_PREFETCH((const void *)";
  2842. writeOperand(I.getOperand(1));
  2843. Out << ", ";
  2844. writeOperand(I.getOperand(2));
  2845. Out << ", ";
  2846. writeOperand(I.getOperand(3));
  2847. Out << ")";
  2848. return true;
  2849. case Intrinsic::stacksave:
  2850. // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
  2851. // to work around GCC bugs (see PR1809).
  2852. Out << "0; *((void**)&" << GetValueName(&I)
  2853. << ") = __builtin_stack_save()";
  2854. return true;
  2855. case Intrinsic::dbg_stoppoint: {
  2856. // If we use writeOperand directly we get a "u" suffix which is rejected
  2857. // by gcc.
  2858. DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
  2859. std::string dir;
  2860. GetConstantStringInfo(SPI.getDirectory(), dir);
  2861. std::string file;
  2862. GetConstantStringInfo(SPI.getFileName(), file);
  2863. Out << "\n#line "
  2864. << SPI.getLine()
  2865. << " \""
  2866. << dir << '/' << file << "\"\n";
  2867. return true;
  2868. }
  2869. case Intrinsic::x86_sse_cmp_ss:
  2870. case Intrinsic::x86_sse_cmp_ps:
  2871. case Intrinsic::x86_sse2_cmp_sd:
  2872. case Intrinsic::x86_sse2_cmp_pd:
  2873. Out << '(';
  2874. printType(Out, I.getType());
  2875. Out << ')';
  2876. // Multiple GCC builtins multiplex onto this intrinsic.
  2877. switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
  2878. default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
  2879. case 0: Out << "__builtin_ia32_cmpeq"; break;
  2880. case 1: Out << "__builtin_ia32_cmplt"; break;
  2881. case 2: Out << "__builtin_ia32_cmple"; break;
  2882. case 3: Out << "__builtin_ia32_cmpunord"; break;
  2883. case 4: Out << "__builtin_ia32_cmpneq"; break;
  2884. case 5: Out << "__builtin_ia32_cmpnlt"; break;
  2885. case 6: Out << "__builtin_ia32_cmpnle"; break;
  2886. case 7: Out << "__builtin_ia32_cmpord"; break;
  2887. }
  2888. if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
  2889. Out << 'p';
  2890. else
  2891. Out << 's';
  2892. if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
  2893. Out << 's';
  2894. else
  2895. Out << 'd';
  2896. Out << "(";
  2897. writeOperand(I.getOperand(1));
  2898. Out << ", ";
  2899. writeOperand(I.getOperand(2));
  2900. Out << ")";
  2901. return true;
  2902. case Intrinsic::ppc_altivec_lvsl:
  2903. Out << '(';
  2904. printType(Out, I.getType());
  2905. Out << ')';
  2906. Out << "__builtin_altivec_lvsl(0, (void*)";
  2907. writeOperand(I.getOperand(1));
  2908. Out << ")";
  2909. return true;
  2910. }
  2911. }
  2912. //This converts the llvm constraint string to something gcc is expecting.
  2913. //TODO: work out platform independent constraints and factor those out
  2914. // of the per target tables
  2915. // handle multiple constraint codes
  2916. std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
  2917. assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
  2918. const char *const *table = 0;
  2919. // Grab the translation table from TargetAsmInfo if it exists.
  2920. if (!TAsm) {
  2921. std::string Triple = TheModule->getTargetTriple();
  2922. if (Triple.empty())
  2923. Triple = llvm::sys::getHostTriple();
  2924. std::string E;
  2925. if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
  2926. TAsm = Match->createAsmInfo(Triple);
  2927. }
  2928. if (TAsm)
  2929. table = TAsm->getAsmCBE();
  2930. // Search the translation table if it exists.
  2931. for (int i = 0; table && table[i]; i += 2)
  2932. if (c.Codes[0] == table[i])
  2933. return table[i+1];
  2934. // Default is identity.
  2935. return c.Codes[0];
  2936. }
  2937. //TODO: import logic from AsmPrinter.cpp
  2938. static std::string gccifyAsm(std::string asmstr) {
  2939. for (std::string::size_type i = 0; i != asmstr.size(); ++i)
  2940. if (asmstr[i] == '\n')
  2941. asmstr.replace(i, 1, "\\n");
  2942. else if (asmstr[i] == '\t')
  2943. asmstr.replace(i, 1, "\\t");
  2944. else if (asmstr[i] == '$') {
  2945. if (asmstr[i + 1] == '{') {
  2946. std::string::size_type a = asmstr.find_first_of(':', i + 1);
  2947. std::string::size_type b = asmstr.find_first_of('}', i + 1);
  2948. std::string n = "%" +
  2949. asmstr.substr(a + 1, b - a - 1) +
  2950. asmstr.substr(i + 2, a - i - 2);
  2951. asmstr.replace(i, b - i + 1, n);
  2952. i += n.size() - 1;
  2953. } else
  2954. asmstr.replace(i, 1, "%");
  2955. }
  2956. else if (asmstr[i] == '%')//grr
  2957. { asmstr.replace(i, 1, "%%"); ++i;}
  2958. return asmstr;
  2959. }
  2960. //TODO: assumptions about what consume arguments from the call are likely wrong
  2961. // handle communitivity
  2962. void CWriter::visitInlineAsm(CallInst &CI) {
  2963. InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
  2964. std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
  2965. std::vector<std::pair<Value*, int> > ResultVals;
  2966. if (CI.getType() == Type::getVoidTy(CI.getContext()))
  2967. ;
  2968. else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
  2969. for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
  2970. ResultVals.push_back(std::make_pair(&CI, (int)i));
  2971. } else {
  2972. ResultVals.push_back(std::make_pair(&CI, -1));
  2973. }
  2974. // Fix up the asm string for gcc and emit it.
  2975. Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
  2976. Out << " :";
  2977. unsigned ValueCount = 0;
  2978. bool IsFirst = true;
  2979. // Convert over all the output constraints.
  2980. for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
  2981. E = Constraints.end(); I != E; ++I) {
  2982. if (I->Type != InlineAsm::isOutput) {
  2983. ++ValueCount;
  2984. continue; // Ignore non-output constraints.
  2985. }
  2986. assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
  2987. std::string C = InterpretASMConstraint(*I);
  2988. if (C.empty()) continue;
  2989. if (!IsFirst) {
  2990. Out << ", ";
  2991. IsFirst = false;
  2992. }
  2993. // Unpack the dest.
  2994. Value *DestVal;
  2995. int DestValNo = -1;
  2996. if (ValueCount < ResultVals.size()) {
  2997. DestVal = ResultVals[ValueCount].first;
  2998. DestValNo = ResultVals[ValueCount].second;
  2999. } else
  3000. DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
  3001. if (I->isEarlyClobber)
  3002. C = "&"+C;
  3003. Out << "\"=" << C << "\"(" << GetValueName(DestVal);
  3004. if (DestValNo != -1)
  3005. Out << ".field" << DestValNo; // Multiple retvals.
  3006. Out << ")";
  3007. ++ValueCount;
  3008. }
  3009. // Convert over all the input constraints.
  3010. Out << "\n :";
  3011. IsFirst = true;
  3012. ValueCount = 0;
  3013. for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
  3014. E = Constraints.end(); I != E; ++I) {
  3015. if (I->Type != InlineAsm::isInput) {
  3016. ++ValueCount;
  3017. continue; // Ignore non-input constraints.
  3018. }
  3019. assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
  3020. std::string C = InterpretASMConstraint(*I);
  3021. if (C.empty()) continue;
  3022. if (!IsFirst) {
  3023. Out << ", ";
  3024. IsFirst = false;
  3025. }
  3026. assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
  3027. Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
  3028. Out << "\"" << C << "\"(";
  3029. if (!I->isIndirect)
  3030. writeOperand(SrcVal);
  3031. else
  3032. writeOperandDeref(SrcVal);
  3033. Out << ")";
  3034. }
  3035. // Convert over the clobber constraints.
  3036. IsFirst = true;
  3037. ValueCount = 0;
  3038. for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
  3039. E = Constraints.end(); I != E; ++I) {
  3040. if (I->Type != InlineAsm::isClobber)
  3041. continue; // Ignore non-input constraints.
  3042. assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
  3043. std::string C = InterpretASMConstraint(*I);
  3044. if (C.empty()) continue;
  3045. if (!IsFirst) {
  3046. Out << ", ";
  3047. IsFirst = false;
  3048. }
  3049. Out << '\"' << C << '"';
  3050. }
  3051. Out << ")";
  3052. }
  3053. void CWriter::visitMallocInst(MallocInst &I) {
  3054. llvm_unreachable("lowerallocations pass didn't work!");
  3055. }
  3056. void CWriter::visitAllocaInst(AllocaInst &I) {
  3057. Out << '(';
  3058. printType(Out, I.getType());
  3059. Out << ") alloca(sizeof(";
  3060. printType(Out, I.getType()->getElementType());
  3061. Out << ')';
  3062. if (I.isArrayAllocation()) {
  3063. Out << " * " ;
  3064. writeOperand(I.getOperand(0));
  3065. }
  3066. Out << ')';
  3067. }
  3068. void CWriter::visitFreeInst(FreeInst &I) {
  3069. llvm_unreachable("lowerallocations pass didn't work!");
  3070. }
  3071. void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
  3072. gep_type_iterator E, bool Static) {
  3073. // If there are no indices, just print out the pointer.
  3074. if (I == E) {
  3075. writeOperand(Ptr);
  3076. return;
  3077. }
  3078. // Find out if the last index is into a vector. If so, we have to print this
  3079. // specially. Since vectors can't have elements of indexable type, only the
  3080. // last index could possibly be of a vector element.
  3081. const VectorType *LastIndexIsVector = 0;
  3082. {
  3083. for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
  3084. LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
  3085. }
  3086. Out << "(";
  3087. // If the last index is into a vector, we can't print it as &a[i][j] because
  3088. // we can't index into a vector with j in GCC. Instead, emit this as
  3089. // (((float*)&a[i])+j)
  3090. if (LastIndexIsVector) {
  3091. Out << "((";
  3092. printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
  3093. Out << ")(";
  3094. }
  3095. Out << '&';
  3096. // If the first index is 0 (very typical) we can do a number of
  3097. // simplifications to clean up the code.
  3098. Value *FirstOp = I.getOperand();
  3099. if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
  3100. // First index isn't simple, print it the hard way.
  3101. writeOperand(Ptr);
  3102. } else {
  3103. ++I; // Skip the zero index.
  3104. // Okay, emit the first operand. If Ptr is something that is already address
  3105. // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
  3106. if (isAddressExposed(Ptr)) {
  3107. writeOperandInternal(Ptr, Static);
  3108. } else if (I != E && isa<StructType>(*I)) {
  3109. // If we didn't already emit the first operand, see if we can print it as
  3110. // P->f instead of "P[0].f"
  3111. writeOperand(Ptr);
  3112. Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
  3113. ++I; // eat the struct index as well.
  3114. } else {
  3115. // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
  3116. Out << "(*";
  3117. writeOperand(Ptr);
  3118. Out << ")";
  3119. }
  3120. }
  3121. for (; I != E; ++I) {
  3122. if (isa<StructType>(*I)) {
  3123. Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
  3124. } else if (isa<ArrayType>(*I)) {
  3125. Out << ".array[";
  3126. writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
  3127. Out << ']';
  3128. } else if (!isa<VectorType>(*I)) {
  3129. Out << '[';
  3130. writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
  3131. Out << ']';
  3132. } else {
  3133. // If the last index is into a vector, then print it out as "+j)". This
  3134. // works with the 'LastIndexIsVector' code above.
  3135. if (isa<Constant>(I.getOperand()) &&
  3136. cast<Constant>(I.getOperand())->isNullValue()) {
  3137. Out << "))"; // avoid "+0".
  3138. } else {
  3139. Out << ")+(";
  3140. writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
  3141. Out << "))";
  3142. }
  3143. }
  3144. }
  3145. Out << ")";
  3146. }
  3147. void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
  3148. bool IsVolatile, unsigned Alignment) {
  3149. bool IsUnaligned = Alignment &&
  3150. Alignment < TD->getABITypeAlignment(OperandType);
  3151. if (!IsUnaligned)
  3152. Out << '*';
  3153. if (IsVolatile || IsUnaligned) {
  3154. Out << "((";
  3155. if (IsUnaligned)
  3156. Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
  3157. printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
  3158. if (IsUnaligned) {
  3159. Out << "; } ";
  3160. if (IsVolatile) Out << "volatile ";
  3161. Out << "*";
  3162. }
  3163. Out << ")";
  3164. }
  3165. writeOperand(Operand);
  3166. if (IsVolatile || IsUnaligned) {
  3167. Out << ')';
  3168. if (IsUnaligned)
  3169. Out << "->data";
  3170. }
  3171. }
  3172. void CWriter::visitLoadInst(LoadInst &I) {
  3173. writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
  3174. I.getAlignment());
  3175. }
  3176. void CWriter::visitStoreInst(StoreInst &I) {
  3177. writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
  3178. I.isVolatile(), I.getAlignment());
  3179. Out << " = ";
  3180. Value *Operand = I.getOperand(0);
  3181. Constant *BitMask = 0;
  3182. if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
  3183. if (!ITy->isPowerOf2ByteWidth())
  3184. // We have a bit width that doesn't match an even power-of-2 byte
  3185. // size. Consequently we must & the value with the type's bit mask
  3186. BitMask = ConstantInt::get(ITy, ITy->getBitMask());
  3187. if (BitMask)
  3188. Out << "((";
  3189. writeOperand(Operand);
  3190. if (BitMask) {
  3191. Out << ") & ";
  3192. printConstant(BitMask, false);
  3193. Out << ")";
  3194. }
  3195. }
  3196. void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
  3197. printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
  3198. gep_type_end(I), false);
  3199. }
  3200. void CWriter::visitVAArgInst(VAArgInst &I) {
  3201. Out << "va_arg(*(va_list*)";
  3202. writeOperand(I.getOperand(0));
  3203. Out << ", ";
  3204. printType(Out, I.getType());
  3205. Out << ");\n ";
  3206. }
  3207. void CWriter::visitInsertElementInst(InsertElementInst &I) {
  3208. const Type *EltTy = I.getType()->getElementType();
  3209. writeOperand(I.getOperand(0));
  3210. Out << ";\n ";
  3211. Out << "((";
  3212. printType(Out, PointerType::getUnqual(EltTy));
  3213. Out << ")(&" << GetValueName(&I) << "))[";
  3214. writeOperand(I.getOperand(2));
  3215. Out << "] = (";
  3216. writeOperand(I.getOperand(1));
  3217. Out << ")";
  3218. }
  3219. void CWriter::visitExtractElementInst(ExtractElementInst &I) {
  3220. // We know that our operand is not inlined.
  3221. Out << "((";
  3222. const Type *EltTy =
  3223. cast<VectorType>(I.getOperand(0)->getType())->getElementType();
  3224. printType(Out, PointerType::getUnqual(EltTy));
  3225. Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
  3226. writeOperand(I.getOperand(1));
  3227. Out << "]";
  3228. }
  3229. void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
  3230. Out << "(";
  3231. printType(Out, SVI.getType());
  3232. Out << "){ ";
  3233. const VectorType *VT = SVI.getType();
  3234. unsigned NumElts = VT->getNumElements();
  3235. const Type *EltTy = VT->getElementType();
  3236. for (unsigned i = 0; i != NumElts; ++i) {
  3237. if (i) Out << ", ";
  3238. int SrcVal = SVI.getMaskValue(i);
  3239. if ((unsigned)SrcVal >= NumElts*2) {
  3240. Out << " 0/*undef*/ ";
  3241. } else {
  3242. Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
  3243. if (isa<Instruction>(Op)) {
  3244. // Do an extractelement of this value from the appropriate input.
  3245. Out << "((";
  3246. printType(Out, PointerType::getUnqual(EltTy));
  3247. Out << ")(&" << GetValueName(Op)
  3248. << "))[" << (SrcVal & (NumElts-1)) << "]";
  3249. } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
  3250. Out << "0";
  3251. } else {
  3252. printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
  3253. (NumElts-1)),
  3254. false);
  3255. }
  3256. }
  3257. }
  3258. Out << "}";
  3259. }
  3260. void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
  3261. // Start by copying the entire aggregate value into the result variable.
  3262. writeOperand(IVI.getOperand(0));
  3263. Out << ";\n ";
  3264. // Then do the insert to update the field.
  3265. Out << GetValueName(&IVI);
  3266. for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
  3267. i != e; ++i) {
  3268. const Type *IndexedTy =
  3269. ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
  3270. if (isa<ArrayType>(IndexedTy))
  3271. Out << ".array[" << *i << "]";
  3272. else
  3273. Out << ".field" << *i;
  3274. }
  3275. Out << " = ";
  3276. writeOperand(IVI.getOperand(1));
  3277. }
  3278. void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
  3279. Out << "(";
  3280. if (isa<UndefValue>(EVI.getOperand(0))) {
  3281. Out << "(";
  3282. printType(Out, EVI.getType());
  3283. Out << ") 0/*UNDEF*/";
  3284. } else {
  3285. Out << GetValueName(EVI.getOperand(0));
  3286. for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
  3287. i != e; ++i) {
  3288. const Type *IndexedTy =
  3289. ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
  3290. if (isa<ArrayType>(IndexedTy))
  3291. Out << ".array[" << *i << "]";
  3292. else
  3293. Out << ".field" << *i;
  3294. }
  3295. }
  3296. Out << ")";
  3297. }
  3298. //===----------------------------------------------------------------------===//
  3299. // External Interface declaration
  3300. //===----------------------------------------------------------------------===//
  3301. bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
  3302. formatted_raw_ostream &o,
  3303. CodeGenFileType FileType,
  3304. CodeGenOpt::Level OptLevel) {
  3305. if (FileType != TargetMachine::AssemblyFile) return true;
  3306. PM.add(createGCLoweringPass());
  3307. PM.add(createLowerAllocationsPass(true));
  3308. PM.add(createLowerInvokePass());
  3309. PM.add(createCFGSimplificationPass()); // clean up after lower invoke.
  3310. PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
  3311. PM.add(new CWriter(o));
  3312. PM.add(createGCInfoDeleter());
  3313. return false;
  3314. }