CBackend.cpp 122 KB

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