CBackend.cpp 120 KB

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