5b5955d7c2bcccc92c1d09d375a03b1241020385
[oota-llvm.git] / lib / VMCore / AutoUpgrade.cpp
1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
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 file implements the auto-upgrade helper functions 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Module.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/IRBuilder.h"
24 #include <cstring>
25 using namespace llvm;
26
27
28 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
29   assert(F && "Illegal to upgrade a non-existent Function.");
30
31   // Get the Function's name.
32   const std::string& Name = F->getName();
33
34   // Convenience
35   const FunctionType *FTy = F->getFunctionType();
36
37   // Quickly eliminate it, if it's not a candidate.
38   if (Name.length() <= 8 || Name[0] != 'l' || Name[1] != 'l' || 
39       Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
40     return false;
41
42   Module *M = F->getParent();
43   switch (Name[5]) {
44   default: break;
45   case 'a':
46     // This upgrades the llvm.atomic.lcs, llvm.atomic.las, llvm.atomic.lss,
47     // and atomics with default address spaces to their new names to their new
48     // function name (e.g. llvm.atomic.add.i32 => llvm.atomic.add.i32.p0i32)
49     if (Name.compare(5,7,"atomic.",7) == 0) {
50       if (Name.compare(12,3,"lcs",3) == 0) {
51         std::string::size_type delim = Name.find('.',12);
52         F->setName("llvm.atomic.cmp.swap" + Name.substr(delim) +
53                    ".p0" + Name.substr(delim+1));
54         NewFn = F;
55         return true;
56       }
57       else if (Name.compare(12,3,"las",3) == 0) {
58         std::string::size_type delim = Name.find('.',12);
59         F->setName("llvm.atomic.load.add"+Name.substr(delim)
60                    + ".p0" + Name.substr(delim+1));
61         NewFn = F;
62         return true;
63       }
64       else if (Name.compare(12,3,"lss",3) == 0) {
65         std::string::size_type delim = Name.find('.',12);
66         F->setName("llvm.atomic.load.sub"+Name.substr(delim)
67                    + ".p0" + Name.substr(delim+1));
68         NewFn = F;
69         return true;
70       }
71       else if (Name.rfind(".p") == std::string::npos) {
72         // We don't have an address space qualifier so this has be upgraded
73         // to the new name.  Copy the type name at the end of the intrinsic
74         // and add to it
75         std::string::size_type delim = Name.find_last_of('.');
76         assert(delim != std::string::npos && "can not find type");
77         F->setName(Name + ".p0" + Name.substr(delim+1));
78         NewFn = F;
79         return true;
80       }
81     } else if (Name.compare(5, 9, "arm.neon.", 9) == 0) {
82       if (((Name.compare(14, 5, "vmovl", 5) == 0 ||
83             Name.compare(14, 5, "vaddl", 5) == 0 ||
84             Name.compare(14, 5, "vsubl", 5) == 0 ||
85             Name.compare(14, 5, "vaddw", 5) == 0 ||
86             Name.compare(14, 5, "vsubw", 5) == 0 ||
87             Name.compare(14, 5, "vmull", 5) == 0 ||
88             Name.compare(14, 5, "vmlal", 5) == 0 ||
89             Name.compare(14, 5, "vmlsl", 5) == 0 ||
90             Name.compare(14, 5, "vabdl", 5) == 0 ||
91             Name.compare(14, 5, "vabal", 5) == 0) &&
92            (Name.compare(19, 2, "s.", 2) == 0 ||
93             Name.compare(19, 2, "u.", 2) == 0)) ||
94
95           (Name.compare(14, 4, "vaba", 4) == 0 &&
96            (Name.compare(18, 2, "s.", 2) == 0 ||
97             Name.compare(18, 2, "u.", 2) == 0)) ||
98
99           (Name.compare(14, 6, "vmovn.", 6) == 0)) {
100
101         // Calls to these are transformed into IR without intrinsics.
102         NewFn = 0;
103         return true;
104       }
105       // Old versions of NEON ld/st intrinsics are missing alignment arguments.
106       bool isVLd = (Name.compare(14, 3, "vld", 3) == 0);
107       bool isVSt = (Name.compare(14, 3, "vst", 3) == 0);
108       if (isVLd || isVSt) {
109         unsigned NumVecs = Name.at(17) - '0';
110         if (NumVecs == 0 || NumVecs > 4)
111           return false;
112         bool isLaneOp = (Name.compare(18, 5, "lane.", 5) == 0);
113         if (!isLaneOp && Name.at(18) != '.')
114           return false;
115         unsigned ExpectedArgs = 2; // for the address and alignment
116         if (isVSt || isLaneOp)
117           ExpectedArgs += NumVecs;
118         if (isLaneOp)
119           ExpectedArgs += 1; // for the lane number
120         unsigned NumP = FTy->getNumParams();
121         if (NumP != ExpectedArgs - 1)
122           return false;
123
124         // Change the name of the old (bad) intrinsic, because 
125         // its type is incorrect, but we cannot overload that name.
126         F->setName("");
127
128         // One argument is missing: add the alignment argument.
129         std::vector<const Type*> NewParams;
130         for (unsigned p = 0; p < NumP; ++p)
131           NewParams.push_back(FTy->getParamType(p));
132         NewParams.push_back(Type::getInt32Ty(F->getContext()));
133         FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(),
134                                                  NewParams, false);
135         NewFn = cast<Function>(M->getOrInsertFunction(Name, NewFTy));
136         return true;
137       }
138     }
139     break;
140   case 'b':
141     //  This upgrades the name of the llvm.bswap intrinsic function to only use 
142     //  a single type name for overloading. We only care about the old format
143     //  'llvm.bswap.i*.i*', so check for 'bswap.' and then for there being 
144     //  a '.' after 'bswap.'
145     if (Name.compare(5,6,"bswap.",6) == 0) {
146       std::string::size_type delim = Name.find('.',11);
147       
148       if (delim != std::string::npos) {
149         //  Construct the new name as 'llvm.bswap' + '.i*'
150         F->setName(Name.substr(0,10)+Name.substr(delim));
151         NewFn = F;
152         return true;
153       }
154     }
155     break;
156
157   case 'c':
158     //  We only want to fix the 'llvm.ct*' intrinsics which do not have the 
159     //  correct return type, so we check for the name, and then check if the 
160     //  return type does not match the parameter type.
161     if ( (Name.compare(5,5,"ctpop",5) == 0 ||
162           Name.compare(5,4,"ctlz",4) == 0 ||
163           Name.compare(5,4,"cttz",4) == 0) &&
164         FTy->getReturnType() != FTy->getParamType(0)) {
165       //  We first need to change the name of the old (bad) intrinsic, because 
166       //  its type is incorrect, but we cannot overload that name. We 
167       //  arbitrarily unique it here allowing us to construct a correctly named 
168       //  and typed function below.
169       F->setName("");
170
171       //  Now construct the new intrinsic with the correct name and type. We 
172       //  leave the old function around in order to query its type, whatever it 
173       //  may be, and correctly convert up to the new type.
174       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
175                                                     FTy->getParamType(0),
176                                                     FTy->getParamType(0),
177                                                     (Type *)0));
178       return true;
179     }
180     break;
181
182   case 'e':
183     //  The old llvm.eh.selector.i32 is equivalent to the new llvm.eh.selector.
184     if (Name.compare("llvm.eh.selector.i32") == 0) {
185       F->setName("llvm.eh.selector");
186       NewFn = F;
187       return true;
188     }
189     //  The old llvm.eh.typeid.for.i32 is equivalent to llvm.eh.typeid.for.
190     if (Name.compare("llvm.eh.typeid.for.i32") == 0) {
191       F->setName("llvm.eh.typeid.for");
192       NewFn = F;
193       return true;
194     }
195     //  Convert the old llvm.eh.selector.i64 to a call to llvm.eh.selector.
196     if (Name.compare("llvm.eh.selector.i64") == 0) {
197       NewFn = Intrinsic::getDeclaration(M, Intrinsic::eh_selector);
198       return true;
199     }
200     //  Convert the old llvm.eh.typeid.for.i64 to a call to llvm.eh.typeid.for.
201     if (Name.compare("llvm.eh.typeid.for.i64") == 0) {
202       NewFn = Intrinsic::getDeclaration(M, Intrinsic::eh_typeid_for);
203       return true;
204     }
205     break;
206
207   case 'm': {
208     // This upgrades the llvm.memcpy, llvm.memmove, and llvm.memset to the
209     // new format that allows overloading the pointer for different address
210     // space (e.g., llvm.memcpy.i16 => llvm.memcpy.p0i8.p0i8.i16)
211     const char* NewFnName = NULL;
212     if (Name.compare(5,8,"memcpy.i",8) == 0) {
213       if (Name[13] == '8')
214         NewFnName = "llvm.memcpy.p0i8.p0i8.i8";
215       else if (Name.compare(13,2,"16") == 0)
216         NewFnName = "llvm.memcpy.p0i8.p0i8.i16";
217       else if (Name.compare(13,2,"32") == 0)
218         NewFnName = "llvm.memcpy.p0i8.p0i8.i32";
219       else if (Name.compare(13,2,"64") == 0)
220         NewFnName = "llvm.memcpy.p0i8.p0i8.i64";
221     } else if (Name.compare(5,9,"memmove.i",9) == 0) {
222       if (Name[14] == '8')
223         NewFnName = "llvm.memmove.p0i8.p0i8.i8";
224       else if (Name.compare(14,2,"16") == 0)
225         NewFnName = "llvm.memmove.p0i8.p0i8.i16";
226       else if (Name.compare(14,2,"32") == 0)
227         NewFnName = "llvm.memmove.p0i8.p0i8.i32";
228       else if (Name.compare(14,2,"64") == 0)
229         NewFnName = "llvm.memmove.p0i8.p0i8.i64";
230     }
231     else if (Name.compare(5,8,"memset.i",8) == 0) {
232       if (Name[13] == '8')
233         NewFnName = "llvm.memset.p0i8.i8";
234       else if (Name.compare(13,2,"16") == 0)
235         NewFnName = "llvm.memset.p0i8.i16";
236       else if (Name.compare(13,2,"32") == 0)
237         NewFnName = "llvm.memset.p0i8.i32";
238       else if (Name.compare(13,2,"64") == 0)
239         NewFnName = "llvm.memset.p0i8.i64";
240     }
241     if (NewFnName) {
242       NewFn = cast<Function>(M->getOrInsertFunction(NewFnName, 
243                                             FTy->getReturnType(),
244                                             FTy->getParamType(0),
245                                             FTy->getParamType(1),
246                                             FTy->getParamType(2),
247                                             FTy->getParamType(3),
248                                             Type::getInt1Ty(F->getContext()),
249                                             (Type *)0));
250       return true;
251     }
252     break;
253   }
254   case 'p':
255     //  This upgrades the llvm.part.select overloaded intrinsic names to only 
256     //  use one type specifier in the name. We only care about the old format
257     //  'llvm.part.select.i*.i*', and solve as above with bswap.
258     if (Name.compare(5,12,"part.select.",12) == 0) {
259       std::string::size_type delim = Name.find('.',17);
260       
261       if (delim != std::string::npos) {
262         //  Construct a new name as 'llvm.part.select' + '.i*'
263         F->setName(Name.substr(0,16)+Name.substr(delim));
264         NewFn = F;
265         return true;
266       }
267       break;
268     }
269
270     //  This upgrades the llvm.part.set intrinsics similarly as above, however 
271     //  we care about 'llvm.part.set.i*.i*.i*', but only the first two types 
272     //  must match. There is an additional type specifier after these two 
273     //  matching types that we must retain when upgrading.  Thus, we require 
274     //  finding 2 periods, not just one, after the intrinsic name.
275     if (Name.compare(5,9,"part.set.",9) == 0) {
276       std::string::size_type delim = Name.find('.',14);
277
278       if (delim != std::string::npos &&
279           Name.find('.',delim+1) != std::string::npos) {
280         //  Construct a new name as 'llvm.part.select' + '.i*.i*'
281         F->setName(Name.substr(0,13)+Name.substr(delim));
282         NewFn = F;
283         return true;
284       }
285       break;
286     }
287
288     break;
289   case 'x': 
290     // This fixes all MMX shift intrinsic instructions to take a
291     // x86_mmx instead of a v1i64, v2i32, v4i16, or v8i8.
292     if (Name.compare(5, 8, "x86.mmx.", 8) == 0) {
293       const Type *X86_MMXTy = VectorType::getX86_MMXTy(FTy->getContext());
294
295       if (Name.compare(13, 4, "padd", 4) == 0   ||
296           Name.compare(13, 4, "psub", 4) == 0   ||
297           Name.compare(13, 4, "pmul", 4) == 0   ||
298           Name.compare(13, 5, "pmadd", 5) == 0  ||
299           Name.compare(13, 4, "pand", 4) == 0   ||
300           Name.compare(13, 3, "por", 3) == 0    ||
301           Name.compare(13, 4, "pxor", 4) == 0   ||
302           Name.compare(13, 4, "pavg", 4) == 0   ||
303           Name.compare(13, 4, "pmax", 4) == 0   ||
304           Name.compare(13, 4, "pmin", 4) == 0   ||
305           Name.compare(13, 4, "psad", 4) == 0   ||
306           Name.compare(13, 4, "psll", 4) == 0   ||
307           Name.compare(13, 4, "psrl", 4) == 0   ||
308           Name.compare(13, 4, "psra", 4) == 0   ||
309           Name.compare(13, 4, "pack", 4) == 0   ||
310           Name.compare(13, 6, "punpck", 6) == 0 ||
311           Name.compare(13, 4, "pcmp", 4) == 0) {
312         assert(FTy->getNumParams() == 2 && "MMX intrinsic takes 2 args!");
313         const Type *SecondParamTy = X86_MMXTy;
314
315         if (Name.compare(13, 5, "pslli", 5) == 0 ||
316             Name.compare(13, 5, "psrli", 5) == 0 ||
317             Name.compare(13, 5, "psrai", 5) == 0)
318           SecondParamTy = FTy->getParamType(1);
319
320         // Don't do anything if it has the correct types.
321         if (FTy->getReturnType() == X86_MMXTy &&
322             FTy->getParamType(0) == X86_MMXTy &&
323             FTy->getParamType(1) == SecondParamTy)
324           break;
325
326         // We first need to change the name of the old (bad) intrinsic, because
327         // its type is incorrect, but we cannot overload that name. We
328         // arbitrarily unique it here allowing us to construct a correctly named
329         // and typed function below.
330         F->setName("");
331
332         // Now construct the new intrinsic with the correct name and type. We
333         // leave the old function around in order to query its type, whatever it
334         // may be, and correctly convert up to the new type.
335         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
336                                                       X86_MMXTy, X86_MMXTy,
337                                                       SecondParamTy, (Type*)0));
338         return true;
339       }
340
341       if (Name.compare(13, 8, "maskmovq", 8) == 0) {
342         // Don't do anything if it has the correct types.
343         if (FTy->getParamType(0) == X86_MMXTy &&
344             FTy->getParamType(1) == X86_MMXTy)
345           break;
346
347         F->setName("");
348         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
349                                                       FTy->getReturnType(),
350                                                       X86_MMXTy,
351                                                       X86_MMXTy,
352                                                       FTy->getParamType(2),
353                                                       (Type*)0));
354         return true;
355       }
356
357       if (Name.compare(13, 8, "pmovmskb", 8) == 0) {
358         if (FTy->getParamType(0) == X86_MMXTy)
359           break;
360
361         F->setName("");
362         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
363                                                       FTy->getReturnType(),
364                                                       X86_MMXTy,
365                                                       (Type*)0));
366         return true;
367       }
368
369       if (Name.compare(13, 5, "movnt", 5) == 0) {
370         if (FTy->getParamType(1) == X86_MMXTy)
371           break;
372
373         F->setName("");
374         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
375                                                       FTy->getReturnType(),
376                                                       FTy->getParamType(0),
377                                                       X86_MMXTy,
378                                                       (Type*)0));
379         return true;
380       }
381
382       if (Name.compare(13, 7, "palignr", 7) == 0) {
383         if (FTy->getReturnType() == X86_MMXTy &&
384             FTy->getParamType(0) == X86_MMXTy &&
385             FTy->getParamType(1) == X86_MMXTy)
386           break;
387
388         F->setName("");
389         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
390                                                       X86_MMXTy,
391                                                       X86_MMXTy,
392                                                       X86_MMXTy,
393                                                       FTy->getParamType(2),
394                                                       (Type*)0));
395         return true;
396       }
397
398       if (Name.compare(13, 5, "pextr", 5) == 0) {
399         if (FTy->getParamType(0) == X86_MMXTy)
400           break;
401
402         F->setName("");
403         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
404                                                       FTy->getReturnType(),
405                                                       X86_MMXTy,
406                                                       FTy->getParamType(1),
407                                                       (Type*)0));
408         return true;
409       }
410
411       if (Name.compare(13, 5, "pinsr", 5) == 0) {
412         if (FTy->getReturnType() == X86_MMXTy &&
413             FTy->getParamType(0) == X86_MMXTy)
414           break;
415
416         F->setName("");
417         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
418                                                       X86_MMXTy,
419                                                       X86_MMXTy,
420                                                       FTy->getParamType(1),
421                                                       FTy->getParamType(2),
422                                                       (Type*)0));
423         return true;
424       }
425
426       if (Name.compare(13, 12, "cvtsi32.si64", 12) == 0) {
427         if (FTy->getReturnType() == X86_MMXTy)
428           break;
429
430         F->setName("");
431         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
432                                                       X86_MMXTy,
433                                                       FTy->getParamType(0),
434                                                       (Type*)0));
435         return true;
436       }
437
438       if (Name.compare(13, 12, "cvtsi64.si32", 12) == 0) {
439         if (FTy->getParamType(0) == X86_MMXTy)
440           break;
441
442         F->setName("");
443         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
444                                                       FTy->getReturnType(),
445                                                       X86_MMXTy,
446                                                       (Type*)0));
447         return true;
448       }
449
450       if (Name.compare(13, 8, "vec.init", 8) == 0) {
451         if (FTy->getReturnType() == X86_MMXTy)
452           break;
453
454         F->setName("");
455
456         if (Name.compare(21, 2, ".b", 2) == 0)
457           NewFn = cast<Function>(M->getOrInsertFunction(Name, 
458                                                         X86_MMXTy,
459                                                         FTy->getParamType(0),
460                                                         FTy->getParamType(1),
461                                                         FTy->getParamType(2),
462                                                         FTy->getParamType(3),
463                                                         FTy->getParamType(4),
464                                                         FTy->getParamType(5),
465                                                         FTy->getParamType(6),
466                                                         FTy->getParamType(7),
467                                                         (Type*)0));
468         else if (Name.compare(21, 2, ".w", 2) == 0)
469           NewFn = cast<Function>(M->getOrInsertFunction(Name, 
470                                                         X86_MMXTy,
471                                                         FTy->getParamType(0),
472                                                         FTy->getParamType(1),
473                                                         FTy->getParamType(2),
474                                                         FTy->getParamType(3),
475                                                         (Type*)0));
476         else if (Name.compare(21, 2, ".d", 2) == 0)
477           NewFn = cast<Function>(M->getOrInsertFunction(Name, 
478                                                         X86_MMXTy,
479                                                         FTy->getParamType(0),
480                                                         FTy->getParamType(1),
481                                                         (Type*)0));
482         return true;
483       }
484
485
486       if (Name.compare(13, 9, "vec.ext.d", 9) == 0) {
487         if (FTy->getReturnType() == X86_MMXTy &&
488             FTy->getParamType(0) == X86_MMXTy)
489           break;
490
491         F->setName("");
492         NewFn = cast<Function>(M->getOrInsertFunction(Name, 
493                                                       X86_MMXTy,
494                                                       X86_MMXTy,
495                                                       FTy->getParamType(1),
496                                                       (Type*)0));
497         return true;
498       }
499
500       if (Name.compare(13, 9, "emms", 4) == 0 ||
501           Name.compare(13, 9, "femms", 5) == 0) {
502         NewFn = 0;
503         break;
504       }
505
506       // We really shouldn't get here ever.
507       assert(0 && "Invalid MMX intrinsic!");
508       break;
509     } else if (Name.compare(5,17,"x86.sse2.loadh.pd",17) == 0 ||
510                Name.compare(5,17,"x86.sse2.loadl.pd",17) == 0 ||
511                Name.compare(5,16,"x86.sse2.movl.dq",16) == 0 ||
512                Name.compare(5,15,"x86.sse2.movs.d",15) == 0 ||
513                Name.compare(5,16,"x86.sse2.shuf.pd",16) == 0 ||
514                Name.compare(5,18,"x86.sse2.unpckh.pd",18) == 0 ||
515                Name.compare(5,18,"x86.sse2.unpckl.pd",18) == 0 ||
516                Name.compare(5,20,"x86.sse2.punpckh.qdq",20) == 0 ||
517                Name.compare(5,20,"x86.sse2.punpckl.qdq",20) == 0) {
518       // Calls to these intrinsics are transformed into ShuffleVector's.
519       NewFn = 0;
520       return true;
521     } else if (Name.compare(5, 16, "x86.sse41.pmulld", 16) == 0) {
522       // Calls to these intrinsics are transformed into vector multiplies.
523       NewFn = 0;
524       return true;
525     } else if (Name.compare(5, 18, "x86.ssse3.palign.r", 18) == 0 ||
526                Name.compare(5, 22, "x86.ssse3.palign.r.128", 22) == 0) {
527       // Calls to these intrinsics are transformed into vector shuffles, shifts,
528       // or 0.
529       NewFn = 0;
530       return true;           
531     }
532
533     break;
534   }
535
536   //  This may not belong here. This function is effectively being overloaded 
537   //  to both detect an intrinsic which needs upgrading, and to provide the 
538   //  upgraded form of the intrinsic. We should perhaps have two separate 
539   //  functions for this.
540   return false;
541 }
542
543 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
544   NewFn = 0;
545   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
546
547   // Upgrade intrinsic attributes.  This does not change the function.
548   if (NewFn)
549     F = NewFn;
550   if (unsigned id = F->getIntrinsicID())
551     F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
552   return Upgraded;
553 }
554
555 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
556   StringRef Name(GV->getName());
557
558   // We are only upgrading one symbol here.
559   if (Name == ".llvm.eh.catch.all.value") {
560     GV->setName("llvm.eh.catch.all.value");
561     return true;
562   }
563
564   return false;
565 }
566
567 /// ExtendNEONArgs - For NEON "long" and "wide" operations, where the results
568 /// have vector elements twice as big as one or both source operands, do the
569 /// sign- or zero-extension that used to be handled by intrinsics.  The
570 /// extended values are returned via V0 and V1.
571 static void ExtendNEONArgs(CallInst *CI, Value *Arg0, Value *Arg1,
572                            Value *&V0, Value *&V1) {
573   Function *F = CI->getCalledFunction();
574   const std::string& Name = F->getName();
575   bool isLong = (Name.at(18) == 'l');
576   bool isSigned = (Name.at(19) == 's');
577
578   if (isSigned) {
579     if (isLong)
580       V0 = new SExtInst(Arg0, CI->getType(), "", CI);
581     else
582       V0 = Arg0;
583     V1 = new SExtInst(Arg1, CI->getType(), "", CI);
584   } else {
585     if (isLong)
586       V0 = new ZExtInst(Arg0, CI->getType(), "", CI);
587     else
588       V0 = Arg0;
589     V1 = new ZExtInst(Arg1, CI->getType(), "", CI);
590   }
591 }
592
593 /// CallVABD - As part of expanding a call to one of the old NEON vabdl, vaba,
594 /// or vabal intrinsics, construct a call to a vabd intrinsic.  Examine the
595 /// name of the old intrinsic to determine whether to use a signed or unsigned
596 /// vabd intrinsic.  Get the type from the old call instruction, adjusted for
597 /// half-size vector elements if the old intrinsic was vabdl or vabal.
598 static Instruction *CallVABD(CallInst *CI, Value *Arg0, Value *Arg1) {
599   Function *F = CI->getCalledFunction();
600   const std::string& Name = F->getName();
601   bool isLong = (Name.at(18) == 'l');
602   bool isSigned = (Name.at(isLong ? 19 : 18) == 's');
603
604   Intrinsic::ID intID;
605   if (isSigned)
606     intID = Intrinsic::arm_neon_vabds;
607   else
608     intID = Intrinsic::arm_neon_vabdu;
609
610   const Type *Ty = CI->getType();
611   if (isLong)
612     Ty = VectorType::getTruncatedElementVectorType(cast<const VectorType>(Ty));
613
614   Function *VABD = Intrinsic::getDeclaration(F->getParent(), intID, &Ty, 1);
615   Value *Operands[2];
616   Operands[0] = Arg0;
617   Operands[1] = Arg1;
618   return CallInst::Create(VABD, Operands, Operands+2, 
619                           "upgraded."+CI->getName(), CI);
620 }
621
622 /// ConstructNewCallInst - Construct a new CallInst with the signature of NewFn.
623 static void ConstructNewCallInst(Function *NewFn, CallInst *OldCI,
624                                  Value **Operands, unsigned NumOps,
625                                  bool AssignName = true) {
626   // Construct a new CallInst.
627   CallInst *NewCI =
628     CallInst::Create(NewFn, Operands, Operands + NumOps,
629                      AssignName ? "upgraded." + OldCI->getName() : "", OldCI);
630
631   NewCI->setTailCall(OldCI->isTailCall());
632   NewCI->setCallingConv(OldCI->getCallingConv());
633
634   // Handle any uses of the old CallInst.
635   if (!OldCI->use_empty()) {
636     // If the type has changed, add a cast.
637     Instruction *I = OldCI;
638     if (OldCI->getType() != NewCI->getType()) {
639       Function *OldFn = OldCI->getCalledFunction();
640       CastInst *RetCast =
641         CastInst::Create(CastInst::getCastOpcode(NewCI, true,
642                                                  OldFn->getReturnType(), true),
643                          NewCI, OldFn->getReturnType(), NewCI->getName(),OldCI);
644       I = RetCast;
645     }
646     // Replace all uses of the old call with the new cast which has the 
647     // correct type.
648     OldCI->replaceAllUsesWith(I);
649   }
650   // Clean up the old call now that it has been completely upgraded.
651   OldCI->eraseFromParent();
652 }
653
654 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the 
655 // upgraded intrinsic. All argument and return casting must be provided in 
656 // order to seamlessly integrate with existing context.
657 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
658   Function *F = CI->getCalledFunction();
659   LLVMContext &C = CI->getContext();
660   ImmutableCallSite CS(CI);
661
662   assert(F && "CallInst has no function associated with it.");
663
664   if (!NewFn) {
665     // Get the Function's name.
666     const std::string& Name = F->getName();
667
668     // Upgrade ARM NEON intrinsics.
669     if (Name.compare(5, 9, "arm.neon.", 9) == 0) {
670       Instruction *NewI;
671       Value *V0, *V1;
672       if (Name.compare(14, 7, "vmovls.", 7) == 0) {
673         NewI = new SExtInst(CI->getArgOperand(0), CI->getType(),
674                             "upgraded." + CI->getName(), CI);
675       } else if (Name.compare(14, 7, "vmovlu.", 7) == 0) {
676         NewI = new ZExtInst(CI->getArgOperand(0), CI->getType(),
677                             "upgraded." + CI->getName(), CI);
678       } else if (Name.compare(14, 4, "vadd", 4) == 0) {
679         ExtendNEONArgs(CI, CI->getArgOperand(0), CI->getArgOperand(1), V0, V1);
680         NewI = BinaryOperator::CreateAdd(V0, V1, "upgraded."+CI->getName(), CI);
681       } else if (Name.compare(14, 4, "vsub", 4) == 0) {
682         ExtendNEONArgs(CI, CI->getArgOperand(0), CI->getArgOperand(1), V0, V1);
683         NewI = BinaryOperator::CreateSub(V0, V1,"upgraded."+CI->getName(),CI);
684       } else if (Name.compare(14, 4, "vmul", 4) == 0) {
685         ExtendNEONArgs(CI, CI->getArgOperand(0), CI->getArgOperand(1), V0, V1);
686         NewI = BinaryOperator::CreateMul(V0, V1,"upgraded."+CI->getName(),CI);
687       } else if (Name.compare(14, 4, "vmla", 4) == 0) {
688         ExtendNEONArgs(CI, CI->getArgOperand(1), CI->getArgOperand(2), V0, V1);
689         Instruction *MulI = BinaryOperator::CreateMul(V0, V1, "", CI);
690         NewI = BinaryOperator::CreateAdd(CI->getArgOperand(0), MulI,
691                                          "upgraded."+CI->getName(), CI);
692       } else if (Name.compare(14, 4, "vmls", 4) == 0) {
693         ExtendNEONArgs(CI, CI->getArgOperand(1), CI->getArgOperand(2), V0, V1);
694         Instruction *MulI = BinaryOperator::CreateMul(V0, V1, "", CI);
695         NewI = BinaryOperator::CreateSub(CI->getArgOperand(0), MulI,
696                                          "upgraded."+CI->getName(), CI);
697       } else if (Name.compare(14, 4, "vabd", 4) == 0) {
698         NewI = CallVABD(CI, CI->getArgOperand(0), CI->getArgOperand(1));
699         NewI = new ZExtInst(NewI, CI->getType(), "upgraded."+CI->getName(), CI);
700       } else if (Name.compare(14, 4, "vaba", 4) == 0) {
701         NewI = CallVABD(CI, CI->getArgOperand(1), CI->getArgOperand(2));
702         if (Name.at(18) == 'l')
703           NewI = new ZExtInst(NewI, CI->getType(), "", CI);
704         NewI = BinaryOperator::CreateAdd(CI->getArgOperand(0), NewI,
705                                          "upgraded."+CI->getName(), CI);
706       } else if (Name.compare(14, 6, "vmovn.", 6) == 0) {
707         NewI = new TruncInst(CI->getArgOperand(0), CI->getType(),
708                              "upgraded." + CI->getName(), CI);
709       } else {
710         llvm_unreachable("Unknown arm.neon function for CallInst upgrade.");
711       }
712       // Replace any uses of the old CallInst.
713       if (!CI->use_empty())
714         CI->replaceAllUsesWith(NewI);
715       CI->eraseFromParent();
716       return;
717     }
718
719     bool isLoadH = false, isLoadL = false, isMovL = false;
720     bool isMovSD = false, isShufPD = false;
721     bool isUnpckhPD = false, isUnpcklPD = false;
722     bool isPunpckhQPD = false, isPunpcklQPD = false;
723     if (F->getName() == "llvm.x86.sse2.loadh.pd")
724       isLoadH = true;
725     else if (F->getName() == "llvm.x86.sse2.loadl.pd")
726       isLoadL = true;
727     else if (F->getName() == "llvm.x86.sse2.movl.dq")
728       isMovL = true;
729     else if (F->getName() == "llvm.x86.sse2.movs.d")
730       isMovSD = true;
731     else if (F->getName() == "llvm.x86.sse2.shuf.pd")
732       isShufPD = true;
733     else if (F->getName() == "llvm.x86.sse2.unpckh.pd")
734       isUnpckhPD = true;
735     else if (F->getName() == "llvm.x86.sse2.unpckl.pd")
736       isUnpcklPD = true;
737     else if (F->getName() ==  "llvm.x86.sse2.punpckh.qdq")
738       isPunpckhQPD = true;
739     else if (F->getName() ==  "llvm.x86.sse2.punpckl.qdq")
740       isPunpcklQPD = true;
741
742     if (isLoadH || isLoadL || isMovL || isMovSD || isShufPD ||
743         isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
744       std::vector<Constant*> Idxs;
745       Value *Op0 = CI->getArgOperand(0);
746       ShuffleVectorInst *SI = NULL;
747       if (isLoadH || isLoadL) {
748         Value *Op1 = UndefValue::get(Op0->getType());
749         Value *Addr = new BitCastInst(CI->getArgOperand(1), 
750                                   Type::getDoublePtrTy(C),
751                                       "upgraded.", CI);
752         Value *Load = new LoadInst(Addr, "upgraded.", false, 8, CI);
753         Value *Idx = ConstantInt::get(Type::getInt32Ty(C), 0);
754         Op1 = InsertElementInst::Create(Op1, Load, Idx, "upgraded.", CI);
755
756         if (isLoadH) {
757           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
758           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
759         } else {
760           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
761           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
762         }
763         Value *Mask = ConstantVector::get(Idxs);
764         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
765       } else if (isMovL) {
766         Constant *Zero = ConstantInt::get(Type::getInt32Ty(C), 0);
767         Idxs.push_back(Zero);
768         Idxs.push_back(Zero);
769         Idxs.push_back(Zero);
770         Idxs.push_back(Zero);
771         Value *ZeroV = ConstantVector::get(Idxs);
772
773         Idxs.clear(); 
774         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 4));
775         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 5));
776         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
777         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 3));
778         Value *Mask = ConstantVector::get(Idxs);
779         SI = new ShuffleVectorInst(ZeroV, Op0, Mask, "upgraded.", CI);
780       } else if (isMovSD ||
781                  isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
782         Value *Op1 = CI->getArgOperand(1);
783         if (isMovSD) {
784           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
785           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
786         } else if (isUnpckhPD || isPunpckhQPD) {
787           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
788           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 3));
789         } else {
790           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
791           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
792         }
793         Value *Mask = ConstantVector::get(Idxs);
794         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
795       } else if (isShufPD) {
796         Value *Op1 = CI->getArgOperand(1);
797         unsigned MaskVal =
798                         cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
799         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), MaskVal & 1));
800         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C),
801                                                ((MaskVal >> 1) & 1)+2));
802         Value *Mask = ConstantVector::get(Idxs);
803         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
804       }
805
806       assert(SI && "Unexpected!");
807
808       // Handle any uses of the old CallInst.
809       if (!CI->use_empty())
810         //  Replace all uses of the old call with the new cast which has the 
811         //  correct type.
812         CI->replaceAllUsesWith(SI);
813       
814       //  Clean up the old call now that it has been completely upgraded.
815       CI->eraseFromParent();
816     } else if (F->getName() == "llvm.x86.sse41.pmulld") {
817       // Upgrade this set of intrinsics into vector multiplies.
818       Instruction *Mul = BinaryOperator::CreateMul(CI->getArgOperand(0),
819                                                    CI->getArgOperand(1),
820                                                    CI->getName(),
821                                                    CI);
822       // Fix up all the uses with our new multiply.
823       if (!CI->use_empty())
824         CI->replaceAllUsesWith(Mul);
825         
826       // Remove upgraded multiply.
827       CI->eraseFromParent();
828     } else if (F->getName() == "llvm.x86.ssse3.palign.r") {
829       Value *Op1 = CI->getArgOperand(0);
830       Value *Op2 = CI->getArgOperand(1);
831       Value *Op3 = CI->getArgOperand(2);
832       unsigned shiftVal = cast<ConstantInt>(Op3)->getZExtValue();
833       Value *Rep;
834       IRBuilder<> Builder(C);
835       Builder.SetInsertPoint(CI->getParent(), CI);
836
837       // If palignr is shifting the pair of input vectors less than 9 bytes,
838       // emit a shuffle instruction.
839       if (shiftVal <= 8) {
840         const Type *IntTy = Type::getInt32Ty(C);
841         const Type *EltTy = Type::getInt8Ty(C);
842         const Type *VecTy = VectorType::get(EltTy, 8);
843         
844         Op2 = Builder.CreateBitCast(Op2, VecTy);
845         Op1 = Builder.CreateBitCast(Op1, VecTy);
846
847         llvm::SmallVector<llvm::Constant*, 8> Indices;
848         for (unsigned i = 0; i != 8; ++i)
849           Indices.push_back(ConstantInt::get(IntTy, shiftVal + i));
850
851         Value *SV = ConstantVector::get(Indices.begin(), Indices.size());
852         Rep = Builder.CreateShuffleVector(Op2, Op1, SV, "palignr");
853         Rep = Builder.CreateBitCast(Rep, F->getReturnType());
854       }
855
856       // If palignr is shifting the pair of input vectors more than 8 but less
857       // than 16 bytes, emit a logical right shift of the destination.
858       else if (shiftVal < 16) {
859         // MMX has these as 1 x i64 vectors for some odd optimization reasons.
860         const Type *EltTy = Type::getInt64Ty(C);
861         const Type *VecTy = VectorType::get(EltTy, 1);
862
863         Op1 = Builder.CreateBitCast(Op1, VecTy, "cast");
864         Op2 = ConstantInt::get(VecTy, (shiftVal-8) * 8);
865
866         // create i32 constant
867         Function *I =
868           Intrinsic::getDeclaration(F->getParent(), Intrinsic::x86_mmx_psrl_q);
869         Rep = Builder.CreateCall2(I, Op1, Op2, "palignr");
870       }
871
872       // If palignr is shifting the pair of vectors more than 32 bytes, emit zero.
873       else {
874         Rep = Constant::getNullValue(F->getReturnType());
875       }
876       
877       // Replace any uses with our new instruction.
878       if (!CI->use_empty())
879         CI->replaceAllUsesWith(Rep);
880         
881       // Remove upgraded instruction.
882       CI->eraseFromParent();
883       
884     } else if (F->getName() == "llvm.x86.ssse3.palign.r.128") {
885       Value *Op1 = CI->getArgOperand(0);
886       Value *Op2 = CI->getArgOperand(1);
887       Value *Op3 = CI->getArgOperand(2);
888       unsigned shiftVal = cast<ConstantInt>(Op3)->getZExtValue();
889       Value *Rep;
890       IRBuilder<> Builder(C);
891       Builder.SetInsertPoint(CI->getParent(), CI);
892
893       // If palignr is shifting the pair of input vectors less than 17 bytes,
894       // emit a shuffle instruction.
895       if (shiftVal <= 16) {
896         const Type *IntTy = Type::getInt32Ty(C);
897         const Type *EltTy = Type::getInt8Ty(C);
898         const Type *VecTy = VectorType::get(EltTy, 16);
899         
900         Op2 = Builder.CreateBitCast(Op2, VecTy);
901         Op1 = Builder.CreateBitCast(Op1, VecTy);
902
903         llvm::SmallVector<llvm::Constant*, 16> Indices;
904         for (unsigned i = 0; i != 16; ++i)
905           Indices.push_back(ConstantInt::get(IntTy, shiftVal + i));
906
907         Value *SV = ConstantVector::get(Indices.begin(), Indices.size());
908         Rep = Builder.CreateShuffleVector(Op2, Op1, SV, "palignr");
909         Rep = Builder.CreateBitCast(Rep, F->getReturnType());
910       }
911
912       // If palignr is shifting the pair of input vectors more than 16 but less
913       // than 32 bytes, emit a logical right shift of the destination.
914       else if (shiftVal < 32) {
915         const Type *EltTy = Type::getInt64Ty(C);
916         const Type *VecTy = VectorType::get(EltTy, 2);
917         const Type *IntTy = Type::getInt32Ty(C);
918
919         Op1 = Builder.CreateBitCast(Op1, VecTy, "cast");
920         Op2 = ConstantInt::get(IntTy, (shiftVal-16) * 8);
921
922         // create i32 constant
923         Function *I =
924           Intrinsic::getDeclaration(F->getParent(), Intrinsic::x86_sse2_psrl_dq);
925         Rep = Builder.CreateCall2(I, Op1, Op2, "palignr");
926       }
927
928       // If palignr is shifting the pair of vectors more than 32 bytes, emit zero.
929       else {
930         Rep = Constant::getNullValue(F->getReturnType());
931       }
932       
933       // Replace any uses with our new instruction.
934       if (!CI->use_empty())
935         CI->replaceAllUsesWith(Rep);
936         
937       // Remove upgraded instruction.
938       CI->eraseFromParent();
939       
940     } else {
941       llvm_unreachable("Unknown function for CallInst upgrade.");
942     }
943     return;
944   }
945
946   switch (NewFn->getIntrinsicID()) {
947   default: llvm_unreachable("Unknown function for CallInst upgrade.");
948   case Intrinsic::arm_neon_vld1:
949   case Intrinsic::arm_neon_vld2:
950   case Intrinsic::arm_neon_vld3:
951   case Intrinsic::arm_neon_vld4:
952   case Intrinsic::arm_neon_vst1:
953   case Intrinsic::arm_neon_vst2:
954   case Intrinsic::arm_neon_vst3:
955   case Intrinsic::arm_neon_vst4:
956   case Intrinsic::arm_neon_vld2lane:
957   case Intrinsic::arm_neon_vld3lane:
958   case Intrinsic::arm_neon_vld4lane:
959   case Intrinsic::arm_neon_vst2lane:
960   case Intrinsic::arm_neon_vst3lane:
961   case Intrinsic::arm_neon_vst4lane: {
962     // Add a default alignment argument of 1.
963     SmallVector<Value*, 8> Operands(CS.arg_begin(), CS.arg_end());
964     Operands.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
965     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
966                                        CI->getName(), CI);
967     NewCI->setTailCall(CI->isTailCall());
968     NewCI->setCallingConv(CI->getCallingConv());
969
970     //  Handle any uses of the old CallInst.
971     if (!CI->use_empty())
972       //  Replace all uses of the old call with the new cast which has the 
973       //  correct type.
974       CI->replaceAllUsesWith(NewCI);
975     
976     //  Clean up the old call now that it has been completely upgraded.
977     CI->eraseFromParent();
978     break;
979   }        
980
981   case Intrinsic::x86_mmx_padd_b:
982   case Intrinsic::x86_mmx_padd_w:
983   case Intrinsic::x86_mmx_padd_d:
984   case Intrinsic::x86_mmx_padd_q:
985   case Intrinsic::x86_mmx_padds_b:
986   case Intrinsic::x86_mmx_padds_w:
987   case Intrinsic::x86_mmx_paddus_b:
988   case Intrinsic::x86_mmx_paddus_w:
989   case Intrinsic::x86_mmx_psub_b:
990   case Intrinsic::x86_mmx_psub_w:
991   case Intrinsic::x86_mmx_psub_d:
992   case Intrinsic::x86_mmx_psub_q:
993   case Intrinsic::x86_mmx_psubs_b:
994   case Intrinsic::x86_mmx_psubs_w:
995   case Intrinsic::x86_mmx_psubus_b:
996   case Intrinsic::x86_mmx_psubus_w:
997   case Intrinsic::x86_mmx_pmulh_w:
998   case Intrinsic::x86_mmx_pmull_w:
999   case Intrinsic::x86_mmx_pmulhu_w:
1000   case Intrinsic::x86_mmx_pmulu_dq:
1001   case Intrinsic::x86_mmx_pmadd_wd:
1002   case Intrinsic::x86_mmx_pand:
1003   case Intrinsic::x86_mmx_pandn:
1004   case Intrinsic::x86_mmx_por:
1005   case Intrinsic::x86_mmx_pxor:
1006   case Intrinsic::x86_mmx_pavg_b:
1007   case Intrinsic::x86_mmx_pavg_w:
1008   case Intrinsic::x86_mmx_pmaxu_b:
1009   case Intrinsic::x86_mmx_pmaxs_w:
1010   case Intrinsic::x86_mmx_pminu_b:
1011   case Intrinsic::x86_mmx_pmins_w:
1012   case Intrinsic::x86_mmx_psad_bw:
1013   case Intrinsic::x86_mmx_psll_w:
1014   case Intrinsic::x86_mmx_psll_d:
1015   case Intrinsic::x86_mmx_psll_q:
1016   case Intrinsic::x86_mmx_pslli_w:
1017   case Intrinsic::x86_mmx_pslli_d:
1018   case Intrinsic::x86_mmx_pslli_q:
1019   case Intrinsic::x86_mmx_psrl_w:
1020   case Intrinsic::x86_mmx_psrl_d:
1021   case Intrinsic::x86_mmx_psrl_q:
1022   case Intrinsic::x86_mmx_psrli_w:
1023   case Intrinsic::x86_mmx_psrli_d:
1024   case Intrinsic::x86_mmx_psrli_q:
1025   case Intrinsic::x86_mmx_psra_w:
1026   case Intrinsic::x86_mmx_psra_d:
1027   case Intrinsic::x86_mmx_psrai_w:
1028   case Intrinsic::x86_mmx_psrai_d:
1029   case Intrinsic::x86_mmx_packsswb:
1030   case Intrinsic::x86_mmx_packssdw:
1031   case Intrinsic::x86_mmx_packuswb:
1032   case Intrinsic::x86_mmx_punpckhbw:
1033   case Intrinsic::x86_mmx_punpckhwd:
1034   case Intrinsic::x86_mmx_punpckhdq:
1035   case Intrinsic::x86_mmx_punpcklbw:
1036   case Intrinsic::x86_mmx_punpcklwd:
1037   case Intrinsic::x86_mmx_punpckldq:
1038   case Intrinsic::x86_mmx_pcmpeq_b:
1039   case Intrinsic::x86_mmx_pcmpeq_w:
1040   case Intrinsic::x86_mmx_pcmpeq_d:
1041   case Intrinsic::x86_mmx_pcmpgt_b:
1042   case Intrinsic::x86_mmx_pcmpgt_w:
1043   case Intrinsic::x86_mmx_pcmpgt_d: {
1044     Value *Operands[2];
1045     
1046     // Cast the operand to the X86 MMX type.
1047     Operands[0] = new BitCastInst(CI->getArgOperand(0), 
1048                                   NewFn->getFunctionType()->getParamType(0),
1049                                   "upgraded.", CI);
1050
1051     switch (NewFn->getIntrinsicID()) {
1052     default:
1053       // Cast to the X86 MMX type.
1054       Operands[1] = new BitCastInst(CI->getArgOperand(1), 
1055                                     NewFn->getFunctionType()->getParamType(1),
1056                                     "upgraded.", CI);
1057       break;
1058     case Intrinsic::x86_mmx_pslli_w:
1059     case Intrinsic::x86_mmx_pslli_d:
1060     case Intrinsic::x86_mmx_pslli_q:
1061     case Intrinsic::x86_mmx_psrli_w:
1062     case Intrinsic::x86_mmx_psrli_d:
1063     case Intrinsic::x86_mmx_psrli_q:
1064     case Intrinsic::x86_mmx_psrai_w:
1065     case Intrinsic::x86_mmx_psrai_d:
1066       // These take an i32 as their second parameter.
1067       Operands[1] = CI->getArgOperand(1);
1068       break;
1069     }
1070
1071     ConstructNewCallInst(NewFn, CI, Operands, 2);
1072     break;
1073   }
1074   case Intrinsic::x86_mmx_maskmovq: {
1075     Value *Operands[3];
1076
1077     // Cast the operands to the X86 MMX type.
1078     Operands[0] = new BitCastInst(CI->getArgOperand(0), 
1079                                   NewFn->getFunctionType()->getParamType(0),
1080                                   "upgraded.", CI);
1081     Operands[1] = new BitCastInst(CI->getArgOperand(1), 
1082                                   NewFn->getFunctionType()->getParamType(1),
1083                                   "upgraded.", CI);
1084     Operands[2] = CI->getArgOperand(2);
1085
1086     ConstructNewCallInst(NewFn, CI, Operands, 3, false);
1087     break;
1088   }
1089   case Intrinsic::x86_mmx_pmovmskb: {
1090     Value *Operands[1];
1091
1092     // Cast the operand to the X86 MMX type.
1093     Operands[0] = new BitCastInst(CI->getArgOperand(0), 
1094                                   NewFn->getFunctionType()->getParamType(0),
1095                                   "upgraded.", CI);
1096
1097     ConstructNewCallInst(NewFn, CI, Operands, 1);
1098     break;
1099   }
1100   case Intrinsic::x86_mmx_movnt_dq: {
1101     Value *Operands[2];
1102
1103     Operands[0] = CI->getArgOperand(0);
1104
1105     // Cast the operand to the X86 MMX type.
1106     Operands[1] = new BitCastInst(CI->getArgOperand(1),
1107                                   NewFn->getFunctionType()->getParamType(1),
1108                                   "upgraded.", CI);
1109
1110     ConstructNewCallInst(NewFn, CI, Operands, 2, false);
1111     break;
1112   }
1113   case Intrinsic::x86_mmx_palignr_b: {
1114     Value *Operands[3];
1115
1116     // Cast the operands to the X86 MMX type.
1117     Operands[0] = new BitCastInst(CI->getArgOperand(0),
1118                                   NewFn->getFunctionType()->getParamType(0),
1119                                   "upgraded.", CI);
1120     Operands[1] = new BitCastInst(CI->getArgOperand(1),
1121                                   NewFn->getFunctionType()->getParamType(1),
1122                                   "upgraded.", CI);
1123     Operands[2] = CI->getArgOperand(2);
1124
1125     ConstructNewCallInst(NewFn, CI, Operands, 3);
1126     break;
1127   }
1128   case Intrinsic::x86_mmx_pextr_w: {
1129     Value *Operands[2];
1130
1131     // Cast the operands to the X86 MMX type.
1132     Operands[0] = new BitCastInst(CI->getArgOperand(0),
1133                                   NewFn->getFunctionType()->getParamType(0),
1134                                   "upgraded.", CI);
1135     Operands[1] = CI->getArgOperand(1);
1136
1137     ConstructNewCallInst(NewFn, CI, Operands, 2);
1138     break;
1139   }
1140   case Intrinsic::x86_mmx_pinsr_w: {
1141     Value *Operands[3];
1142
1143     // Cast the operands to the X86 MMX type.
1144     Operands[0] = new BitCastInst(CI->getArgOperand(0),
1145                                   NewFn->getFunctionType()->getParamType(0),
1146                                   "upgraded.", CI);
1147     Operands[1] = CI->getArgOperand(1);
1148     Operands[2] = CI->getArgOperand(2);
1149
1150     ConstructNewCallInst(NewFn, CI, Operands, 3);
1151     break;
1152   }
1153 #if 0
1154   case Intrinsic::x86_mmx_cvtsi32_si64: {
1155     // The return type needs to be changed.
1156     Value *Operands[1];
1157     Operands[0] = CI->getArgOperand(0);
1158     ConstructNewCallInst(NewFn, CI, Operands, 1);
1159     break;
1160   }
1161   case Intrinsic::x86_mmx_cvtsi64_si32: {
1162     Value *Operands[1];
1163
1164     // Cast the operand to the X86 MMX type.
1165     Operands[0] = new BitCastInst(CI->getArgOperand(0),
1166                                   NewFn->getFunctionType()->getParamType(0),
1167                                   "upgraded.", CI);
1168
1169     ConstructNewCallInst(NewFn, CI, Operands, 1);
1170     break;
1171   }
1172   case Intrinsic::x86_mmx_vec_init_b:
1173   case Intrinsic::x86_mmx_vec_init_w:
1174   case Intrinsic::x86_mmx_vec_init_d: {
1175     // The return type needs to be changed.
1176     Value *Operands[8];
1177     unsigned NumOps = 0;
1178
1179     switch (NewFn->getIntrinsicID()) {
1180     default: break;
1181     case Intrinsic::x86_mmx_vec_init_b: NumOps = 8; break;
1182     case Intrinsic::x86_mmx_vec_init_w: NumOps = 4; break;
1183     case Intrinsic::x86_mmx_vec_init_d: NumOps = 2; break;
1184     }
1185
1186     switch (NewFn->getIntrinsicID()) {
1187     default: break;
1188     case Intrinsic::x86_mmx_vec_init_b:
1189       Operands[7] = CI->getArgOperand(7);
1190       Operands[6] = CI->getArgOperand(6);
1191       Operands[5] = CI->getArgOperand(5);
1192       Operands[4] = CI->getArgOperand(4);
1193       // FALLTHRU
1194     case Intrinsic::x86_mmx_vec_init_w:
1195       Operands[3] = CI->getArgOperand(3);
1196       Operands[2] = CI->getArgOperand(2);
1197       // FALLTHRU
1198     case Intrinsic::x86_mmx_vec_init_d:
1199       Operands[1] = CI->getArgOperand(1);
1200       Operands[0] = CI->getArgOperand(0);
1201       break;
1202     }
1203
1204     ConstructNewCallInst(NewFn, CI, Operands, NumOps);
1205     break;
1206   }
1207   case Intrinsic::x86_mmx_vec_ext_d: {
1208     Value *Operands[2];
1209
1210     // Cast the operand to the X86 MMX type.
1211     Operands[0] = new BitCastInst(CI->getArgOperand(0),
1212                                   NewFn->getFunctionType()->getParamType(0),
1213                                   "upgraded.", CI);
1214     Operands[1] = CI->getArgOperand(1);
1215
1216     ConstructNewCallInst(NewFn, CI, Operands, 2);
1217     break;
1218   }
1219 #endif
1220
1221   case Intrinsic::ctlz:
1222   case Intrinsic::ctpop:
1223   case Intrinsic::cttz: {
1224     //  Build a small vector of the original arguments.
1225     SmallVector<Value*, 8> Operands(CS.arg_begin(), CS.arg_end());
1226
1227     //  Construct a new CallInst
1228     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
1229                                        "upgraded."+CI->getName(), CI);
1230     NewCI->setTailCall(CI->isTailCall());
1231     NewCI->setCallingConv(CI->getCallingConv());
1232
1233     //  Handle any uses of the old CallInst.
1234     if (!CI->use_empty()) {
1235       //  Check for sign extend parameter attributes on the return values.
1236       bool SrcSExt = NewFn->getAttributes().paramHasAttr(0, Attribute::SExt);
1237       bool DestSExt = F->getAttributes().paramHasAttr(0, Attribute::SExt);
1238       
1239       //  Construct an appropriate cast from the new return type to the old.
1240       CastInst *RetCast = CastInst::Create(
1241                             CastInst::getCastOpcode(NewCI, SrcSExt,
1242                                                     F->getReturnType(),
1243                                                     DestSExt),
1244                             NewCI, F->getReturnType(),
1245                             NewCI->getName(), CI);
1246       NewCI->moveBefore(RetCast);
1247
1248       //  Replace all uses of the old call with the new cast which has the 
1249       //  correct type.
1250       CI->replaceAllUsesWith(RetCast);
1251     }
1252
1253     //  Clean up the old call now that it has been completely upgraded.
1254     CI->eraseFromParent();
1255   }
1256   break;
1257   case Intrinsic::eh_selector:
1258   case Intrinsic::eh_typeid_for: {
1259     // Only the return type changed.
1260     SmallVector<Value*, 8> Operands(CS.arg_begin(), CS.arg_end());
1261     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
1262                                        "upgraded." + CI->getName(), CI);
1263     NewCI->setTailCall(CI->isTailCall());
1264     NewCI->setCallingConv(CI->getCallingConv());
1265
1266     //  Handle any uses of the old CallInst.
1267     if (!CI->use_empty()) {
1268       //  Construct an appropriate cast from the new return type to the old.
1269       CastInst *RetCast =
1270         CastInst::Create(CastInst::getCastOpcode(NewCI, true,
1271                                                  F->getReturnType(), true),
1272                          NewCI, F->getReturnType(), NewCI->getName(), CI);
1273       CI->replaceAllUsesWith(RetCast);
1274     }
1275     CI->eraseFromParent();
1276   }
1277   break;
1278   case Intrinsic::memcpy:
1279   case Intrinsic::memmove:
1280   case Intrinsic::memset: {
1281     // Add isVolatile
1282     const llvm::Type *I1Ty = llvm::Type::getInt1Ty(CI->getContext());
1283     Value *Operands[5] = { CI->getArgOperand(0), CI->getArgOperand(1),
1284                            CI->getArgOperand(2), CI->getArgOperand(3),
1285                            llvm::ConstantInt::get(I1Ty, 0) };
1286     CallInst *NewCI = CallInst::Create(NewFn, Operands, Operands+5,
1287                                        CI->getName(), CI);
1288     NewCI->setTailCall(CI->isTailCall());
1289     NewCI->setCallingConv(CI->getCallingConv());
1290     //  Handle any uses of the old CallInst.
1291     if (!CI->use_empty())
1292       //  Replace all uses of the old call with the new cast which has the 
1293       //  correct type.
1294       CI->replaceAllUsesWith(NewCI);
1295     
1296     //  Clean up the old call now that it has been completely upgraded.
1297     CI->eraseFromParent();
1298     break;
1299   }
1300   }
1301 }
1302
1303 // This tests each Function to determine if it needs upgrading. When we find 
1304 // one we are interested in, we then upgrade all calls to reflect the new 
1305 // function.
1306 void llvm::UpgradeCallsToIntrinsic(Function* F) {
1307   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
1308
1309   // Upgrade the function and check if it is a totaly new function.
1310   Function* NewFn;
1311   if (UpgradeIntrinsicFunction(F, NewFn)) {
1312     if (NewFn != F) {
1313       // Replace all uses to the old function with the new one if necessary.
1314       for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
1315            UI != UE; ) {
1316         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1317           UpgradeIntrinsicCall(CI, NewFn);
1318       }
1319       // Remove old function, no longer used, from the module.
1320       F->eraseFromParent();
1321     }
1322   }
1323 }
1324
1325 /// This function strips all debug info intrinsics, except for llvm.dbg.declare.
1326 /// If an llvm.dbg.declare intrinsic is invalid, then this function simply
1327 /// strips that use.
1328 void llvm::CheckDebugInfoIntrinsics(Module *M) {
1329
1330
1331   if (Function *FuncStart = M->getFunction("llvm.dbg.func.start")) {
1332     while (!FuncStart->use_empty()) {
1333       CallInst *CI = cast<CallInst>(FuncStart->use_back());
1334       CI->eraseFromParent();
1335     }
1336     FuncStart->eraseFromParent();
1337   }
1338   
1339   if (Function *StopPoint = M->getFunction("llvm.dbg.stoppoint")) {
1340     while (!StopPoint->use_empty()) {
1341       CallInst *CI = cast<CallInst>(StopPoint->use_back());
1342       CI->eraseFromParent();
1343     }
1344     StopPoint->eraseFromParent();
1345   }
1346
1347   if (Function *RegionStart = M->getFunction("llvm.dbg.region.start")) {
1348     while (!RegionStart->use_empty()) {
1349       CallInst *CI = cast<CallInst>(RegionStart->use_back());
1350       CI->eraseFromParent();
1351     }
1352     RegionStart->eraseFromParent();
1353   }
1354
1355   if (Function *RegionEnd = M->getFunction("llvm.dbg.region.end")) {
1356     while (!RegionEnd->use_empty()) {
1357       CallInst *CI = cast<CallInst>(RegionEnd->use_back());
1358       CI->eraseFromParent();
1359     }
1360     RegionEnd->eraseFromParent();
1361   }
1362   
1363   if (Function *Declare = M->getFunction("llvm.dbg.declare")) {
1364     if (!Declare->use_empty()) {
1365       DbgDeclareInst *DDI = cast<DbgDeclareInst>(Declare->use_back());
1366       if (!isa<MDNode>(DDI->getArgOperand(0)) ||
1367           !isa<MDNode>(DDI->getArgOperand(1))) {
1368         while (!Declare->use_empty()) {
1369           CallInst *CI = cast<CallInst>(Declare->use_back());
1370           CI->eraseFromParent();
1371         }
1372         Declare->eraseFromParent();
1373       }
1374     }
1375   }
1376 }