forked from ispc/ispc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cbackend.cpp
5431 lines (4846 loc) · 195 KB
/
cbackend.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This library converts LLVM code to C code, compilable by GCC and other C
// compilers.
//
//===----------------------------------------------------------------------===//
#include "ispc.h"
#include "module.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#ifndef _MSC_VER
#include <inttypes.h>
#define HAVE_PRINTF_A 1
#define ENABLE_CBE_PRINTF_A 1
#endif
#ifndef PRIx64
#define PRIx64 "llx"
#endif
#include "llvmutil.h"
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/CallingConv.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/InlineAsm.h"
#else // LLVM 3.3+
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/InlineAsm.h"
#endif
#include "llvm/Pass.h"
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 // <= 3.6
#include "llvm/PassManager.h"
#else // LLVM 3.7+
#include "llvm/IR/LegacyPassManager.h"
#endif
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
#include "llvm/TypeFinder.h"
#else // LLVM_3_3+
#include "llvm/IR/TypeFinder.h"
#endif
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_4 // 3.2, 3.3, 3.4
#include "llvm/Support/InstIterator.h"
#else // 3.5+
#include "llvm/IR/InstIterator.h"
#endif
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5
#include "llvm/Analysis/FindUsedTypes.h"
#endif
#include "llvm/Analysis/LoopInfo.h"
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5
#include "llvm/IR/Verifier.h"
#include <llvm/IR/IRPrintingPasses.h>
#include "llvm/IR/CallSite.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/Support/FileSystem.h"
#else
#include "llvm/Analysis/Verifier.h"
#include <llvm/Assembly/PrintModulePass.h>
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#endif
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
//#include "llvm/Target/Mangler.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2 // 3.2
#include "llvm/DataLayout.h"
#else // LLVM 3.3+
#include "llvm/IR/DataLayout.h"
#endif
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2 // 3.2
#include "llvm/Support/InstVisitor.h"
#elif ISPC_LLVM_VERSION <= ISPC_LLVM_3_4 // 3.3, 3.4
#include "llvm/InstVisitor.h"
#else // LLVM 3.5+
#include "llvm/IR/InstVisitor.h"
#endif
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/Host.h"
#include "llvm/Target/TargetMachine.h"
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_4 // 3.2, 3.3, 3.4
#include "llvm/Config/config.h"
#endif
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/ToolOutputFile.h>
#include <algorithm>
// Some ms header decided to define setjmp as _setjmp, undo this for this file.
#ifdef _MSC_VER
#undef setjmp
#define snprintf _snprintf
#endif
///////////////////////////////////////////////////////////////////////////////
// This part of code was in LLVM's ConstantsScanner.h,
// but it was removed in revision #232397
namespace constant_scanner {
class constant_iterator : public std::iterator<std::forward_iterator_tag,
const llvm::Constant, ptrdiff_t> {
llvm::const_inst_iterator InstI; // Method instruction iterator
unsigned OpIdx; // Operand index
bool isAtConstant() const {
assert(!InstI.atEnd() && OpIdx < InstI->getNumOperands() &&
"isAtConstant called with invalid arguments!");
return llvm::isa<llvm::Constant>(InstI->getOperand(OpIdx));
}
public:
constant_iterator(const llvm::Function *F) : InstI(llvm::inst_begin(F)), OpIdx(0) {
// Advance to first constant... if we are not already at constant or end
if (InstI != llvm::inst_end(F) && // InstI is valid?
(InstI->getNumOperands() == 0 || !isAtConstant())) // Not at constant?
operator++();
}
constant_iterator(const llvm::Function *F, bool) // end ctor
: InstI(llvm::inst_end(F)),
OpIdx(0) {}
bool operator==(const constant_iterator &x) const {
return OpIdx == x.OpIdx && InstI == x.InstI;
}
bool operator!=(const constant_iterator &x) const { return !(*this == x); }
pointer operator*() const {
assert(isAtConstant() && "Dereferenced an iterator at the end!");
return llvm::cast<llvm::Constant>(InstI->getOperand(OpIdx));
}
constant_iterator &operator++() { // Preincrement implementation
++OpIdx;
do {
unsigned NumOperands = InstI->getNumOperands();
while (OpIdx < NumOperands && !isAtConstant()) {
++OpIdx;
}
if (OpIdx < NumOperands) return *this; // Found a constant!
++InstI;
OpIdx = 0;
} while (!InstI.atEnd());
return *this; // At the end of the method
}
};
inline constant_iterator constant_begin(const llvm::Function *F) {
return constant_iterator(F);
}
inline constant_iterator constant_end(const llvm::Function *F) {
return constant_iterator(F, true);
}
}
///////////////////////////////////////////////////////////////////////////////
// FIXME:
namespace {
/// TypeFinder - Walk over a module, identifying all of the types that are
/// used by the module.
class TypeFinder {
// To avoid walking constant expressions multiple times and other IR
// objects, we keep several helper maps.
llvm::DenseSet<const llvm::Value*> VisitedConstants;
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_6 // LLVM 3.6+
llvm::DenseSet<const llvm::Metadata*> VisitedMDNodes;
#endif
llvm::DenseSet<llvm::Type*> VisitedTypes;
std::vector<llvm::ArrayType*> &ArrayTypes;
std::vector<llvm::IntegerType*> &IntegerTypes;
std::vector<bool> &IsVolatile;
std::vector<int> &Alignment;
public:
TypeFinder(std::vector<llvm::ArrayType*> &t, std::vector<llvm::IntegerType*> &i,
std::vector<bool> &v, std::vector<int> &a)
: ArrayTypes(t), IntegerTypes(i) , IsVolatile(v), Alignment(a){}
void run(const llvm::Module &M) {
// Get types from global variables.
for (llvm::Module::const_global_iterator I = M.global_begin(),
E = M.global_end(); I != E; ++I) {
incorporateType(I->getType());
if (I->hasInitializer())
incorporateValue(I->getInitializer());
}
// Get types from aliases.
for (llvm::Module::const_alias_iterator I = M.alias_begin(),
E = M.alias_end(); I != E; ++I) {
incorporateType(I->getType());
if (const llvm::Value *Aliasee = I->getAliasee())
incorporateValue(Aliasee);
}
llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 4> MDForInst;
// Get types from functions.
for (llvm::Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
incorporateType(FI->getType());
for (llvm::Function::const_iterator BB = FI->begin(), E = FI->end();
BB != E;++BB)
for (llvm::BasicBlock::const_iterator II = BB->begin(),
E = BB->end(); II != E; ++II) {
const llvm::Instruction &I = *II;
// Operands of SwitchInsts changed format after 3.1
// Seems like there ought to be better way to do what we
// want here. For now, punt on SwitchInsts.
if (llvm::isa<llvm::SwitchInst>(&I)) continue;
// Incorporate the type of the instruction and all its operands.
incorporateType(I.getType());
if (llvm::isa<llvm::StoreInst>(&I))
if (llvm::IntegerType *ITy = llvm::dyn_cast<llvm::IntegerType>(I.getType())) {
IntegerTypes.push_back(ITy);
const llvm::StoreInst *St = llvm::dyn_cast<llvm::StoreInst>(&I);
IsVolatile.push_back(St->isVolatile());
Alignment.push_back(St->getAlignment());
}
if (llvm::isa<llvm::LoadInst>(&I))
if (llvm::IntegerType *ITy = llvm::dyn_cast<llvm::IntegerType>(I.getType())) {
IntegerTypes.push_back(ITy);
const llvm::LoadInst *St = llvm::dyn_cast<llvm::LoadInst>(&I);
IsVolatile.push_back(St->isVolatile());
Alignment.push_back(St->getAlignment());
}
for (llvm::User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
OI != OE; ++OI)
incorporateValue(*OI);
// Incorporate types hiding in metadata.
I.getAllMetadataOtherThanDebugLoc(MDForInst);
for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
incorporateMDNode(MDForInst[i].second);
MDForInst.clear();
}
}
for (llvm::Module::const_named_metadata_iterator I = M.named_metadata_begin(),
E = M.named_metadata_end(); I != E; ++I) {
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_7 /* 3.2, 3.3, 3.4, 3.5, 3.6, 3.7 */
const llvm::NamedMDNode *NMD = I;
#else /* LLVM 3.8+ */
const llvm::NamedMDNode *NMD = &*I;
#endif
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
incorporateMDNode(NMD->getOperand(i));
}
}
private:
void incorporateType(llvm::Type *Ty) {
// Check to see if we're already visited this type.
if (!VisitedTypes.insert(Ty).second)
return;
if (llvm::ArrayType *ATy = llvm::dyn_cast<llvm::ArrayType>(Ty))
ArrayTypes.push_back(ATy);
// Recursively walk all contained types.
for (llvm::Type::subtype_iterator I = Ty->subtype_begin(),
E = Ty->subtype_end(); I != E; ++I)
incorporateType(*I);
}
/// incorporateValue - This method is used to walk operand lists finding
/// types hiding in constant expressions and other operands that won't be
/// walked in other ways. GlobalValues, basic blocks, instructions, and
/// inst operands are all explicitly enumerated.
void incorporateValue(const llvm::Value *V) {
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5 // 3.2, 3.3, 3.4, 3.5
if (const llvm::MDNode *M = llvm::dyn_cast<llvm::MDNode>(V)) {
incorporateMDNode(M);
return;
}
#else /* LLVN 3.6+ */
if (const llvm::MetadataAsValue *MV = llvm::dyn_cast<llvm::MetadataAsValue>(V)) {
incorporateMDNode(MV->getMetadata());
return;
}
#endif
if (!llvm::isa<llvm::Constant>(V) || llvm::isa<llvm::GlobalValue>(V)) return;
// Already visited?
if (!VisitedConstants.insert(V).second)
return;
// Check this type.
incorporateType(V->getType());
// Look in operands for types.
const llvm::User *U = llvm::cast<llvm::User>(V);
for (llvm::Constant::const_op_iterator I = U->op_begin(),
E = U->op_end(); I != E;++I)
incorporateValue(*I);
}
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5 // 3.2, 3.3, 3.4, 3.5
void incorporateMDNode(const llvm::MDNode *V) {
// Already visited?
if (!VisitedConstants.insert(V).second)
return;
// Look in operands for types.
for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i)
if (llvm::Value *Op = V->getOperand(i))
incorporateValue(Op);
}
#else // LLVM 3.6+
void incorporateMDNode(const llvm::Metadata *M) {
// Already visited?
if (!VisitedMDNodes.insert(M).second)
return;
if (const llvm::MDNode* N = llvm::dyn_cast<llvm::MDNode>(M)) {
// Look in operands for types.
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
if (const llvm::Metadata *O = N->getOperand(i))
incorporateMDNode(O);
} else if (llvm::isa<llvm::MDString>(M)) {
// Nothing to do with MDString.
} else if (const llvm::ValueAsMetadata* V = llvm::dyn_cast<llvm::ValueAsMetadata>(M)) {
incorporateValue(V->getValue());
} else {
// Some unknown Metadata subclass - has LLVM introduced something new?
llvm_unreachable("Unknown Metadata subclass");
}
}
#endif
};
} // end anonymous namespace
static void findUsedArrayAndLongIntTypes(const llvm::Module *m, std::vector<llvm::ArrayType*> &t,
std::vector<llvm::IntegerType*> &i, std::vector<bool> &IsVolatile,
std::vector<int> &Alignment) {
TypeFinder(t, i, IsVolatile, Alignment).run(*m);
}
static bool is_vec16_i64_ty(llvm::Type *Ty) {
llvm::VectorType *VTy = llvm::dyn_cast<llvm::VectorType>(Ty);
if ((VTy != NULL) && (VTy->getElementType()->isIntegerTy()) &&
VTy->getElementType()->getPrimitiveSizeInBits() == 64)
return true;
return false;
}
namespace {
class CBEMCAsmInfo : public llvm::MCAsmInfo {
public:
CBEMCAsmInfo() {
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_4 // 3.2, 3.3, 3.4
GlobalPrefix = "";
#endif
PrivateGlobalPrefix = "";
}
};
/// CWriter - This class is the main chunk of code that converts an LLVM
/// module to a C translation unit.
class CWriter : public llvm::FunctionPass, public llvm::InstVisitor<CWriter> {
llvm::formatted_raw_ostream &Out;
llvm::IntrinsicLowering *IL;
//llvm::Mangler *Mang;
llvm::LoopInfo *LI;
const llvm::Module *TheModule;
const llvm::MCAsmInfo* TAsm;
const llvm::MCRegisterInfo *MRI;
const llvm::MCObjectFileInfo *MOFI;
llvm::MCContext *TCtx;
// FIXME: it's ugly to have the name be "TD" here, but it saves us
// lots of ifdefs in the below since the new DataLayout and the old
// TargetData have generally similar interfaces...
const llvm::DataLayout* TD;
std::map<const llvm::ConstantFP *, unsigned> FPConstantMap;
std::map<const llvm::ConstantDataVector *, unsigned> VectorConstantMap;
unsigned VectorConstantIndex;
std::set<llvm::Function*> intrinsicPrototypesAlreadyGenerated;
std::set<const llvm::Argument*> ByValParams;
unsigned FPCounter;
unsigned OpaqueCounter;
llvm::DenseMap<const llvm::Value*, unsigned> AnonValueNumbers;
unsigned NextAnonValueNumber;
std::string includeName;
int vectorWidth;
/// UnnamedStructIDs - This contains a unique ID for each struct that is
/// either anonymous or has no name.
llvm::DenseMap<llvm::StructType*, unsigned> UnnamedStructIDs;
llvm::DenseMap<llvm::ArrayType *, unsigned> ArrayIDs;
public:
static char ID;
explicit CWriter(llvm::formatted_raw_ostream &o, const char *incname,
int vecwidth)
: FunctionPass(ID), Out(o), IL(0), /* Mang(0), */ LI(0),
TheModule(0), TAsm(0), MRI(0), MOFI(0), TCtx(0), TD(0),
OpaqueCounter(0), NextAnonValueNumber(0),
includeName(incname ? incname : "generic_defs.h"),
vectorWidth(vecwidth) {
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 // <= 3.6
initializeLoopInfoPass(*llvm::PassRegistry::getPassRegistry());
#else // LLVM 3.7+
initializeLoopInfoWrapperPassPass(*llvm::PassRegistry::getPassRegistry());
#endif
FPCounter = 0;
VectorConstantIndex = 0;
}
virtual const char *getPassName() const { return "C backend"; }
void getAnalysisUsage(llvm::AnalysisUsage &AU) const {
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 // <= 3.6
AU.addRequired<llvm::LoopInfo>();
#else // LLVM 3.7+
AU.addRequired<llvm::LoopInfoWrapperPass>();
#endif
AU.setPreservesAll();
}
virtual bool doInitialization(llvm::Module &M);
bool runOnFunction(llvm::Function &F) {
// Do not codegen any 'available_externally' functions at all, they have
// definitions outside the translation unit.
if (F.hasAvailableExternallyLinkage())
return false;
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6 // <= 3.6
LI = &getAnalysis<llvm::LoopInfo>();
#else // LLVM 3.7+
LI = &getAnalysis<llvm::LoopInfoWrapperPass>().getLoopInfo();
#endif
// Get rid of intrinsics we can't handle.
lowerIntrinsics(F);
// Output all floating point constants that cannot be printed accurately.
printFloatingPointConstants(F);
// Output all vector constants so they can be accessed with single
// vector loads
printVectorConstants(F);
printFunction(F);
return false;
}
virtual bool doFinalization(llvm::Module &M) {
// Free memory...
delete IL;
delete TD;
//delete Mang;
delete TCtx;
delete TAsm;
delete MRI;
delete MOFI;
FPConstantMap.clear();
VectorConstantMap.clear();
ByValParams.clear();
intrinsicPrototypesAlreadyGenerated.clear();
UnnamedStructIDs.clear();
ArrayIDs.clear();
return false;
}
llvm::raw_ostream &printType(llvm::raw_ostream &Out, llvm::Type *Ty,
bool isSigned = false,
const std::string &VariableName = "",
bool IgnoreName = false,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
const llvm::AttrListPtr &PAL = llvm::AttrListPtr()
#else // LLVM 3.3+
const llvm::AttributeSet &PAL = llvm::AttributeSet()
#endif
);
llvm::raw_ostream &printSimpleType(llvm::raw_ostream &Out, llvm::Type *Ty,
bool isSigned,
const std::string &NameSoFar = "");
void printStructReturnPointerFunctionType(llvm::raw_ostream &Out,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
const llvm::AttrListPtr &PAL,
#else // LLVM 3.3+
const llvm::AttributeSet &PAL,
#endif
llvm::PointerType *Ty);
std::string getStructName(llvm::StructType *ST);
std::string getArrayName(llvm::ArrayType *AT);
/// writeOperandDeref - Print the result of dereferencing the specified
/// operand with '*'. This is equivalent to printing '*' then using
/// writeOperand, but avoids excess syntax in some cases.
void writeOperandDeref(llvm::Value *Operand) {
if (isAddressExposed(Operand)) {
// Already something with an address exposed.
writeOperandInternal(Operand);
} else {
Out << "*(";
writeOperand(Operand);
Out << ")";
}
}
void writeOperand(llvm::Value *Operand, bool Static = false);
void writeInstComputationInline(llvm::Instruction &I);
void writeOperandInternal(llvm::Value *Operand, bool Static = false);
void writeOperandWithCast(llvm::Value* Operand, unsigned Opcode);
void writeOperandWithCast(llvm::Value* Operand, const llvm::ICmpInst &I);
bool writeInstructionCast(const llvm::Instruction &I);
void writeMemoryAccess(llvm::Value *Operand, llvm::Type *OperandType,
bool IsVolatile, unsigned Alignment);
private :
void lowerIntrinsics(llvm::Function &F);
/// Prints the definition of the intrinsic function F. Supports the
/// intrinsics which need to be explicitly defined in the CBackend.
void printIntrinsicDefinition(const llvm::Function &F, llvm::raw_ostream &Out);
void printModuleTypes();
void printContainedStructs(llvm::Type *Ty, llvm::SmallPtrSet<llvm::Type *, 16> &);
void printContainedArrays(llvm::ArrayType *ATy, llvm::SmallPtrSet<llvm::Type *, 16> &);
void printFloatingPointConstants(llvm::Function &F);
void printFloatingPointConstants(const llvm::Constant *C);
void printVectorConstants(llvm::Function &F);
void printFunctionSignature(const llvm::Function *F, bool Prototype);
void printFunction(llvm::Function &);
void printBasicBlock(llvm::BasicBlock *BB);
void printLoop(llvm::Loop *L);
bool printCast(unsigned opcode, llvm::Type *SrcTy, llvm::Type *DstTy);
void printConstant(llvm::Constant *CPV, bool Static);
void printConstantWithCast(llvm::Constant *CPV, unsigned Opcode);
bool printConstExprCast(const llvm::ConstantExpr *CE, bool Static);
void printConstantArray(llvm::ConstantArray *CPA, bool Static);
void printConstantVector(llvm::ConstantVector *CV, bool Static);
void printConstantDataSequential(llvm::ConstantDataSequential *CDS, bool Static);
/// isAddressExposed - Return true if the specified value's name needs to
/// have its address taken in order to get a C value of the correct type.
/// This happens for global variables, byval parameters, and direct allocas.
bool isAddressExposed(const llvm::Value *V) const {
if (const llvm::Argument *A = llvm::dyn_cast<llvm::Argument>(V))
return ByValParams.count(A);
return llvm::isa<llvm::GlobalVariable>(V) || isDirectAlloca(V);
}
// isInlinableInst - Attempt to inline instructions into their uses to build
// trees as much as possible. To do this, we have to consistently decide
// what is acceptable to inline, so that variable declarations don't get
// printed and an extra copy of the expr is not emitted.
//
static bool isInlinableInst(const llvm::Instruction &I) {
// Always inline cmp instructions, even if they are shared by multiple
// expressions. GCC generates horrible code if we don't.
if (llvm::isa<llvm::CmpInst>(I) && llvm::isa<llvm::VectorType>(I.getType()) == false)
return true;
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 // 3.5+
// This instruction returns a struct on LLVM older than 3.4, and can not be inlined
if (llvm::isa<llvm::AtomicCmpXchgInst>(I))
return false;
#endif
// Must be an expression, must be used exactly once. If it is dead, we
// emit it inline where it would go.
if (I.getType() == llvm::Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
llvm::isa<llvm::TerminatorInst>(I) || llvm::isa<llvm::CallInst>(I) || llvm::isa<llvm::PHINode>(I) ||
llvm::isa<llvm::LoadInst>(I) || llvm::isa<llvm::VAArgInst>(I) || llvm::isa<llvm::InsertElementInst>(I) ||
llvm::isa<llvm::InsertValueInst>(I) || llvm::isa<llvm::ExtractValueInst>(I) || llvm::isa<llvm::SelectInst>(I))
// Don't inline a load across a store or other bad things!
return false;
// Must not be used in inline asm, extractelement, or shufflevector.
if (I.hasOneUse()) {
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 // 3.5+
const llvm::Instruction &User = llvm::cast<llvm::Instruction>(*I.user_back());
#else
const llvm::Instruction &User = llvm::cast<llvm::Instruction>(*I.use_back());
#endif
if (isInlineAsm(User) || llvm::isa<llvm::ExtractElementInst>(User) ||
llvm::isa<llvm::ShuffleVectorInst>(User) || llvm::isa<llvm::AtomicRMWInst>(User) ||
llvm::isa<llvm::AtomicCmpXchgInst>(User))
return false;
}
// Only inline instruction it if it's use is in the same BB as the inst.
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 // 3.5+
return I.getParent() == llvm::cast<llvm::Instruction>(I.user_back())->getParent();
#else
return I.getParent() == llvm::cast<llvm::Instruction>(I.use_back())->getParent();
#endif
}
// isDirectAlloca - Define fixed sized allocas in the entry block as direct
// variables which are accessed with the & operator. This causes GCC to
// generate significantly better code than to emit alloca calls directly.
//
static const llvm::AllocaInst *isDirectAlloca(const llvm::Value *V) {
const llvm::AllocaInst *AI = llvm::dyn_cast<llvm::AllocaInst>(V);
if (!AI) return 0;
if (AI->isArrayAllocation())
return 0; // FIXME: we can also inline fixed size array allocas!
if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
return 0;
return AI;
}
// isInlineAsm - Check if the instruction is a call to an inline asm chunk.
static bool isInlineAsm(const llvm::Instruction& I) {
if (const llvm::CallInst *CI = llvm::dyn_cast<llvm::CallInst>(&I))
return llvm::isa<llvm::InlineAsm>(CI->getCalledValue());
return false;
}
// Instruction visitation functions
friend class llvm::InstVisitor<CWriter>;
void visitReturnInst(llvm::ReturnInst &I);
void visitBranchInst(llvm::BranchInst &I);
void visitSwitchInst(llvm::SwitchInst &I);
void visitIndirectBrInst(llvm::IndirectBrInst &I);
void visitInvokeInst(llvm::InvokeInst &I) {
llvm_unreachable("Lowerinvoke pass didn't work!");
}
void visitResumeInst(llvm::ResumeInst &I) {
llvm_unreachable("DwarfEHPrepare pass didn't work!");
}
void visitUnreachableInst(llvm::UnreachableInst &I);
void visitPHINode(llvm::PHINode &I);
void visitBinaryOperator(llvm::Instruction &I);
void visitICmpInst(llvm::ICmpInst &I);
void visitFCmpInst(llvm::FCmpInst &I);
void visitCastInst (llvm::CastInst &I);
void visitSelectInst(llvm::SelectInst &I);
void visitCallInst (llvm::CallInst &I);
void visitInlineAsm(llvm::CallInst &I);
bool visitBuiltinCall(llvm::CallInst &I, llvm::Intrinsic::ID ID, bool &WroteCallee);
void visitAllocaInst(llvm::AllocaInst &I);
void visitLoadInst (llvm::LoadInst &I);
void visitStoreInst (llvm::StoreInst &I);
void visitGetElementPtrInst(llvm::GetElementPtrInst &I);
void visitVAArgInst (llvm::VAArgInst &I);
void visitInsertElementInst(llvm::InsertElementInst &I);
void visitExtractElementInst(llvm::ExtractElementInst &I);
void visitShuffleVectorInst(llvm::ShuffleVectorInst &SVI);
void visitInsertValueInst(llvm::InsertValueInst &I);
void visitExtractValueInst(llvm::ExtractValueInst &I);
void visitAtomicRMWInst(llvm::AtomicRMWInst &I);
void visitAtomicCmpXchgInst(llvm::AtomicCmpXchgInst &I);
void visitInstruction(llvm::Instruction &I) {
#ifndef NDEBUG
llvm::errs() << "C Writer does not know about " << I;
#endif
llvm_unreachable(0);
}
void outputLValue(llvm::Instruction *I) {
Out << " " << GetValueName(I) << " = ";
}
bool isGotoCodeNecessary(llvm::BasicBlock *From, llvm::BasicBlock *To);
void printPHICopiesForSuccessor(llvm::BasicBlock *CurBlock,
llvm::BasicBlock *Successor, unsigned Indent);
void printBranchToBlock(llvm::BasicBlock *CurBlock, llvm::BasicBlock *SuccBlock,
unsigned Indent);
void printGEPExpression(llvm::Value *Ptr, llvm::gep_type_iterator I,
llvm::gep_type_iterator E, bool Static);
std::string GetValueName(const llvm::Value *Operand);
};
}
char CWriter::ID = 0;
static std::string CBEMangle(const std::string &S) {
std::string Result;
for (unsigned i = 0, e = S.size(); i != e; ++i) {
if (i+1 != e && ((S[i] == '>' && S[i+1] == '>') ||
(S[i] == '<' && S[i+1] == '<'))) {
Result += '_';
Result += 'A'+(S[i]&15);
Result += 'A'+((S[i]>>4)&15);
Result += '_';
i++;
} else if (isalnum(S[i]) || S[i] == '_' || S[i] == '<' || S[i] == '>') {
Result += S[i];
} else {
Result += '_';
Result += 'A'+(S[i]&15);
Result += 'A'+((S[i]>>4)&15);
Result += '_';
}
}
return Result;
}
std::string CWriter::getStructName(llvm::StructType *ST) {
if (!ST->isLiteral() && !ST->getName().empty())
return CBEMangle("l_"+ST->getName().str());
return "l_unnamed_" + llvm::utostr(UnnamedStructIDs[ST]);
}
std::string CWriter::getArrayName(llvm::ArrayType *AT) {
return "l_array_" + llvm::utostr(ArrayIDs[AT]);
}
/// printStructReturnPointerFunctionType - This is like printType for a struct
/// return type, except, instead of printing the type as void (*)(Struct*, ...)
/// print it as "Struct (*)(...)", for struct return functions.
void CWriter::printStructReturnPointerFunctionType(llvm::raw_ostream &Out,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
const llvm::AttrListPtr &PAL,
#else // LLVM 3.3+
const llvm::AttributeSet &PAL,
#endif
llvm::PointerType *TheTy) {
llvm::FunctionType *FTy = llvm::cast<llvm::FunctionType>(TheTy->getElementType());
std::string tstr;
llvm::raw_string_ostream FunctionInnards(tstr);
FunctionInnards << " (*) (";
bool PrintedType = false;
llvm::FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
llvm::Type *RetTy = llvm::cast<llvm::PointerType>(*I)->getElementType();
unsigned Idx = 1;
for (++I, ++Idx; I != E; ++I, ++Idx) {
if (PrintedType)
FunctionInnards << ", ";
llvm::Type *ArgTy = *I;
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::ByVal)) {
#else // LLVM 3.3+
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::ByVal)) {
#endif
assert(ArgTy->isPointerTy());
ArgTy = llvm::cast<llvm::PointerType>(ArgTy)->getElementType();
}
printType(FunctionInnards, ArgTy,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::SExt),
#else // LLVM 3.3+
PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::SExt),
#endif
"");
PrintedType = true;
}
if (FTy->isVarArg()) {
if (!PrintedType)
FunctionInnards << " int"; //dummy argument for empty vararg functs
FunctionInnards << ", ...";
} else if (!PrintedType) {
FunctionInnards << "void";
}
FunctionInnards << ')';
printType(Out, RetTy,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
PAL.getParamAttributes(0).hasAttribute(llvm::Attributes::SExt),
#else // LLVM 3.3+
PAL.getParamAttributes(0).hasAttribute(llvm::AttributeSet::ReturnIndex, llvm::Attribute::SExt),
#endif
FunctionInnards.str());
}
llvm::raw_ostream &
CWriter::printSimpleType(llvm::raw_ostream &Out, llvm::Type *Ty, bool isSigned,
const std::string &NameSoFar) {
assert((Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() || Ty->isVectorTy() || Ty->isVoidTy()) &&
"Invalid type for printSimpleType");
switch (Ty->getTypeID()) {
case llvm::Type::VoidTyID: return Out << "void " << NameSoFar;
case llvm::Type::IntegerTyID: {
unsigned NumBits = llvm::cast<llvm::IntegerType>(Ty)->getBitWidth();
if (NumBits == 1)
return Out << "bool " << NameSoFar;
else if (NumBits <= 8)
return Out << (isSigned?"":"u") << "int8_t " << NameSoFar;
else if (NumBits <= 16)
return Out << (isSigned?"":"u") << "int16_t " << NameSoFar;
else if (NumBits <= 32)
return Out << (isSigned?"":"u") << "int32_t " << NameSoFar;
else if (NumBits <= 64)
return Out << (isSigned?"":"u") << "int64_t "<< NameSoFar;
else
return Out << "iN<" << NumBits << "> " << NameSoFar;
}
case llvm::Type::FloatTyID: return Out << "float " << NameSoFar;
case llvm::Type::DoubleTyID: return Out << "double " << NameSoFar;
// Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
// present matches host 'long double'.
case llvm::Type::X86_FP80TyID:
case llvm::Type::PPC_FP128TyID:
case llvm::Type::FP128TyID: return Out << "long double " << NameSoFar;
case llvm::Type::X86_MMXTyID:
return printSimpleType(Out, llvm::Type::getInt32Ty(Ty->getContext()), isSigned,
" __attribute__((vector_size(64))) " + NameSoFar);
case llvm::Type::VectorTyID: {
llvm::VectorType *VTy = llvm::cast<llvm::VectorType>(Ty);
#if 1
const char *suffix = NULL;
const llvm::Type *eltTy = VTy->getElementType();
if (eltTy->isFloatTy())
suffix = "f";
else if (eltTy->isDoubleTy())
suffix = "d";
else {
assert(eltTy->isIntegerTy());
switch (eltTy->getPrimitiveSizeInBits()) {
case 1:
suffix = "i1";
break;
case 8:
suffix = "i8";
break;
case 16:
suffix = "i16";
break;
case 32:
suffix = "i32";
break;
case 64:
suffix = "i64";
break;
default:
suffix = "iN";
break;
}
}
return Out << "__vec" << VTy->getNumElements() << "_" << suffix << " " <<
NameSoFar;
#else
return printSimpleType(Out, VTy->getElementType(), isSigned,
" __attribute__((vector_size(" +
utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
#endif
}
default:
#ifndef NDEBUG
llvm::errs() << "Unknown primitive type: " << *Ty << "\n";
#endif
llvm_unreachable(0);
}
}
// Pass the Type* and the variable name and this prints out the variable
// declaration.
//
llvm::raw_ostream &CWriter::printType(llvm::raw_ostream &Out, llvm::Type *Ty,
bool isSigned, const std::string &NameSoFar,
bool IgnoreName,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
const llvm::AttrListPtr &PAL
#else /* LLVM 3.3+ */
const llvm::AttributeSet &PAL
#endif
) {
if (Ty->isFloatingPointTy() || Ty->isX86_MMXTy() || Ty->isIntegerTy() || Ty->isVectorTy() || Ty->isVoidTy()) {
printSimpleType(Out, Ty, isSigned, NameSoFar);
return Out;
}
switch (Ty->getTypeID()) {
case llvm::Type::FunctionTyID: {
llvm::FunctionType *FTy = llvm::cast<llvm::FunctionType>(Ty);
std::string tstr;
llvm::raw_string_ostream FunctionInnards(tstr);
FunctionInnards << " (" << NameSoFar << ") (";
unsigned Idx = 1;
for (llvm::FunctionType::param_iterator I = FTy->param_begin(),
E = FTy->param_end(); I != E; ++I) {
llvm::Type *ArgTy = *I;
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::ByVal)) {
#else /* LLVM 3.3+ */
if (PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::ByVal)) {
#endif
assert(ArgTy->isPointerTy());
ArgTy = llvm::cast<llvm::PointerType>(ArgTy)->getElementType();
}
if (I != FTy->param_begin())
FunctionInnards << ", ";
printType(FunctionInnards, ArgTy,
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
PAL.getParamAttributes(Idx).hasAttribute(llvm::Attributes::SExt),
#else /* LLVM 3.3+ */
PAL.getParamAttributes(Idx).hasAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::SExt),
#endif
"");
++Idx;
}
if (FTy->isVarArg()) {
if (!FTy->getNumParams())
FunctionInnards << " int"; //dummy argument for empty vaarg functs
FunctionInnards << ", ...";
} else if (!FTy->getNumParams()) {
FunctionInnards << "void";
}
FunctionInnards << ')';
printType(Out, FTy->getReturnType(),
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
PAL.getParamAttributes(0).hasAttribute(llvm::Attributes::SExt),
#else /* LLVM 3.3+ */
PAL.getParamAttributes(0).hasAttribute(llvm::AttributeSet::ReturnIndex, llvm::Attribute::SExt),
#endif
FunctionInnards.str());
return Out;
}
case llvm::Type::StructTyID: {
llvm::StructType *STy = llvm::cast<llvm::StructType>(Ty);
// Check to see if the type is named.
if (!IgnoreName)
return Out << getStructName(STy) << ' ' << NameSoFar;
Out << "struct " << NameSoFar << " {\n";
// print initialization func
if (STy->getNumElements() > 0) {
Out << " static " << NameSoFar << " init(";
unsigned Idx = 0;
for (llvm::StructType::element_iterator I = STy->element_begin(),
E = STy->element_end(); I != E; ++I, ++Idx) {
char buf[64];
sprintf(buf, "v%d", Idx);