Added copyright header to all C++ source files.
[oota-llvm.git] / tools / bugpoint / CodeGeneratorBug.cpp
1 //===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 //
11 // This file implements program code generation debugging support.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "ListReducer.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/GlobalValue.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iOther.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/Verifier.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/Linker.h"
30 #include "Support/CommandLine.h"
31 #include "Support/Debug.h"
32 #include "Support/StringExtras.h"
33 #include "Support/FileUtilities.h"
34 #include <algorithm>
35 #include <set>
36
37 extern cl::list<std::string> InputArgv;
38
39 class ReduceMisCodegenFunctions : public ListReducer<Function*> {
40   BugDriver &BD;
41 public:
42   ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
43
44   virtual TestResult doTest(std::vector<Function*> &Prefix,
45                             std::vector<Function*> &Suffix) {
46     if (!Prefix.empty() && TestFuncs(Prefix))
47       return KeepPrefix;
48     if (!Suffix.empty() && TestFuncs(Suffix))
49       return KeepSuffix;
50     return NoFailure;
51   }
52   
53   bool TestFuncs(const std::vector<Function*> &CodegenTest,
54                  bool KeepFiles = false);
55 };
56
57
58 bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
59                                           bool KeepFiles) {
60   std::cout << "Testing functions: ";
61   BD.PrintFunctionList(Funcs);
62   std::cout << "\t";
63
64   // Clone the module for the two halves of the program we want.
65   Module *SafeModule = CloneModule(BD.Program);
66
67   // Make sure functions & globals are all external so that linkage
68   // between the two modules will work.
69   for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
70     I->setLinkage(GlobalValue::ExternalLinkage);
71   for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
72     I->setLinkage(GlobalValue::ExternalLinkage);
73
74   Module *TestModule = CloneModule(SafeModule);
75
76   // Make sure global initializers exist only in the safe module (CBE->.so)
77   for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
78     I->setInitializer(0);  // Delete the initializer to make it external
79
80   // Remove the Test functions from the Safe module
81   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
82     Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
83                                              Funcs[i]->getFunctionType());
84     DEBUG(std::cerr << "Removing function " << Funcs[i]->getName() << "\n");
85     assert(TNOF && "Function doesn't exist in module!");
86     DeleteFunctionBody(TNOF);       // Function is now external in this module!
87   }
88
89   // Remove the Safe functions from the Test module
90   for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {
91     bool funcFound = false;
92     for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();
93          F != Fe; ++F)
94       if (I->getName() == (*F)->getName()) funcFound = true;
95
96     if (!funcFound && !(BD.isExecutingJIT() && I->getName() == "main"))
97       DeleteFunctionBody(I);
98   }
99
100   // This is only applicable if we are debugging the JIT:
101   // Find all external functions in the Safe modules that are actually used
102   // (called or taken address of), and make them call the JIT wrapper instead
103   if (BD.isExecutingJIT()) {
104     // Must delete `main' from Safe module if it has it
105     Function *safeMain = SafeModule->getNamedFunction("main");
106     assert(safeMain && "`main' function not found in safe module!");
107     DeleteFunctionBody(safeMain);
108
109     // Add an external function "getPointerToNamedFunction" that JIT provides
110     // Prototype: void *getPointerToNamedFunction(const char* Name)
111     std::vector<const Type*> Params;
112     Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
113     FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
114                                                  Params, false /* isVarArg */);
115     Function *resolverFunc = new Function(resolverTy,
116                                           GlobalValue::ExternalLinkage,
117                                           "getPointerToNamedFunction",
118                                           SafeModule);
119
120     // Use the function we just added to get addresses of functions we need
121     // Iterate over the global declarations in the Safe module
122     for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
123       if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
124           F->getIntrinsicID() == 0 /* ignore intrinsics */ &&
125           // Don't forward functions which are external in the test module too.
126           !TestModule->getNamedFunction(F->getName())->isExternal()) {
127         // If it has a non-zero use list,
128         // 1. Add a string constant with its name to the global file
129         // The correct type is `const [ NUM x sbyte ]' where NUM is length of
130         // function name + 1
131         const std::string &Name = F->getName();
132         GlobalVariable *funcName =
133           new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
134                              true /* isConstant */,
135                              GlobalValue::InternalLinkage,
136                              ConstantArray::get(Name),
137                              Name + "_name",
138                              SafeModule);
139
140         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
141         // sbyte* so it matches the signature of the resolver function.
142         std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::LongTy));
143
144         // 3. Replace all uses of `func' with calls to resolver by:
145         // (a) Iterating through the list of uses of this function
146         // (b) Insert a cast instruction in front of each use
147         // (c) Replace use of old call with new call
148
149         // GetElementPtr *funcName, ulong 0, ulong 0
150         Value *GEP =
151           ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
152                                          GEPargs);
153         std::vector<Value*> ResolverArgs;
154         ResolverArgs.push_back(GEP);
155
156         // Insert code at the beginning of the function
157         while (!F->use_empty())
158           if (Instruction *Inst = dyn_cast<Instruction>(F->use_back())) {
159             // call resolver(GetElementPtr...)
160             CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, 
161                                              "resolver", Inst);
162             // cast the result from the resolver to correctly-typed function
163             CastInst *castResolver =
164               new CastInst(resolve, PointerType::get(F->getFunctionType()),
165                            "resolverCast", Inst);
166             // actually use the resolved function
167             Inst->replaceUsesOfWith(F, castResolver);
168           } else {
169             // FIXME: need to take care of cases where a function is used that
170             // is not an instruction, e.g. global variable initializer...
171             std::cerr << "Non-instruction is using an external function!\n";
172             abort();
173           }
174       }
175     }
176   }
177
178   if (verifyModule(*SafeModule) || verifyModule(*TestModule)) {
179     std::cerr << "Bugpoint has a bug, an corrupted a module!!\n";
180     abort();
181   }
182
183   DEBUG(std::cerr << "Safe module:\n";
184         typedef Module::iterator MI;
185         typedef Module::giterator MGI;
186
187         for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
188           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
189         for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
190           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
191
192         std::cerr << "Test module:\n";
193         for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
194           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
195         for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
196           if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
197         );
198
199   // Write out the bytecode to be sent to CBE
200   std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
201
202   if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
203     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
204     exit(1);
205   }
206
207   // Remove all functions from the Test module EXCEPT for the ones specified in
208   // Funcs.  We know which ones these are because they are non-external in
209   // ToOptimize, but external in ToNotOptimize.
210   //
211   for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
212     if (!I->isExternal()) {
213       Function *TNOF = SafeModule->getFunction(I->getName(),
214                                                I->getFunctionType());
215       assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
216       if (!TNOF->isExternal())
217         DeleteFunctionBody(I);
218     }
219
220   std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
221   if (verifyModule(*TestModule)) {
222     std::cerr << "Bytecode file corrupted!\n";
223     exit(1);
224   }
225
226   // Clean up the modules, removing extra cruft that we don't need anymore...
227   SafeModule = BD.performFinalCleanups(SafeModule);
228   TestModule = BD.performFinalCleanups(TestModule);
229
230   if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
231     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
232     exit(1);
233   }
234
235   // Make a shared library
236   std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
237
238   delete SafeModule;
239   delete TestModule;
240
241   // Run the code generator on the `Test' code, loading the shared library.
242   // The function returns whether or not the new output differs from reference.
243   int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
244
245   if (Result)
246     std::cerr << ": still failing!\n";
247   else
248     std::cerr << ": didn't fail.\n";
249     
250   if (KeepFiles) {
251     std::cout << "You can reproduce the problem with the command line: \n";
252     if (BD.isExecutingJIT()) {
253       std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
254     } else {
255       std::cout << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
256       std::cout << "  gcc " << SharedObject << " " << TestModuleBC
257                 << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
258       std::cout << "  " << TestModuleBC << ".exe";
259     }
260     for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
261       std::cout << " " << InputArgv[i];
262     std::cout << "\n";
263     std::cout << "The shared object was created with:\n  llvm-dis -c "
264               << SafeModuleBC << " -o temporary.c\n"
265               << "  gcc -xc temporary.c -O2 -o " << SharedObject
266 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
267               << " -G"            // Compile a shared library, `-G' for Sparc
268 #else
269               << " -shared"       // `-shared' for Linux/X86, maybe others
270 #endif
271               << " -fno-strict-aliasing\n";
272   } else {
273     removeFile(TestModuleBC);
274     removeFile(SafeModuleBC);
275     removeFile(SharedObject);
276   }
277   return Result;
278 }
279
280 namespace {
281   struct Disambiguator {
282     std::set<std::string>  SymbolNames;
283     std::set<GlobalValue*> Symbols;
284     uint64_t uniqueCounter;
285     bool externalOnly;
286   public:
287     Disambiguator() : uniqueCounter(0), externalOnly(true) {}
288     void setExternalOnly(bool value) { externalOnly = value; }
289     void add(GlobalValue &V) {
290       // If we're only processing externals and this isn't external, bail
291       if (externalOnly && !V.isExternal()) return;
292       // If we're already processed this symbol, don't add it again
293       if (Symbols.count(&V) != 0) return;
294       // Ignore intrinsic functions
295       if (Function *F = dyn_cast<Function>(&V))
296         if (F->getIntrinsicID() != 0)
297           return;
298
299       std::string SymName = V.getName();
300
301       // Use the Mangler facility to make symbol names that will be valid in
302       // shared objects.
303       SymName = Mangler::makeNameProper(SymName);
304       V.setName(SymName);
305
306       if (SymbolNames.count(SymName) == 0) {
307         DEBUG(std::cerr << "Disambiguator: adding " << SymName
308                         << ", no conflicts.\n");
309         SymbolNames.insert(SymName);
310       } else { 
311         // Mangle name before adding
312         std::string newName;
313         do {
314           newName = SymName + "_" + utostr(uniqueCounter);
315           if (SymbolNames.count(newName) == 0) break;
316           else ++uniqueCounter;
317         } while (1);
318         //while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
319         DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
320                         << ", adding: " << newName << "\n");
321         V.setName(newName);
322         SymbolNames.insert(newName);
323       }
324       Symbols.insert(&V);
325     }
326   };
327 }
328
329 void DisambiguateGlobalSymbols(Module *M) {
330   // First, try not to cause collisions by minimizing chances of renaming an
331   // already-external symbol, so take in external globals and functions as-is.
332   Disambiguator D;
333   DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
334   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
335   DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
336   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I) D.add(*I);
337
338   // Now just rename functions and globals as necessary, keeping what's already
339   // in the set unique.
340   D.setExternalOnly(false);
341   DEBUG(std::cerr << "Disambiguating globals\n");
342   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
343   DEBUG(std::cerr << "Disambiguating globals\n");
344   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I) D.add(*I);
345 }
346
347
348 bool BugDriver::debugCodeGenerator() {
349   // See if we can pin down which functions are being miscompiled...
350   //First, build a list of all of the non-external functions in the program.
351   std::vector<Function*> MisCodegenFunctions;
352   for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
353     if (!I->isExternal())
354       MisCodegenFunctions.push_back(I);
355
356   // If we are executing the JIT, we *must* keep the function `main' in the
357   // module that is passed in, and not the shared library. However, we still
358   // want to be able to debug the `main' function alone. Thus, we create a new
359   // function `main' which just calls the old one.
360   if (isExecutingJIT()) {
361     // Get the `main' function
362     Function *oldMain = Program->getNamedFunction("main");
363     assert(oldMain && "`main' function not found in program!");
364     // Rename it
365     oldMain->setName("llvm_old_main");
366     // Create a NEW `main' function with same type
367     Function *newMain = new Function(oldMain->getFunctionType(), 
368                                      GlobalValue::ExternalLinkage,
369                                      "main", Program);
370     // Call the old main function and return its result
371     BasicBlock *BB = new BasicBlock("entry", newMain);
372     std::vector<Value*> args;
373     for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
374            OI = oldMain->abegin(); I != E; ++I, ++OI) {
375       I->setName(OI->getName());    // Copy argument names from oldMain
376       args.push_back(I);
377     }
378     CallInst *call = new CallInst(oldMain, args);
379     BB->getInstList().push_back(call);
380     
381     // if the type of old function wasn't void, return value of call
382     ReturnInst *ret;
383     if (oldMain->getReturnType() != Type::VoidTy) {
384       ret = new ReturnInst(call);
385     } else {
386       ret = new ReturnInst();
387     }
388
389     // Add the return instruction to the BasicBlock
390     BB->getInstList().push_back(ret);
391   }
392
393   DisambiguateGlobalSymbols(Program);
394
395   // Do the reduction...
396   if (!ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions)) {
397     std::cerr << "*** Execution matches reference output! "
398               << "bugpoint can't help you with your problem!\n";
399     return false;
400   }
401
402   std::cout << "\n*** The following functions are being miscompiled: ";
403   PrintFunctionList(MisCodegenFunctions);
404   std::cout << "\n";
405
406   // Output a bunch of bytecode files for the user...
407   ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
408
409   return false;
410 }