CBackend.cpp 125 KB

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