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 // This is where deprecated IR intrinsics and other IR features are updated to
12 // current specifications.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Regex.h"
31 #include <cstring>
32 using namespace llvm;
33 
34 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
35 
36 // Upgrade the declarations of the SSE4.1 ptest intrinsics whose arguments have
37 // changed their type from v4f32 to v2i64.
38 static bool UpgradePTESTIntrinsic(Function* F, Intrinsic::ID IID,
39                                   Function *&NewFn) {
40   // Check whether this is an old version of the function, which received
41   // v4f32 arguments.
42   Type *Arg0Type = F->getFunctionType()->getParamType(0);
43   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
44     return false;
45 
46   // Yes, it's old, replace it with new version.
47   rename(F);
48   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
49   return true;
50 }
51 
52 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
53 // arguments have changed their type from i32 to i8.
54 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
55                                              Function *&NewFn) {
56   // Check that the last argument is an i32.
57   Type *LastArgType = F->getFunctionType()->getParamType(
58      F->getFunctionType()->getNumParams() - 1);
59   if (!LastArgType->isIntegerTy(32))
60     return false;
61 
62   // Move this function aside and map down.
63   rename(F);
64   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
65   return true;
66 }
67 
68 // Upgrade the declaration of fp compare intrinsics that change return type
69 // from scalar to vXi1 mask.
70 static bool UpgradeX86MaskedFPCompare(Function *F, Intrinsic::ID IID,
71                                       Function *&NewFn) {
72   // Check if the return type is a vector.
73   if (F->getReturnType()->isVectorTy())
74     return false;
75 
76   rename(F);
77   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
78   return true;
79 }
80 
81 static bool ShouldUpgradeX86Intrinsic(Function *F, StringRef Name) {
82   // All of the intrinsics matches below should be marked with which llvm
83   // version started autoupgrading them. At some point in the future we would
84   // like to use this information to remove upgrade code for some older
85   // intrinsics. It is currently undecided how we will determine that future
86   // point.
87   if (Name=="ssse3.pabs.b.128" || // Added in 6.0
88       Name=="ssse3.pabs.w.128" || // Added in 6.0
89       Name=="ssse3.pabs.d.128" || // Added in 6.0
90       Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
91       Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
92       Name.startswith("avx512.kunpck") || //added in 6.0
93       Name.startswith("avx2.pabs.") || // Added in 6.0
94       Name.startswith("avx512.mask.pabs.") || // Added in 6.0
95       Name.startswith("avx512.broadcastm") || // Added in 6.0
96       Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
97       Name.startswith("sse2.pcmpeq.") || // Added in 3.1
98       Name.startswith("sse2.pcmpgt.") || // Added in 3.1
99       Name.startswith("avx2.pcmpeq.") || // Added in 3.1
100       Name.startswith("avx2.pcmpgt.") || // Added in 3.1
101       Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
102       Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
103       Name.startswith("avx.vperm2f128.") || // Added in 6.0
104       Name == "avx2.vperm2i128" || // Added in 6.0
105       Name == "sse.add.ss" || // Added in 4.0
106       Name == "sse2.add.sd" || // Added in 4.0
107       Name == "sse.sub.ss" || // Added in 4.0
108       Name == "sse2.sub.sd" || // Added in 4.0
109       Name == "sse.mul.ss" || // Added in 4.0
110       Name == "sse2.mul.sd" || // Added in 4.0
111       Name == "sse.div.ss" || // Added in 4.0
112       Name == "sse2.div.sd" || // Added in 4.0
113       Name == "sse41.pmaxsb" || // Added in 3.9
114       Name == "sse2.pmaxs.w" || // Added in 3.9
115       Name == "sse41.pmaxsd" || // Added in 3.9
116       Name == "sse2.pmaxu.b" || // Added in 3.9
117       Name == "sse41.pmaxuw" || // Added in 3.9
118       Name == "sse41.pmaxud" || // Added in 3.9
119       Name == "sse41.pminsb" || // Added in 3.9
120       Name == "sse2.pmins.w" || // Added in 3.9
121       Name == "sse41.pminsd" || // Added in 3.9
122       Name == "sse2.pminu.b" || // Added in 3.9
123       Name == "sse41.pminuw" || // Added in 3.9
124       Name == "sse41.pminud" || // Added in 3.9
125       Name == "avx512.kand.w" || // Added in 7.0
126       Name == "avx512.kandn.w" || // Added in 7.0
127       Name == "avx512.knot.w" || // Added in 7.0
128       Name == "avx512.kor.w" || // Added in 7.0
129       Name == "avx512.kxor.w" || // Added in 7.0
130       Name == "avx512.kxnor.w" || // Added in 7.0
131       Name == "avx512.kortestc.w" || // Added in 7.0
132       Name == "avx512.kortestz.w" || // Added in 7.0
133       Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
134       Name.startswith("avx2.pmax") || // Added in 3.9
135       Name.startswith("avx2.pmin") || // Added in 3.9
136       Name.startswith("avx512.mask.pmax") || // Added in 4.0
137       Name.startswith("avx512.mask.pmin") || // Added in 4.0
138       Name.startswith("avx2.vbroadcast") || // Added in 3.8
139       Name.startswith("avx2.pbroadcast") || // Added in 3.8
140       Name.startswith("avx.vpermil.") || // Added in 3.1
141       Name.startswith("sse2.pshuf") || // Added in 3.9
142       Name.startswith("avx512.pbroadcast") || // Added in 3.9
143       Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
144       Name.startswith("avx512.mask.movddup") || // Added in 3.9
145       Name.startswith("avx512.mask.movshdup") || // Added in 3.9
146       Name.startswith("avx512.mask.movsldup") || // Added in 3.9
147       Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
148       Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
149       Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
150       Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
151       Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
152       Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
153       Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
154       Name.startswith("avx512.mask.punpckl") || // Added in 3.9
155       Name.startswith("avx512.mask.punpckh") || // Added in 3.9
156       Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
157       Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
158       Name.startswith("avx512.mask.pand.") || // Added in 3.9
159       Name.startswith("avx512.mask.pandn.") || // Added in 3.9
160       Name.startswith("avx512.mask.por.") || // Added in 3.9
161       Name.startswith("avx512.mask.pxor.") || // Added in 3.9
162       Name.startswith("avx512.mask.and.") || // Added in 3.9
163       Name.startswith("avx512.mask.andn.") || // Added in 3.9
164       Name.startswith("avx512.mask.or.") || // Added in 3.9
165       Name.startswith("avx512.mask.xor.") || // Added in 3.9
166       Name.startswith("avx512.mask.padd.") || // Added in 4.0
167       Name.startswith("avx512.mask.psub.") || // Added in 4.0
168       Name.startswith("avx512.mask.pmull.") || // Added in 4.0
169       Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
170       Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
171       Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
172       Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
173       Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
174       Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
175       Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
176       Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
177       Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
178       Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
179       Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
180       Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
181       Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
182       Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
183       Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
184       Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
185       Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
186       Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
187       Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
188       Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
189       Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
190       Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
191       Name == "avx512.mask.add.pd.128" || // Added in 4.0
192       Name == "avx512.mask.add.pd.256" || // Added in 4.0
193       Name == "avx512.mask.add.ps.128" || // Added in 4.0
194       Name == "avx512.mask.add.ps.256" || // Added in 4.0
195       Name == "avx512.mask.div.pd.128" || // Added in 4.0
196       Name == "avx512.mask.div.pd.256" || // Added in 4.0
197       Name == "avx512.mask.div.ps.128" || // Added in 4.0
198       Name == "avx512.mask.div.ps.256" || // Added in 4.0
199       Name == "avx512.mask.mul.pd.128" || // Added in 4.0
200       Name == "avx512.mask.mul.pd.256" || // Added in 4.0
201       Name == "avx512.mask.mul.ps.128" || // Added in 4.0
202       Name == "avx512.mask.mul.ps.256" || // Added in 4.0
203       Name == "avx512.mask.sub.pd.128" || // Added in 4.0
204       Name == "avx512.mask.sub.pd.256" || // Added in 4.0
205       Name == "avx512.mask.sub.ps.128" || // Added in 4.0
206       Name == "avx512.mask.sub.ps.256" || // Added in 4.0
207       Name == "avx512.mask.max.pd.128" || // Added in 5.0
208       Name == "avx512.mask.max.pd.256" || // Added in 5.0
209       Name == "avx512.mask.max.ps.128" || // Added in 5.0
210       Name == "avx512.mask.max.ps.256" || // Added in 5.0
211       Name == "avx512.mask.min.pd.128" || // Added in 5.0
212       Name == "avx512.mask.min.pd.256" || // Added in 5.0
213       Name == "avx512.mask.min.ps.128" || // Added in 5.0
214       Name == "avx512.mask.min.ps.256" || // Added in 5.0
215       Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
216       Name.startswith("avx512.mask.psll.d") || // Added in 4.0
217       Name.startswith("avx512.mask.psll.q") || // Added in 4.0
218       Name.startswith("avx512.mask.psll.w") || // Added in 4.0
219       Name.startswith("avx512.mask.psra.d") || // Added in 4.0
220       Name.startswith("avx512.mask.psra.q") || // Added in 4.0
221       Name.startswith("avx512.mask.psra.w") || // Added in 4.0
222       Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
223       Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
224       Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
225       Name.startswith("avx512.mask.pslli") || // Added in 4.0
226       Name.startswith("avx512.mask.psrai") || // Added in 4.0
227       Name.startswith("avx512.mask.psrli") || // Added in 4.0
228       Name.startswith("avx512.mask.psllv") || // Added in 4.0
229       Name.startswith("avx512.mask.psrav") || // Added in 4.0
230       Name.startswith("avx512.mask.psrlv") || // Added in 4.0
231       Name.startswith("sse41.pmovsx") || // Added in 3.8
232       Name.startswith("sse41.pmovzx") || // Added in 3.9
233       Name.startswith("avx2.pmovsx") || // Added in 3.9
234       Name.startswith("avx2.pmovzx") || // Added in 3.9
235       Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
236       Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
237       Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
238       Name == "sse2.cvtdq2pd" || // Added in 3.9
239       Name == "sse2.cvtps2pd" || // Added in 3.9
240       Name == "avx.cvtdq2.pd.256" || // Added in 3.9
241       Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
242       Name.startswith("avx.vinsertf128.") || // Added in 3.7
243       Name == "avx2.vinserti128" || // Added in 3.7
244       Name.startswith("avx512.mask.insert") || // Added in 4.0
245       Name.startswith("avx.vextractf128.") || // Added in 3.7
246       Name == "avx2.vextracti128" || // Added in 3.7
247       Name.startswith("avx512.mask.vextract") || // Added in 4.0
248       Name.startswith("sse4a.movnt.") || // Added in 3.9
249       Name.startswith("avx.movnt.") || // Added in 3.2
250       Name.startswith("avx512.storent.") || // Added in 3.9
251       Name == "sse41.movntdqa" || // Added in 5.0
252       Name == "avx2.movntdqa" || // Added in 5.0
253       Name == "avx512.movntdqa" || // Added in 5.0
254       Name == "sse2.storel.dq" || // Added in 3.9
255       Name.startswith("sse.storeu.") || // Added in 3.9
256       Name.startswith("sse2.storeu.") || // Added in 3.9
257       Name.startswith("avx.storeu.") || // Added in 3.9
258       Name.startswith("avx512.mask.storeu.") || // Added in 3.9
259       Name.startswith("avx512.mask.store.p") || // Added in 3.9
260       Name.startswith("avx512.mask.store.b.") || // Added in 3.9
261       Name.startswith("avx512.mask.store.w.") || // Added in 3.9
262       Name.startswith("avx512.mask.store.d.") || // Added in 3.9
263       Name.startswith("avx512.mask.store.q.") || // Added in 3.9
264       Name.startswith("avx512.mask.loadu.") || // Added in 3.9
265       Name.startswith("avx512.mask.load.") || // Added in 3.9
266       Name == "sse42.crc32.64.8" || // Added in 3.4
267       Name.startswith("avx.vbroadcast.s") || // Added in 3.5
268       Name.startswith("avx512.mask.palignr.") || // Added in 3.9
269       Name.startswith("avx512.mask.valign.") || // Added in 4.0
270       Name.startswith("sse2.psll.dq") || // Added in 3.7
271       Name.startswith("sse2.psrl.dq") || // Added in 3.7
272       Name.startswith("avx2.psll.dq") || // Added in 3.7
273       Name.startswith("avx2.psrl.dq") || // Added in 3.7
274       Name.startswith("avx512.psll.dq") || // Added in 3.9
275       Name.startswith("avx512.psrl.dq") || // Added in 3.9
276       Name == "sse41.pblendw" || // Added in 3.7
277       Name.startswith("sse41.blendp") || // Added in 3.7
278       Name.startswith("avx.blend.p") || // Added in 3.7
279       Name == "avx2.pblendw" || // Added in 3.7
280       Name.startswith("avx2.pblendd.") || // Added in 3.7
281       Name.startswith("avx.vbroadcastf128") || // Added in 4.0
282       Name == "avx2.vbroadcasti128" || // Added in 3.7
283       Name.startswith("avx512.mask.broadcastf") || // Added in 6.0
284       Name.startswith("avx512.mask.broadcasti") || // Added in 6.0
285       Name == "xop.vpcmov" || // Added in 3.8
286       Name == "xop.vpcmov.256" || // Added in 5.0
287       Name.startswith("avx512.mask.move.s") || // Added in 4.0
288       Name.startswith("avx512.cvtmask2") || // Added in 5.0
289       (Name.startswith("xop.vpcom") && // Added in 3.2
290        F->arg_size() == 2) ||
291       Name.startswith("avx512.ptestm") || //Added in 6.0
292       Name.startswith("avx512.ptestnm") || //Added in 6.0
293       Name.startswith("sse2.pavg") || // Added in 6.0
294       Name.startswith("avx2.pavg") || // Added in 6.0
295       Name.startswith("avx512.mask.pavg")) // Added in 6.0
296     return true;
297 
298   return false;
299 }
300 
301 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
302                                         Function *&NewFn) {
303   // Only handle intrinsics that start with "x86.".
304   if (!Name.startswith("x86."))
305     return false;
306   // Remove "x86." prefix.
307   Name = Name.substr(4);
308 
309   if (ShouldUpgradeX86Intrinsic(F, Name)) {
310     NewFn = nullptr;
311     return true;
312   }
313 
314   // SSE4.1 ptest functions may have an old signature.
315   if (Name.startswith("sse41.ptest")) { // Added in 3.2
316     if (Name.substr(11) == "c")
317       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
318     if (Name.substr(11) == "z")
319       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
320     if (Name.substr(11) == "nzc")
321       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
322   }
323   // Several blend and other instructions with masks used the wrong number of
324   // bits.
325   if (Name == "sse41.insertps") // Added in 3.6
326     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
327                                             NewFn);
328   if (Name == "sse41.dppd") // Added in 3.6
329     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
330                                             NewFn);
331   if (Name == "sse41.dpps") // Added in 3.6
332     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
333                                             NewFn);
334   if (Name == "sse41.mpsadbw") // Added in 3.6
335     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
336                                             NewFn);
337   if (Name == "avx.dp.ps.256") // Added in 3.6
338     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
339                                             NewFn);
340   if (Name == "avx2.mpsadbw") // Added in 3.6
341     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
342                                             NewFn);
343   if (Name == "avx512.mask.cmp.pd.128") // Added in 7.0
344     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_128,
345                                      NewFn);
346   if (Name == "avx512.mask.cmp.pd.256") // Added in 7.0
347     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_256,
348                                      NewFn);
349   if (Name == "avx512.mask.cmp.pd.512") // Added in 7.0
350     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
351                                      NewFn);
352   if (Name == "avx512.mask.cmp.ps.128") // Added in 7.0
353     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_128,
354                                      NewFn);
355   if (Name == "avx512.mask.cmp.ps.256") // Added in 7.0
356     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_256,
357                                      NewFn);
358   if (Name == "avx512.mask.cmp.ps.512") // Added in 7.0
359     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
360                                      NewFn);
361 
362   // frcz.ss/sd may need to have an argument dropped. Added in 3.2
363   if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
364     rename(F);
365     NewFn = Intrinsic::getDeclaration(F->getParent(),
366                                       Intrinsic::x86_xop_vfrcz_ss);
367     return true;
368   }
369   if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
370     rename(F);
371     NewFn = Intrinsic::getDeclaration(F->getParent(),
372                                       Intrinsic::x86_xop_vfrcz_sd);
373     return true;
374   }
375   // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
376   if (Name.startswith("xop.vpermil2")) { // Added in 3.9
377     auto Idx = F->getFunctionType()->getParamType(2);
378     if (Idx->isFPOrFPVectorTy()) {
379       rename(F);
380       unsigned IdxSize = Idx->getPrimitiveSizeInBits();
381       unsigned EltSize = Idx->getScalarSizeInBits();
382       Intrinsic::ID Permil2ID;
383       if (EltSize == 64 && IdxSize == 128)
384         Permil2ID = Intrinsic::x86_xop_vpermil2pd;
385       else if (EltSize == 32 && IdxSize == 128)
386         Permil2ID = Intrinsic::x86_xop_vpermil2ps;
387       else if (EltSize == 64 && IdxSize == 256)
388         Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
389       else
390         Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
391       NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
392       return true;
393     }
394   }
395 
396   return false;
397 }
398 
399 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
400   assert(F && "Illegal to upgrade a non-existent Function.");
401 
402   // Quickly eliminate it, if it's not a candidate.
403   StringRef Name = F->getName();
404   if (Name.size() <= 8 || !Name.startswith("llvm."))
405     return false;
406   Name = Name.substr(5); // Strip off "llvm."
407 
408   switch (Name[0]) {
409   default: break;
410   case 'a': {
411     if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
412       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
413                                         F->arg_begin()->getType());
414       return true;
415     }
416     if (Name.startswith("arm.neon.vclz")) {
417       Type* args[2] = {
418         F->arg_begin()->getType(),
419         Type::getInt1Ty(F->getContext())
420       };
421       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
422       // the end of the name. Change name from llvm.arm.neon.vclz.* to
423       //  llvm.ctlz.*
424       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
425       NewFn = Function::Create(fType, F->getLinkage(),
426                                "llvm.ctlz." + Name.substr(14), F->getParent());
427       return true;
428     }
429     if (Name.startswith("arm.neon.vcnt")) {
430       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
431                                         F->arg_begin()->getType());
432       return true;
433     }
434     Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
435     if (vldRegex.match(Name)) {
436       auto fArgs = F->getFunctionType()->params();
437       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
438       // Can't use Intrinsic::getDeclaration here as the return types might
439       // then only be structurally equal.
440       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
441       NewFn = Function::Create(fType, F->getLinkage(),
442                                "llvm." + Name + ".p0i8", F->getParent());
443       return true;
444     }
445     Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
446     if (vstRegex.match(Name)) {
447       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
448                                                 Intrinsic::arm_neon_vst2,
449                                                 Intrinsic::arm_neon_vst3,
450                                                 Intrinsic::arm_neon_vst4};
451 
452       static const Intrinsic::ID StoreLaneInts[] = {
453         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
454         Intrinsic::arm_neon_vst4lane
455       };
456 
457       auto fArgs = F->getFunctionType()->params();
458       Type *Tys[] = {fArgs[0], fArgs[1]};
459       if (Name.find("lane") == StringRef::npos)
460         NewFn = Intrinsic::getDeclaration(F->getParent(),
461                                           StoreInts[fArgs.size() - 3], Tys);
462       else
463         NewFn = Intrinsic::getDeclaration(F->getParent(),
464                                           StoreLaneInts[fArgs.size() - 5], Tys);
465       return true;
466     }
467     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
468       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
469       return true;
470     }
471     break;
472   }
473 
474   case 'c': {
475     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
476       rename(F);
477       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
478                                         F->arg_begin()->getType());
479       return true;
480     }
481     if (Name.startswith("cttz.") && F->arg_size() == 1) {
482       rename(F);
483       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
484                                         F->arg_begin()->getType());
485       return true;
486     }
487     break;
488   }
489   case 'd': {
490     if (Name == "dbg.value" && F->arg_size() == 4) {
491       rename(F);
492       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
493       return true;
494     }
495     break;
496   }
497   case 'i':
498   case 'l': {
499     bool IsLifetimeStart = Name.startswith("lifetime.start");
500     if (IsLifetimeStart || Name.startswith("invariant.start")) {
501       Intrinsic::ID ID = IsLifetimeStart ?
502         Intrinsic::lifetime_start : Intrinsic::invariant_start;
503       auto Args = F->getFunctionType()->params();
504       Type* ObjectPtr[1] = {Args[1]};
505       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
506         rename(F);
507         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
508         return true;
509       }
510     }
511 
512     bool IsLifetimeEnd = Name.startswith("lifetime.end");
513     if (IsLifetimeEnd || Name.startswith("invariant.end")) {
514       Intrinsic::ID ID = IsLifetimeEnd ?
515         Intrinsic::lifetime_end : Intrinsic::invariant_end;
516 
517       auto Args = F->getFunctionType()->params();
518       Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
519       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
520         rename(F);
521         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
522         return true;
523       }
524     }
525     break;
526   }
527   case 'm': {
528     if (Name.startswith("masked.load.")) {
529       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
530       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
531         rename(F);
532         NewFn = Intrinsic::getDeclaration(F->getParent(),
533                                           Intrinsic::masked_load,
534                                           Tys);
535         return true;
536       }
537     }
538     if (Name.startswith("masked.store.")) {
539       auto Args = F->getFunctionType()->params();
540       Type *Tys[] = { Args[0], Args[1] };
541       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
542         rename(F);
543         NewFn = Intrinsic::getDeclaration(F->getParent(),
544                                           Intrinsic::masked_store,
545                                           Tys);
546         return true;
547       }
548     }
549     // Renaming gather/scatter intrinsics with no address space overloading
550     // to the new overload which includes an address space
551     if (Name.startswith("masked.gather.")) {
552       Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
553       if (F->getName() != Intrinsic::getName(Intrinsic::masked_gather, Tys)) {
554         rename(F);
555         NewFn = Intrinsic::getDeclaration(F->getParent(),
556                                           Intrinsic::masked_gather, Tys);
557         return true;
558       }
559     }
560     if (Name.startswith("masked.scatter.")) {
561       auto Args = F->getFunctionType()->params();
562       Type *Tys[] = {Args[0], Args[1]};
563       if (F->getName() != Intrinsic::getName(Intrinsic::masked_scatter, Tys)) {
564         rename(F);
565         NewFn = Intrinsic::getDeclaration(F->getParent(),
566                                           Intrinsic::masked_scatter, Tys);
567         return true;
568       }
569     }
570     // Updating the memory intrinsics (memcpy/memmove/memset) that have an
571     // alignment parameter to embedding the alignment as an attribute of
572     // the pointer args.
573     if (Name.startswith("memcpy.") && F->arg_size() == 5) {
574       rename(F);
575       // Get the types of dest, src, and len
576       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
577       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
578                                         ParamTypes);
579       return true;
580     }
581     if (Name.startswith("memmove.") && F->arg_size() == 5) {
582       rename(F);
583       // Get the types of dest, src, and len
584       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
585       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
586                                         ParamTypes);
587       return true;
588     }
589     if (Name.startswith("memset.") && F->arg_size() == 5) {
590       rename(F);
591       // Get the types of dest, and len
592       const auto *FT = F->getFunctionType();
593       Type *ParamTypes[2] = {
594           FT->getParamType(0), // Dest
595           FT->getParamType(2)  // len
596       };
597       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
598                                         ParamTypes);
599       return true;
600     }
601     break;
602   }
603   case 'n': {
604     if (Name.startswith("nvvm.")) {
605       Name = Name.substr(5);
606 
607       // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
608       Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
609                               .Cases("brev32", "brev64", Intrinsic::bitreverse)
610                               .Case("clz.i", Intrinsic::ctlz)
611                               .Case("popc.i", Intrinsic::ctpop)
612                               .Default(Intrinsic::not_intrinsic);
613       if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
614         NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
615                                           {F->getReturnType()});
616         return true;
617       }
618 
619       // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
620       // not to an intrinsic alone.  We expand them in UpgradeIntrinsicCall.
621       //
622       // TODO: We could add lohi.i2d.
623       bool Expand = StringSwitch<bool>(Name)
624                         .Cases("abs.i", "abs.ll", true)
625                         .Cases("clz.ll", "popc.ll", "h2f", true)
626                         .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
627                         .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
628                         .Default(false);
629       if (Expand) {
630         NewFn = nullptr;
631         return true;
632       }
633     }
634     break;
635   }
636   case 'o':
637     // We only need to change the name to match the mangling including the
638     // address space.
639     if (Name.startswith("objectsize.")) {
640       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
641       if (F->arg_size() == 2 ||
642           F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
643         rename(F);
644         NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
645                                           Tys);
646         return true;
647       }
648     }
649     break;
650 
651   case 's':
652     if (Name == "stackprotectorcheck") {
653       NewFn = nullptr;
654       return true;
655     }
656     break;
657 
658   case 'x':
659     if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
660       return true;
661   }
662   // Remangle our intrinsic since we upgrade the mangling
663   auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
664   if (Result != None) {
665     NewFn = Result.getValue();
666     return true;
667   }
668 
669   //  This may not belong here. This function is effectively being overloaded
670   //  to both detect an intrinsic which needs upgrading, and to provide the
671   //  upgraded form of the intrinsic. We should perhaps have two separate
672   //  functions for this.
673   return false;
674 }
675 
676 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
677   NewFn = nullptr;
678   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
679   assert(F != NewFn && "Intrinsic function upgraded to the same function");
680 
681   // Upgrade intrinsic attributes.  This does not change the function.
682   if (NewFn)
683     F = NewFn;
684   if (Intrinsic::ID id = F->getIntrinsicID())
685     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
686   return Upgraded;
687 }
688 
689 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
690   // Nothing to do yet.
691   return false;
692 }
693 
694 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
695 // to byte shuffles.
696 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
697                                          Value *Op, unsigned Shift) {
698   Type *ResultTy = Op->getType();
699   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
700 
701   // Bitcast from a 64-bit element type to a byte element type.
702   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
703   Op = Builder.CreateBitCast(Op, VecTy, "cast");
704 
705   // We'll be shuffling in zeroes.
706   Value *Res = Constant::getNullValue(VecTy);
707 
708   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
709   // we'll just return the zero vector.
710   if (Shift < 16) {
711     uint32_t Idxs[64];
712     // 256/512-bit version is split into 2/4 16-byte lanes.
713     for (unsigned l = 0; l != NumElts; l += 16)
714       for (unsigned i = 0; i != 16; ++i) {
715         unsigned Idx = NumElts + i - Shift;
716         if (Idx < NumElts)
717           Idx -= NumElts - 16; // end of lane, switch operand.
718         Idxs[l + i] = Idx + l;
719       }
720 
721     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
722   }
723 
724   // Bitcast back to a 64-bit element type.
725   return Builder.CreateBitCast(Res, ResultTy, "cast");
726 }
727 
728 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
729 // to byte shuffles.
730 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
731                                          unsigned Shift) {
732   Type *ResultTy = Op->getType();
733   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
734 
735   // Bitcast from a 64-bit element type to a byte element type.
736   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
737   Op = Builder.CreateBitCast(Op, VecTy, "cast");
738 
739   // We'll be shuffling in zeroes.
740   Value *Res = Constant::getNullValue(VecTy);
741 
742   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
743   // we'll just return the zero vector.
744   if (Shift < 16) {
745     uint32_t Idxs[64];
746     // 256/512-bit version is split into 2/4 16-byte lanes.
747     for (unsigned l = 0; l != NumElts; l += 16)
748       for (unsigned i = 0; i != 16; ++i) {
749         unsigned Idx = i + Shift;
750         if (Idx >= 16)
751           Idx += NumElts - 16; // end of lane, switch operand.
752         Idxs[l + i] = Idx + l;
753       }
754 
755     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
756   }
757 
758   // Bitcast back to a 64-bit element type.
759   return Builder.CreateBitCast(Res, ResultTy, "cast");
760 }
761 
762 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
763                             unsigned NumElts) {
764   llvm::VectorType *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(),
765                              cast<IntegerType>(Mask->getType())->getBitWidth());
766   Mask = Builder.CreateBitCast(Mask, MaskTy);
767 
768   // If we have less than 8 elements, then the starting mask was an i8 and
769   // we need to extract down to the right number of elements.
770   if (NumElts < 8) {
771     uint32_t Indices[4];
772     for (unsigned i = 0; i != NumElts; ++i)
773       Indices[i] = i;
774     Mask = Builder.CreateShuffleVector(Mask, Mask,
775                                        makeArrayRef(Indices, NumElts),
776                                        "extract");
777   }
778 
779   return Mask;
780 }
781 
782 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
783                             Value *Op0, Value *Op1) {
784   // If the mask is all ones just emit the align operation.
785   if (const auto *C = dyn_cast<Constant>(Mask))
786     if (C->isAllOnesValue())
787       return Op0;
788 
789   Mask = getX86MaskVec(Builder, Mask, Op0->getType()->getVectorNumElements());
790   return Builder.CreateSelect(Mask, Op0, Op1);
791 }
792 
793 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
794 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
795 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
796 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
797                                         Value *Op1, Value *Shift,
798                                         Value *Passthru, Value *Mask,
799                                         bool IsVALIGN) {
800   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
801 
802   unsigned NumElts = Op0->getType()->getVectorNumElements();
803   assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
804   assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
805   assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
806 
807   // Mask the immediate for VALIGN.
808   if (IsVALIGN)
809     ShiftVal &= (NumElts - 1);
810 
811   // If palignr is shifting the pair of vectors more than the size of two
812   // lanes, emit zero.
813   if (ShiftVal >= 32)
814     return llvm::Constant::getNullValue(Op0->getType());
815 
816   // If palignr is shifting the pair of input vectors more than one lane,
817   // but less than two lanes, convert to shifting in zeroes.
818   if (ShiftVal > 16) {
819     ShiftVal -= 16;
820     Op1 = Op0;
821     Op0 = llvm::Constant::getNullValue(Op0->getType());
822   }
823 
824   uint32_t Indices[64];
825   // 256-bit palignr operates on 128-bit lanes so we need to handle that
826   for (unsigned l = 0; l < NumElts; l += 16) {
827     for (unsigned i = 0; i != 16; ++i) {
828       unsigned Idx = ShiftVal + i;
829       if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
830         Idx += NumElts - 16; // End of lane, switch operand.
831       Indices[l + i] = Idx + l;
832     }
833   }
834 
835   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
836                                              makeArrayRef(Indices, NumElts),
837                                              "palignr");
838 
839   return EmitX86Select(Builder, Mask, Align, Passthru);
840 }
841 
842 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
843                                  Value *Ptr, Value *Data, Value *Mask,
844                                  bool Aligned) {
845   // Cast the pointer to the right type.
846   Ptr = Builder.CreateBitCast(Ptr,
847                               llvm::PointerType::getUnqual(Data->getType()));
848   unsigned Align =
849     Aligned ? cast<VectorType>(Data->getType())->getBitWidth() / 8 : 1;
850 
851   // If the mask is all ones just emit a regular store.
852   if (const auto *C = dyn_cast<Constant>(Mask))
853     if (C->isAllOnesValue())
854       return Builder.CreateAlignedStore(Data, Ptr, Align);
855 
856   // Convert the mask from an integer type to a vector of i1.
857   unsigned NumElts = Data->getType()->getVectorNumElements();
858   Mask = getX86MaskVec(Builder, Mask, NumElts);
859   return Builder.CreateMaskedStore(Data, Ptr, Align, Mask);
860 }
861 
862 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
863                                 Value *Ptr, Value *Passthru, Value *Mask,
864                                 bool Aligned) {
865   // Cast the pointer to the right type.
866   Ptr = Builder.CreateBitCast(Ptr,
867                              llvm::PointerType::getUnqual(Passthru->getType()));
868   unsigned Align =
869     Aligned ? cast<VectorType>(Passthru->getType())->getBitWidth() / 8 : 1;
870 
871   // If the mask is all ones just emit a regular store.
872   if (const auto *C = dyn_cast<Constant>(Mask))
873     if (C->isAllOnesValue())
874       return Builder.CreateAlignedLoad(Ptr, Align);
875 
876   // Convert the mask from an integer type to a vector of i1.
877   unsigned NumElts = Passthru->getType()->getVectorNumElements();
878   Mask = getX86MaskVec(Builder, Mask, NumElts);
879   return Builder.CreateMaskedLoad(Ptr, Align, Mask, Passthru);
880 }
881 
882 static Value *upgradeAbs(IRBuilder<> &Builder, CallInst &CI) {
883   Value *Op0 = CI.getArgOperand(0);
884   llvm::Type *Ty = Op0->getType();
885   Value *Zero = llvm::Constant::getNullValue(Ty);
886   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_SGT, Op0, Zero);
887   Value *Neg = Builder.CreateNeg(Op0);
888   Value *Res = Builder.CreateSelect(Cmp, Op0, Neg);
889 
890   if (CI.getNumArgOperands() == 3)
891     Res = EmitX86Select(Builder,CI.getArgOperand(2), Res, CI.getArgOperand(1));
892 
893   return Res;
894 }
895 
896 static Value *upgradeIntMinMax(IRBuilder<> &Builder, CallInst &CI,
897                                ICmpInst::Predicate Pred) {
898   Value *Op0 = CI.getArgOperand(0);
899   Value *Op1 = CI.getArgOperand(1);
900   Value *Cmp = Builder.CreateICmp(Pred, Op0, Op1);
901   Value *Res = Builder.CreateSelect(Cmp, Op0, Op1);
902 
903   if (CI.getNumArgOperands() == 4)
904     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
905 
906   return Res;
907 }
908 
909 // Applying mask on vector of i1's and make sure result is at least 8 bits wide.
910 static Value *ApplyX86MaskOn1BitsVec(IRBuilder<> &Builder,Value *Vec, Value *Mask,
911                                      unsigned NumElts) {
912   if (Mask) {
913     const auto *C = dyn_cast<Constant>(Mask);
914     if (!C || !C->isAllOnesValue())
915       Vec = Builder.CreateAnd(Vec, getX86MaskVec(Builder, Mask, NumElts));
916   }
917 
918   if (NumElts < 8) {
919     uint32_t Indices[8];
920     for (unsigned i = 0; i != NumElts; ++i)
921       Indices[i] = i;
922     for (unsigned i = NumElts; i != 8; ++i)
923       Indices[i] = NumElts + i % NumElts;
924     Vec = Builder.CreateShuffleVector(Vec,
925                                       Constant::getNullValue(Vec->getType()),
926                                       Indices);
927   }
928   return Builder.CreateBitCast(Vec, Builder.getIntNTy(std::max(NumElts, 8U)));
929 }
930 
931 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallInst &CI,
932                                    unsigned CC, bool Signed) {
933   Value *Op0 = CI.getArgOperand(0);
934   unsigned NumElts = Op0->getType()->getVectorNumElements();
935 
936   Value *Cmp;
937   if (CC == 3) {
938     Cmp = Constant::getNullValue(llvm::VectorType::get(Builder.getInt1Ty(), NumElts));
939   } else if (CC == 7) {
940     Cmp = Constant::getAllOnesValue(llvm::VectorType::get(Builder.getInt1Ty(), NumElts));
941   } else {
942     ICmpInst::Predicate Pred;
943     switch (CC) {
944     default: llvm_unreachable("Unknown condition code");
945     case 0: Pred = ICmpInst::ICMP_EQ;  break;
946     case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
947     case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
948     case 4: Pred = ICmpInst::ICMP_NE;  break;
949     case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
950     case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
951     }
952     Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
953   }
954 
955   Value *Mask = CI.getArgOperand(CI.getNumArgOperands() - 1);
956 
957   return ApplyX86MaskOn1BitsVec(Builder, Cmp, Mask, NumElts);
958 }
959 
960 // Replace a masked intrinsic with an older unmasked intrinsic.
961 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallInst &CI,
962                                     Intrinsic::ID IID) {
963   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID);
964   Value *Rep = Builder.CreateCall(Intrin,
965                                  { CI.getArgOperand(0), CI.getArgOperand(1) });
966   return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
967 }
968 
969 static Value* upgradeMaskedMove(IRBuilder<> &Builder, CallInst &CI) {
970   Value* A = CI.getArgOperand(0);
971   Value* B = CI.getArgOperand(1);
972   Value* Src = CI.getArgOperand(2);
973   Value* Mask = CI.getArgOperand(3);
974 
975   Value* AndNode = Builder.CreateAnd(Mask, APInt(8, 1));
976   Value* Cmp = Builder.CreateIsNotNull(AndNode);
977   Value* Extract1 = Builder.CreateExtractElement(B, (uint64_t)0);
978   Value* Extract2 = Builder.CreateExtractElement(Src, (uint64_t)0);
979   Value* Select = Builder.CreateSelect(Cmp, Extract1, Extract2);
980   return Builder.CreateInsertElement(A, Select, (uint64_t)0);
981 }
982 
983 
984 static Value* UpgradeMaskToInt(IRBuilder<> &Builder, CallInst &CI) {
985   Value* Op = CI.getArgOperand(0);
986   Type* ReturnOp = CI.getType();
987   unsigned NumElts = CI.getType()->getVectorNumElements();
988   Value *Mask = getX86MaskVec(Builder, Op, NumElts);
989   return Builder.CreateSExt(Mask, ReturnOp, "vpmovm2");
990 }
991 
992 // Replace intrinsic with unmasked version and a select.
993 static bool upgradeAVX512MaskToSelect(StringRef Name, IRBuilder<> &Builder,
994                                       CallInst &CI, Value *&Rep) {
995   Name = Name.substr(12); // Remove avx512.mask.
996 
997   unsigned VecWidth = CI.getType()->getPrimitiveSizeInBits();
998   unsigned EltWidth = CI.getType()->getScalarSizeInBits();
999   Intrinsic::ID IID;
1000   if (Name.startswith("max.p")) {
1001     if (VecWidth == 128 && EltWidth == 32)
1002       IID = Intrinsic::x86_sse_max_ps;
1003     else if (VecWidth == 128 && EltWidth == 64)
1004       IID = Intrinsic::x86_sse2_max_pd;
1005     else if (VecWidth == 256 && EltWidth == 32)
1006       IID = Intrinsic::x86_avx_max_ps_256;
1007     else if (VecWidth == 256 && EltWidth == 64)
1008       IID = Intrinsic::x86_avx_max_pd_256;
1009     else
1010       llvm_unreachable("Unexpected intrinsic");
1011   } else if (Name.startswith("min.p")) {
1012     if (VecWidth == 128 && EltWidth == 32)
1013       IID = Intrinsic::x86_sse_min_ps;
1014     else if (VecWidth == 128 && EltWidth == 64)
1015       IID = Intrinsic::x86_sse2_min_pd;
1016     else if (VecWidth == 256 && EltWidth == 32)
1017       IID = Intrinsic::x86_avx_min_ps_256;
1018     else if (VecWidth == 256 && EltWidth == 64)
1019       IID = Intrinsic::x86_avx_min_pd_256;
1020     else
1021       llvm_unreachable("Unexpected intrinsic");
1022   } else if (Name.startswith("pshuf.b.")) {
1023     if (VecWidth == 128)
1024       IID = Intrinsic::x86_ssse3_pshuf_b_128;
1025     else if (VecWidth == 256)
1026       IID = Intrinsic::x86_avx2_pshuf_b;
1027     else if (VecWidth == 512)
1028       IID = Intrinsic::x86_avx512_pshuf_b_512;
1029     else
1030       llvm_unreachable("Unexpected intrinsic");
1031   } else if (Name.startswith("pmul.dq.")) {
1032     if (VecWidth == 128)
1033       IID = Intrinsic::x86_sse41_pmuldq;
1034     else if (VecWidth == 256)
1035       IID = Intrinsic::x86_avx2_pmul_dq;
1036     else if (VecWidth == 512)
1037       IID = Intrinsic::x86_avx512_pmul_dq_512;
1038     else
1039       llvm_unreachable("Unexpected intrinsic");
1040   } else if (Name.startswith("pmulu.dq.")) {
1041     if (VecWidth == 128)
1042       IID = Intrinsic::x86_sse2_pmulu_dq;
1043     else if (VecWidth == 256)
1044       IID = Intrinsic::x86_avx2_pmulu_dq;
1045     else if (VecWidth == 512)
1046       IID = Intrinsic::x86_avx512_pmulu_dq_512;
1047     else
1048       llvm_unreachable("Unexpected intrinsic");
1049   } else if (Name.startswith("pmul.hr.sw.")) {
1050     if (VecWidth == 128)
1051       IID = Intrinsic::x86_ssse3_pmul_hr_sw_128;
1052     else if (VecWidth == 256)
1053       IID = Intrinsic::x86_avx2_pmul_hr_sw;
1054     else if (VecWidth == 512)
1055       IID = Intrinsic::x86_avx512_pmul_hr_sw_512;
1056     else
1057       llvm_unreachable("Unexpected intrinsic");
1058   } else if (Name.startswith("pmulh.w.")) {
1059     if (VecWidth == 128)
1060       IID = Intrinsic::x86_sse2_pmulh_w;
1061     else if (VecWidth == 256)
1062       IID = Intrinsic::x86_avx2_pmulh_w;
1063     else if (VecWidth == 512)
1064       IID = Intrinsic::x86_avx512_pmulh_w_512;
1065     else
1066       llvm_unreachable("Unexpected intrinsic");
1067   } else if (Name.startswith("pmulhu.w.")) {
1068     if (VecWidth == 128)
1069       IID = Intrinsic::x86_sse2_pmulhu_w;
1070     else if (VecWidth == 256)
1071       IID = Intrinsic::x86_avx2_pmulhu_w;
1072     else if (VecWidth == 512)
1073       IID = Intrinsic::x86_avx512_pmulhu_w_512;
1074     else
1075       llvm_unreachable("Unexpected intrinsic");
1076   } else if (Name.startswith("pmaddw.d.")) {
1077     if (VecWidth == 128)
1078       IID = Intrinsic::x86_sse2_pmadd_wd;
1079     else if (VecWidth == 256)
1080       IID = Intrinsic::x86_avx2_pmadd_wd;
1081     else if (VecWidth == 512)
1082       IID = Intrinsic::x86_avx512_pmaddw_d_512;
1083     else
1084       llvm_unreachable("Unexpected intrinsic");
1085   } else if (Name.startswith("pmaddubs.w.")) {
1086     if (VecWidth == 128)
1087       IID = Intrinsic::x86_ssse3_pmadd_ub_sw_128;
1088     else if (VecWidth == 256)
1089       IID = Intrinsic::x86_avx2_pmadd_ub_sw;
1090     else if (VecWidth == 512)
1091       IID = Intrinsic::x86_avx512_pmaddubs_w_512;
1092     else
1093       llvm_unreachable("Unexpected intrinsic");
1094   } else if (Name.startswith("packsswb.")) {
1095     if (VecWidth == 128)
1096       IID = Intrinsic::x86_sse2_packsswb_128;
1097     else if (VecWidth == 256)
1098       IID = Intrinsic::x86_avx2_packsswb;
1099     else if (VecWidth == 512)
1100       IID = Intrinsic::x86_avx512_packsswb_512;
1101     else
1102       llvm_unreachable("Unexpected intrinsic");
1103   } else if (Name.startswith("packssdw.")) {
1104     if (VecWidth == 128)
1105       IID = Intrinsic::x86_sse2_packssdw_128;
1106     else if (VecWidth == 256)
1107       IID = Intrinsic::x86_avx2_packssdw;
1108     else if (VecWidth == 512)
1109       IID = Intrinsic::x86_avx512_packssdw_512;
1110     else
1111       llvm_unreachable("Unexpected intrinsic");
1112   } else if (Name.startswith("packuswb.")) {
1113     if (VecWidth == 128)
1114       IID = Intrinsic::x86_sse2_packuswb_128;
1115     else if (VecWidth == 256)
1116       IID = Intrinsic::x86_avx2_packuswb;
1117     else if (VecWidth == 512)
1118       IID = Intrinsic::x86_avx512_packuswb_512;
1119     else
1120       llvm_unreachable("Unexpected intrinsic");
1121   } else if (Name.startswith("packusdw.")) {
1122     if (VecWidth == 128)
1123       IID = Intrinsic::x86_sse41_packusdw;
1124     else if (VecWidth == 256)
1125       IID = Intrinsic::x86_avx2_packusdw;
1126     else if (VecWidth == 512)
1127       IID = Intrinsic::x86_avx512_packusdw_512;
1128     else
1129       llvm_unreachable("Unexpected intrinsic");
1130   } else if (Name.startswith("vpermilvar.")) {
1131     if (VecWidth == 128 && EltWidth == 32)
1132       IID = Intrinsic::x86_avx_vpermilvar_ps;
1133     else if (VecWidth == 128 && EltWidth == 64)
1134       IID = Intrinsic::x86_avx_vpermilvar_pd;
1135     else if (VecWidth == 256 && EltWidth == 32)
1136       IID = Intrinsic::x86_avx_vpermilvar_ps_256;
1137     else if (VecWidth == 256 && EltWidth == 64)
1138       IID = Intrinsic::x86_avx_vpermilvar_pd_256;
1139     else if (VecWidth == 512 && EltWidth == 32)
1140       IID = Intrinsic::x86_avx512_vpermilvar_ps_512;
1141     else if (VecWidth == 512 && EltWidth == 64)
1142       IID = Intrinsic::x86_avx512_vpermilvar_pd_512;
1143     else
1144       llvm_unreachable("Unexpected intrinsic");
1145   } else
1146     return false;
1147 
1148   Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1149                            { CI.getArgOperand(0), CI.getArgOperand(1) });
1150   Rep = EmitX86Select(Builder, CI.getArgOperand(3), Rep,
1151                       CI.getArgOperand(2));
1152   return true;
1153 }
1154 
1155 /// Upgrade a call to an old intrinsic. All argument and return casting must be
1156 /// provided to seamlessly integrate with existing context.
1157 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
1158   Function *F = CI->getCalledFunction();
1159   LLVMContext &C = CI->getContext();
1160   IRBuilder<> Builder(C);
1161   Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
1162 
1163   assert(F && "Intrinsic call is not direct?");
1164 
1165   if (!NewFn) {
1166     // Get the Function's name.
1167     StringRef Name = F->getName();
1168 
1169     assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
1170     Name = Name.substr(5);
1171 
1172     bool IsX86 = Name.startswith("x86.");
1173     if (IsX86)
1174       Name = Name.substr(4);
1175     bool IsNVVM = Name.startswith("nvvm.");
1176     if (IsNVVM)
1177       Name = Name.substr(5);
1178 
1179     if (IsX86 && Name.startswith("sse4a.movnt.")) {
1180       Module *M = F->getParent();
1181       SmallVector<Metadata *, 1> Elts;
1182       Elts.push_back(
1183           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1184       MDNode *Node = MDNode::get(C, Elts);
1185 
1186       Value *Arg0 = CI->getArgOperand(0);
1187       Value *Arg1 = CI->getArgOperand(1);
1188 
1189       // Nontemporal (unaligned) store of the 0'th element of the float/double
1190       // vector.
1191       Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
1192       PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
1193       Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
1194       Value *Extract =
1195           Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
1196 
1197       StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, 1);
1198       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1199 
1200       // Remove intrinsic.
1201       CI->eraseFromParent();
1202       return;
1203     }
1204 
1205     if (IsX86 && (Name.startswith("avx.movnt.") ||
1206                   Name.startswith("avx512.storent."))) {
1207       Module *M = F->getParent();
1208       SmallVector<Metadata *, 1> Elts;
1209       Elts.push_back(
1210           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1211       MDNode *Node = MDNode::get(C, Elts);
1212 
1213       Value *Arg0 = CI->getArgOperand(0);
1214       Value *Arg1 = CI->getArgOperand(1);
1215 
1216       // Convert the type of the pointer to a pointer to the stored type.
1217       Value *BC = Builder.CreateBitCast(Arg0,
1218                                         PointerType::getUnqual(Arg1->getType()),
1219                                         "cast");
1220       VectorType *VTy = cast<VectorType>(Arg1->getType());
1221       StoreInst *SI = Builder.CreateAlignedStore(Arg1, BC,
1222                                                  VTy->getBitWidth() / 8);
1223       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1224 
1225       // Remove intrinsic.
1226       CI->eraseFromParent();
1227       return;
1228     }
1229 
1230     if (IsX86 && Name == "sse2.storel.dq") {
1231       Value *Arg0 = CI->getArgOperand(0);
1232       Value *Arg1 = CI->getArgOperand(1);
1233 
1234       Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
1235       Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
1236       Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
1237       Value *BC = Builder.CreateBitCast(Arg0,
1238                                         PointerType::getUnqual(Elt->getType()),
1239                                         "cast");
1240       Builder.CreateAlignedStore(Elt, BC, 1);
1241 
1242       // Remove intrinsic.
1243       CI->eraseFromParent();
1244       return;
1245     }
1246 
1247     if (IsX86 && (Name.startswith("sse.storeu.") ||
1248                   Name.startswith("sse2.storeu.") ||
1249                   Name.startswith("avx.storeu."))) {
1250       Value *Arg0 = CI->getArgOperand(0);
1251       Value *Arg1 = CI->getArgOperand(1);
1252 
1253       Arg0 = Builder.CreateBitCast(Arg0,
1254                                    PointerType::getUnqual(Arg1->getType()),
1255                                    "cast");
1256       Builder.CreateAlignedStore(Arg1, Arg0, 1);
1257 
1258       // Remove intrinsic.
1259       CI->eraseFromParent();
1260       return;
1261     }
1262 
1263     if (IsX86 && (Name.startswith("avx512.mask.store"))) {
1264       // "avx512.mask.storeu." or "avx512.mask.store."
1265       bool Aligned = Name[17] != 'u'; // "avx512.mask.storeu".
1266       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1267                          CI->getArgOperand(2), Aligned);
1268 
1269       // Remove intrinsic.
1270       CI->eraseFromParent();
1271       return;
1272     }
1273 
1274     Value *Rep;
1275     // Upgrade packed integer vector compare intrinsics to compare instructions.
1276     if (IsX86 && (Name.startswith("sse2.pcmp") ||
1277                   Name.startswith("avx2.pcmp"))) {
1278       // "sse2.pcpmpeq." "sse2.pcmpgt." "avx2.pcmpeq." or "avx2.pcmpgt."
1279       bool CmpEq = Name[9] == 'e';
1280       Rep = Builder.CreateICmp(CmpEq ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_SGT,
1281                                CI->getArgOperand(0), CI->getArgOperand(1));
1282       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
1283     } else if (IsX86 && (Name.startswith("avx512.broadcastm"))) {
1284       Type *ExtTy = Type::getInt32Ty(C);
1285       if (CI->getOperand(0)->getType()->isIntegerTy(8))
1286         ExtTy = Type::getInt64Ty(C);
1287       unsigned NumElts = CI->getType()->getPrimitiveSizeInBits() /
1288                          ExtTy->getPrimitiveSizeInBits();
1289       Rep = Builder.CreateZExt(CI->getArgOperand(0), ExtTy);
1290       Rep = Builder.CreateVectorSplat(NumElts, Rep);
1291     } else if (IsX86 && (Name.startswith("avx512.ptestm") ||
1292                          Name.startswith("avx512.ptestnm"))) {
1293       Value *Op0 = CI->getArgOperand(0);
1294       Value *Op1 = CI->getArgOperand(1);
1295       Value *Mask = CI->getArgOperand(2);
1296       Rep = Builder.CreateAnd(Op0, Op1);
1297       llvm::Type *Ty = Op0->getType();
1298       Value *Zero = llvm::Constant::getNullValue(Ty);
1299       ICmpInst::Predicate Pred =
1300         Name.startswith("avx512.ptestm") ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1301       Rep = Builder.CreateICmp(Pred, Rep, Zero);
1302       unsigned NumElts = Op0->getType()->getVectorNumElements();
1303       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, Mask, NumElts);
1304     } else if (IsX86 && (Name.startswith("avx512.mask.pbroadcast"))){
1305       unsigned NumElts =
1306           CI->getArgOperand(1)->getType()->getVectorNumElements();
1307       Rep = Builder.CreateVectorSplat(NumElts, CI->getArgOperand(0));
1308       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1309                           CI->getArgOperand(1));
1310     } else if (IsX86 && (Name.startswith("avx512.kunpck"))) {
1311       unsigned NumElts = CI->getType()->getScalarSizeInBits();
1312       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), NumElts);
1313       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), NumElts);
1314       uint32_t Indices[64];
1315       for (unsigned i = 0; i != NumElts; ++i)
1316         Indices[i] = i;
1317 
1318       // First extract half of each vector. This gives better codegen than
1319       // doing it in a single shuffle.
1320       LHS = Builder.CreateShuffleVector(LHS, LHS,
1321                                         makeArrayRef(Indices, NumElts / 2));
1322       RHS = Builder.CreateShuffleVector(RHS, RHS,
1323                                         makeArrayRef(Indices, NumElts / 2));
1324       // Concat the vectors.
1325       // NOTE: Operands have to be swapped to match intrinsic definition.
1326       Rep = Builder.CreateShuffleVector(RHS, LHS,
1327                                         makeArrayRef(Indices, NumElts));
1328       Rep = Builder.CreateBitCast(Rep, CI->getType());
1329     } else if (IsX86 && Name == "avx512.kand.w") {
1330       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1331       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1332       Rep = Builder.CreateAnd(LHS, RHS);
1333       Rep = Builder.CreateBitCast(Rep, CI->getType());
1334     } else if (IsX86 && Name == "avx512.kandn.w") {
1335       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1336       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1337       LHS = Builder.CreateNot(LHS);
1338       Rep = Builder.CreateAnd(LHS, RHS);
1339       Rep = Builder.CreateBitCast(Rep, CI->getType());
1340     } else if (IsX86 && Name == "avx512.kor.w") {
1341       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1342       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1343       Rep = Builder.CreateOr(LHS, RHS);
1344       Rep = Builder.CreateBitCast(Rep, CI->getType());
1345     } else if (IsX86 && Name == "avx512.kxor.w") {
1346       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1347       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1348       Rep = Builder.CreateXor(LHS, RHS);
1349       Rep = Builder.CreateBitCast(Rep, CI->getType());
1350     } else if (IsX86 && Name == "avx512.kxnor.w") {
1351       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1352       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1353       LHS = Builder.CreateNot(LHS);
1354       Rep = Builder.CreateXor(LHS, RHS);
1355       Rep = Builder.CreateBitCast(Rep, CI->getType());
1356     } else if (IsX86 && Name == "avx512.knot.w") {
1357       Rep = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1358       Rep = Builder.CreateNot(Rep);
1359       Rep = Builder.CreateBitCast(Rep, CI->getType());
1360     } else if (IsX86 &&
1361                (Name == "avx512.kortestz.w" || Name == "avx512.kortestc.w")) {
1362       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1363       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1364       Rep = Builder.CreateOr(LHS, RHS);
1365       Rep = Builder.CreateBitCast(Rep, Builder.getInt16Ty());
1366       Value *C;
1367       if (Name[14] == 'c')
1368         C = ConstantInt::getAllOnesValue(Builder.getInt16Ty());
1369       else
1370         C = ConstantInt::getNullValue(Builder.getInt16Ty());
1371       Rep = Builder.CreateICmpEQ(Rep, C);
1372       Rep = Builder.CreateZExt(Rep, Builder.getInt32Ty());
1373     } else if (IsX86 && (Name == "sse.add.ss" || Name == "sse2.add.sd")) {
1374       Type *I32Ty = Type::getInt32Ty(C);
1375       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1376                                                  ConstantInt::get(I32Ty, 0));
1377       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1378                                                  ConstantInt::get(I32Ty, 0));
1379       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1380                                         Builder.CreateFAdd(Elt0, Elt1),
1381                                         ConstantInt::get(I32Ty, 0));
1382     } else if (IsX86 && (Name == "sse.sub.ss" || Name == "sse2.sub.sd")) {
1383       Type *I32Ty = Type::getInt32Ty(C);
1384       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1385                                                  ConstantInt::get(I32Ty, 0));
1386       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1387                                                  ConstantInt::get(I32Ty, 0));
1388       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1389                                         Builder.CreateFSub(Elt0, Elt1),
1390                                         ConstantInt::get(I32Ty, 0));
1391     } else if (IsX86 && (Name == "sse.mul.ss" || Name == "sse2.mul.sd")) {
1392       Type *I32Ty = Type::getInt32Ty(C);
1393       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1394                                                  ConstantInt::get(I32Ty, 0));
1395       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1396                                                  ConstantInt::get(I32Ty, 0));
1397       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1398                                         Builder.CreateFMul(Elt0, Elt1),
1399                                         ConstantInt::get(I32Ty, 0));
1400     } else if (IsX86 && (Name == "sse.div.ss" || Name == "sse2.div.sd")) {
1401       Type *I32Ty = Type::getInt32Ty(C);
1402       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1403                                                  ConstantInt::get(I32Ty, 0));
1404       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1405                                                  ConstantInt::get(I32Ty, 0));
1406       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1407                                         Builder.CreateFDiv(Elt0, Elt1),
1408                                         ConstantInt::get(I32Ty, 0));
1409     } else if (IsX86 && Name.startswith("avx512.mask.pcmp")) {
1410       // "avx512.mask.pcmpeq." or "avx512.mask.pcmpgt."
1411       bool CmpEq = Name[16] == 'e';
1412       Rep = upgradeMaskedCompare(Builder, *CI, CmpEq ? 0 : 6, true);
1413     } else if (IsX86 && Name.startswith("avx512.mask.cmp")) {
1414       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1415       Rep = upgradeMaskedCompare(Builder, *CI, Imm, true);
1416     } else if (IsX86 && Name.startswith("avx512.mask.ucmp")) {
1417       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1418       Rep = upgradeMaskedCompare(Builder, *CI, Imm, false);
1419     } else if (IsX86 && (Name.startswith("avx512.cvtb2mask.") ||
1420                          Name.startswith("avx512.cvtw2mask.") ||
1421                          Name.startswith("avx512.cvtd2mask.") ||
1422                          Name.startswith("avx512.cvtq2mask."))) {
1423       Value *Op = CI->getArgOperand(0);
1424       Value *Zero = llvm::Constant::getNullValue(Op->getType());
1425       Rep = Builder.CreateICmp(ICmpInst::ICMP_SLT, Op, Zero);
1426       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, nullptr,
1427                                    Op->getType()->getVectorNumElements());
1428     } else if(IsX86 && (Name == "ssse3.pabs.b.128" ||
1429                         Name == "ssse3.pabs.w.128" ||
1430                         Name == "ssse3.pabs.d.128" ||
1431                         Name.startswith("avx2.pabs") ||
1432                         Name.startswith("avx512.mask.pabs"))) {
1433       Rep = upgradeAbs(Builder, *CI);
1434     } else if (IsX86 && (Name == "sse41.pmaxsb" ||
1435                          Name == "sse2.pmaxs.w" ||
1436                          Name == "sse41.pmaxsd" ||
1437                          Name.startswith("avx2.pmaxs") ||
1438                          Name.startswith("avx512.mask.pmaxs"))) {
1439       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SGT);
1440     } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
1441                          Name == "sse41.pmaxuw" ||
1442                          Name == "sse41.pmaxud" ||
1443                          Name.startswith("avx2.pmaxu") ||
1444                          Name.startswith("avx512.mask.pmaxu"))) {
1445       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_UGT);
1446     } else if (IsX86 && (Name == "sse41.pminsb" ||
1447                          Name == "sse2.pmins.w" ||
1448                          Name == "sse41.pminsd" ||
1449                          Name.startswith("avx2.pmins") ||
1450                          Name.startswith("avx512.mask.pmins"))) {
1451       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SLT);
1452     } else if (IsX86 && (Name == "sse2.pminu.b" ||
1453                          Name == "sse41.pminuw" ||
1454                          Name == "sse41.pminud" ||
1455                          Name.startswith("avx2.pminu") ||
1456                          Name.startswith("avx512.mask.pminu"))) {
1457       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_ULT);
1458     } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
1459                          Name == "sse2.cvtps2pd" ||
1460                          Name == "avx.cvtdq2.pd.256" ||
1461                          Name == "avx.cvt.ps2.pd.256" ||
1462                          Name.startswith("avx512.mask.cvtdq2pd.") ||
1463                          Name.startswith("avx512.mask.cvtudq2pd."))) {
1464       // Lossless i32/float to double conversion.
1465       // Extract the bottom elements if necessary and convert to double vector.
1466       Value *Src = CI->getArgOperand(0);
1467       VectorType *SrcTy = cast<VectorType>(Src->getType());
1468       VectorType *DstTy = cast<VectorType>(CI->getType());
1469       Rep = CI->getArgOperand(0);
1470 
1471       unsigned NumDstElts = DstTy->getNumElements();
1472       if (NumDstElts < SrcTy->getNumElements()) {
1473         assert(NumDstElts == 2 && "Unexpected vector size");
1474         uint32_t ShuffleMask[2] = { 0, 1 };
1475         Rep = Builder.CreateShuffleVector(Rep, UndefValue::get(SrcTy),
1476                                           ShuffleMask);
1477       }
1478 
1479       bool SInt2Double = (StringRef::npos != Name.find("cvtdq2"));
1480       bool UInt2Double = (StringRef::npos != Name.find("cvtudq2"));
1481       if (SInt2Double)
1482         Rep = Builder.CreateSIToFP(Rep, DstTy, "cvtdq2pd");
1483       else if (UInt2Double)
1484         Rep = Builder.CreateUIToFP(Rep, DstTy, "cvtudq2pd");
1485       else
1486         Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
1487 
1488       if (CI->getNumArgOperands() == 3)
1489         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1490                             CI->getArgOperand(1));
1491     } else if (IsX86 && (Name.startswith("avx512.mask.loadu."))) {
1492       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
1493                               CI->getArgOperand(1), CI->getArgOperand(2),
1494                               /*Aligned*/false);
1495     } else if (IsX86 && (Name.startswith("avx512.mask.load."))) {
1496       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
1497                               CI->getArgOperand(1),CI->getArgOperand(2),
1498                               /*Aligned*/true);
1499     } else if (IsX86 && Name.startswith("xop.vpcom")) {
1500       Intrinsic::ID intID;
1501       if (Name.endswith("ub"))
1502         intID = Intrinsic::x86_xop_vpcomub;
1503       else if (Name.endswith("uw"))
1504         intID = Intrinsic::x86_xop_vpcomuw;
1505       else if (Name.endswith("ud"))
1506         intID = Intrinsic::x86_xop_vpcomud;
1507       else if (Name.endswith("uq"))
1508         intID = Intrinsic::x86_xop_vpcomuq;
1509       else if (Name.endswith("b"))
1510         intID = Intrinsic::x86_xop_vpcomb;
1511       else if (Name.endswith("w"))
1512         intID = Intrinsic::x86_xop_vpcomw;
1513       else if (Name.endswith("d"))
1514         intID = Intrinsic::x86_xop_vpcomd;
1515       else if (Name.endswith("q"))
1516         intID = Intrinsic::x86_xop_vpcomq;
1517       else
1518         llvm_unreachable("Unknown suffix");
1519 
1520       Name = Name.substr(9); // strip off "xop.vpcom"
1521       unsigned Imm;
1522       if (Name.startswith("lt"))
1523         Imm = 0;
1524       else if (Name.startswith("le"))
1525         Imm = 1;
1526       else if (Name.startswith("gt"))
1527         Imm = 2;
1528       else if (Name.startswith("ge"))
1529         Imm = 3;
1530       else if (Name.startswith("eq"))
1531         Imm = 4;
1532       else if (Name.startswith("ne"))
1533         Imm = 5;
1534       else if (Name.startswith("false"))
1535         Imm = 6;
1536       else if (Name.startswith("true"))
1537         Imm = 7;
1538       else
1539         llvm_unreachable("Unknown condition");
1540 
1541       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
1542       Rep =
1543           Builder.CreateCall(VPCOM, {CI->getArgOperand(0), CI->getArgOperand(1),
1544                                      Builder.getInt8(Imm)});
1545     } else if (IsX86 && Name.startswith("xop.vpcmov")) {
1546       Value *Sel = CI->getArgOperand(2);
1547       Value *NotSel = Builder.CreateNot(Sel);
1548       Value *Sel0 = Builder.CreateAnd(CI->getArgOperand(0), Sel);
1549       Value *Sel1 = Builder.CreateAnd(CI->getArgOperand(1), NotSel);
1550       Rep = Builder.CreateOr(Sel0, Sel1);
1551     } else if (IsX86 && Name == "sse42.crc32.64.8") {
1552       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
1553                                                Intrinsic::x86_sse42_crc32_32_8);
1554       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
1555       Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
1556       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
1557     } else if (IsX86 && Name.startswith("avx.vbroadcast.s")) {
1558       // Replace broadcasts with a series of insertelements.
1559       Type *VecTy = CI->getType();
1560       Type *EltTy = VecTy->getVectorElementType();
1561       unsigned EltNum = VecTy->getVectorNumElements();
1562       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
1563                                           EltTy->getPointerTo());
1564       Value *Load = Builder.CreateLoad(EltTy, Cast);
1565       Type *I32Ty = Type::getInt32Ty(C);
1566       Rep = UndefValue::get(VecTy);
1567       for (unsigned I = 0; I < EltNum; ++I)
1568         Rep = Builder.CreateInsertElement(Rep, Load,
1569                                           ConstantInt::get(I32Ty, I));
1570     } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
1571                          Name.startswith("sse41.pmovzx") ||
1572                          Name.startswith("avx2.pmovsx") ||
1573                          Name.startswith("avx2.pmovzx") ||
1574                          Name.startswith("avx512.mask.pmovsx") ||
1575                          Name.startswith("avx512.mask.pmovzx"))) {
1576       VectorType *SrcTy = cast<VectorType>(CI->getArgOperand(0)->getType());
1577       VectorType *DstTy = cast<VectorType>(CI->getType());
1578       unsigned NumDstElts = DstTy->getNumElements();
1579 
1580       // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
1581       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
1582       for (unsigned i = 0; i != NumDstElts; ++i)
1583         ShuffleMask[i] = i;
1584 
1585       Value *SV = Builder.CreateShuffleVector(
1586           CI->getArgOperand(0), UndefValue::get(SrcTy), ShuffleMask);
1587 
1588       bool DoSext = (StringRef::npos != Name.find("pmovsx"));
1589       Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
1590                    : Builder.CreateZExt(SV, DstTy);
1591       // If there are 3 arguments, it's a masked intrinsic so we need a select.
1592       if (CI->getNumArgOperands() == 3)
1593         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1594                             CI->getArgOperand(1));
1595     } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
1596                          Name == "avx2.vbroadcasti128")) {
1597       // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
1598       Type *EltTy = CI->getType()->getVectorElementType();
1599       unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
1600       Type *VT = VectorType::get(EltTy, NumSrcElts);
1601       Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
1602                                             PointerType::getUnqual(VT));
1603       Value *Load = Builder.CreateAlignedLoad(Op, 1);
1604       if (NumSrcElts == 2)
1605         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
1606                                           { 0, 1, 0, 1 });
1607       else
1608         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
1609                                           { 0, 1, 2, 3, 0, 1, 2, 3 });
1610     } else if (IsX86 && (Name.startswith("avx512.mask.shuf.i") ||
1611                          Name.startswith("avx512.mask.shuf.f"))) {
1612       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1613       Type *VT = CI->getType();
1614       unsigned NumLanes = VT->getPrimitiveSizeInBits() / 128;
1615       unsigned NumElementsInLane = 128 / VT->getScalarSizeInBits();
1616       unsigned ControlBitsMask = NumLanes - 1;
1617       unsigned NumControlBits = NumLanes / 2;
1618       SmallVector<uint32_t, 8> ShuffleMask(0);
1619 
1620       for (unsigned l = 0; l != NumLanes; ++l) {
1621         unsigned LaneMask = (Imm >> (l * NumControlBits)) & ControlBitsMask;
1622         // We actually need the other source.
1623         if (l >= NumLanes / 2)
1624           LaneMask += NumLanes;
1625         for (unsigned i = 0; i != NumElementsInLane; ++i)
1626           ShuffleMask.push_back(LaneMask * NumElementsInLane + i);
1627       }
1628       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
1629                                         CI->getArgOperand(1), ShuffleMask);
1630       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
1631                           CI->getArgOperand(3));
1632     }else if (IsX86 && (Name.startswith("avx512.mask.broadcastf") ||
1633                          Name.startswith("avx512.mask.broadcasti"))) {
1634       unsigned NumSrcElts =
1635                         CI->getArgOperand(0)->getType()->getVectorNumElements();
1636       unsigned NumDstElts = CI->getType()->getVectorNumElements();
1637 
1638       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
1639       for (unsigned i = 0; i != NumDstElts; ++i)
1640         ShuffleMask[i] = i % NumSrcElts;
1641 
1642       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
1643                                         CI->getArgOperand(0),
1644                                         ShuffleMask);
1645       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1646                           CI->getArgOperand(1));
1647     } else if (IsX86 && (Name.startswith("avx2.pbroadcast") ||
1648                          Name.startswith("avx2.vbroadcast") ||
1649                          Name.startswith("avx512.pbroadcast") ||
1650                          Name.startswith("avx512.mask.broadcast.s"))) {
1651       // Replace vp?broadcasts with a vector shuffle.
1652       Value *Op = CI->getArgOperand(0);
1653       unsigned NumElts = CI->getType()->getVectorNumElements();
1654       Type *MaskTy = VectorType::get(Type::getInt32Ty(C), NumElts);
1655       Rep = Builder.CreateShuffleVector(Op, UndefValue::get(Op->getType()),
1656                                         Constant::getNullValue(MaskTy));
1657 
1658       if (CI->getNumArgOperands() == 3)
1659         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1660                             CI->getArgOperand(1));
1661     } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
1662       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
1663                                       CI->getArgOperand(1),
1664                                       CI->getArgOperand(2),
1665                                       CI->getArgOperand(3),
1666                                       CI->getArgOperand(4),
1667                                       false);
1668     } else if (IsX86 && Name.startswith("avx512.mask.valign.")) {
1669       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
1670                                       CI->getArgOperand(1),
1671                                       CI->getArgOperand(2),
1672                                       CI->getArgOperand(3),
1673                                       CI->getArgOperand(4),
1674                                       true);
1675     } else if (IsX86 && (Name == "sse2.psll.dq" ||
1676                          Name == "avx2.psll.dq")) {
1677       // 128/256-bit shift left specified in bits.
1678       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1679       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
1680                                        Shift / 8); // Shift is in bits.
1681     } else if (IsX86 && (Name == "sse2.psrl.dq" ||
1682                          Name == "avx2.psrl.dq")) {
1683       // 128/256-bit shift right specified in bits.
1684       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1685       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
1686                                        Shift / 8); // Shift is in bits.
1687     } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
1688                          Name == "avx2.psll.dq.bs" ||
1689                          Name == "avx512.psll.dq.512")) {
1690       // 128/256/512-bit shift left specified in bytes.
1691       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1692       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
1693     } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
1694                          Name == "avx2.psrl.dq.bs" ||
1695                          Name == "avx512.psrl.dq.512")) {
1696       // 128/256/512-bit shift right specified in bytes.
1697       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1698       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
1699     } else if (IsX86 && (Name == "sse41.pblendw" ||
1700                          Name.startswith("sse41.blendp") ||
1701                          Name.startswith("avx.blend.p") ||
1702                          Name == "avx2.pblendw" ||
1703                          Name.startswith("avx2.pblendd."))) {
1704       Value *Op0 = CI->getArgOperand(0);
1705       Value *Op1 = CI->getArgOperand(1);
1706       unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1707       VectorType *VecTy = cast<VectorType>(CI->getType());
1708       unsigned NumElts = VecTy->getNumElements();
1709 
1710       SmallVector<uint32_t, 16> Idxs(NumElts);
1711       for (unsigned i = 0; i != NumElts; ++i)
1712         Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
1713 
1714       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1715     } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
1716                          Name == "avx2.vinserti128" ||
1717                          Name.startswith("avx512.mask.insert"))) {
1718       Value *Op0 = CI->getArgOperand(0);
1719       Value *Op1 = CI->getArgOperand(1);
1720       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1721       unsigned DstNumElts = CI->getType()->getVectorNumElements();
1722       unsigned SrcNumElts = Op1->getType()->getVectorNumElements();
1723       unsigned Scale = DstNumElts / SrcNumElts;
1724 
1725       // Mask off the high bits of the immediate value; hardware ignores those.
1726       Imm = Imm % Scale;
1727 
1728       // Extend the second operand into a vector the size of the destination.
1729       Value *UndefV = UndefValue::get(Op1->getType());
1730       SmallVector<uint32_t, 8> Idxs(DstNumElts);
1731       for (unsigned i = 0; i != SrcNumElts; ++i)
1732         Idxs[i] = i;
1733       for (unsigned i = SrcNumElts; i != DstNumElts; ++i)
1734         Idxs[i] = SrcNumElts;
1735       Rep = Builder.CreateShuffleVector(Op1, UndefV, Idxs);
1736 
1737       // Insert the second operand into the first operand.
1738 
1739       // Note that there is no guarantee that instruction lowering will actually
1740       // produce a vinsertf128 instruction for the created shuffles. In
1741       // particular, the 0 immediate case involves no lane changes, so it can
1742       // be handled as a blend.
1743 
1744       // Example of shuffle mask for 32-bit elements:
1745       // Imm = 1  <i32 0, i32 1, i32 2,  i32 3,  i32 8, i32 9, i32 10, i32 11>
1746       // Imm = 0  <i32 8, i32 9, i32 10, i32 11, i32 4, i32 5, i32 6,  i32 7 >
1747 
1748       // First fill with identify mask.
1749       for (unsigned i = 0; i != DstNumElts; ++i)
1750         Idxs[i] = i;
1751       // Then replace the elements where we need to insert.
1752       for (unsigned i = 0; i != SrcNumElts; ++i)
1753         Idxs[i + Imm * SrcNumElts] = i + DstNumElts;
1754       Rep = Builder.CreateShuffleVector(Op0, Rep, Idxs);
1755 
1756       // If the intrinsic has a mask operand, handle that.
1757       if (CI->getNumArgOperands() == 5)
1758         Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
1759                             CI->getArgOperand(3));
1760     } else if (IsX86 && (Name.startswith("avx.vextractf128.") ||
1761                          Name == "avx2.vextracti128" ||
1762                          Name.startswith("avx512.mask.vextract"))) {
1763       Value *Op0 = CI->getArgOperand(0);
1764       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1765       unsigned DstNumElts = CI->getType()->getVectorNumElements();
1766       unsigned SrcNumElts = Op0->getType()->getVectorNumElements();
1767       unsigned Scale = SrcNumElts / DstNumElts;
1768 
1769       // Mask off the high bits of the immediate value; hardware ignores those.
1770       Imm = Imm % Scale;
1771 
1772       // Get indexes for the subvector of the input vector.
1773       SmallVector<uint32_t, 8> Idxs(DstNumElts);
1774       for (unsigned i = 0; i != DstNumElts; ++i) {
1775         Idxs[i] = i + (Imm * DstNumElts);
1776       }
1777       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1778 
1779       // If the intrinsic has a mask operand, handle that.
1780       if (CI->getNumArgOperands() == 4)
1781         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1782                             CI->getArgOperand(2));
1783     } else if (!IsX86 && Name == "stackprotectorcheck") {
1784       Rep = nullptr;
1785     } else if (IsX86 && (Name.startswith("avx512.mask.perm.df.") ||
1786                          Name.startswith("avx512.mask.perm.di."))) {
1787       Value *Op0 = CI->getArgOperand(0);
1788       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1789       VectorType *VecTy = cast<VectorType>(CI->getType());
1790       unsigned NumElts = VecTy->getNumElements();
1791 
1792       SmallVector<uint32_t, 8> Idxs(NumElts);
1793       for (unsigned i = 0; i != NumElts; ++i)
1794         Idxs[i] = (i & ~0x3) + ((Imm >> (2 * (i & 0x3))) & 3);
1795 
1796       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1797 
1798       if (CI->getNumArgOperands() == 4)
1799         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1800                             CI->getArgOperand(2));
1801     } else if (IsX86 && (Name.startswith("avx.vperm2f128.") ||
1802                          Name == "avx2.vperm2i128")) {
1803       // The immediate permute control byte looks like this:
1804       //    [1:0] - select 128 bits from sources for low half of destination
1805       //    [2]   - ignore
1806       //    [3]   - zero low half of destination
1807       //    [5:4] - select 128 bits from sources for high half of destination
1808       //    [6]   - ignore
1809       //    [7]   - zero high half of destination
1810 
1811       uint8_t Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1812 
1813       unsigned NumElts = CI->getType()->getVectorNumElements();
1814       unsigned HalfSize = NumElts / 2;
1815       SmallVector<uint32_t, 8> ShuffleMask(NumElts);
1816 
1817       // Determine which operand(s) are actually in use for this instruction.
1818       Value *V0 = (Imm & 0x02) ? CI->getArgOperand(1) : CI->getArgOperand(0);
1819       Value *V1 = (Imm & 0x20) ? CI->getArgOperand(1) : CI->getArgOperand(0);
1820 
1821       // If needed, replace operands based on zero mask.
1822       V0 = (Imm & 0x08) ? ConstantAggregateZero::get(CI->getType()) : V0;
1823       V1 = (Imm & 0x80) ? ConstantAggregateZero::get(CI->getType()) : V1;
1824 
1825       // Permute low half of result.
1826       unsigned StartIndex = (Imm & 0x01) ? HalfSize : 0;
1827       for (unsigned i = 0; i < HalfSize; ++i)
1828         ShuffleMask[i] = StartIndex + i;
1829 
1830       // Permute high half of result.
1831       StartIndex = (Imm & 0x10) ? HalfSize : 0;
1832       for (unsigned i = 0; i < HalfSize; ++i)
1833         ShuffleMask[i + HalfSize] = NumElts + StartIndex + i;
1834 
1835       Rep = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
1836 
1837     } else if (IsX86 && (Name.startswith("avx.vpermil.") ||
1838                          Name == "sse2.pshuf.d" ||
1839                          Name.startswith("avx512.mask.vpermil.p") ||
1840                          Name.startswith("avx512.mask.pshuf.d."))) {
1841       Value *Op0 = CI->getArgOperand(0);
1842       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1843       VectorType *VecTy = cast<VectorType>(CI->getType());
1844       unsigned NumElts = VecTy->getNumElements();
1845       // Calculate the size of each index in the immediate.
1846       unsigned IdxSize = 64 / VecTy->getScalarSizeInBits();
1847       unsigned IdxMask = ((1 << IdxSize) - 1);
1848 
1849       SmallVector<uint32_t, 8> Idxs(NumElts);
1850       // Lookup the bits for this element, wrapping around the immediate every
1851       // 8-bits. Elements are grouped into sets of 2 or 4 elements so we need
1852       // to offset by the first index of each group.
1853       for (unsigned i = 0; i != NumElts; ++i)
1854         Idxs[i] = ((Imm >> ((i * IdxSize) % 8)) & IdxMask) | (i & ~IdxMask);
1855 
1856       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1857 
1858       if (CI->getNumArgOperands() == 4)
1859         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1860                             CI->getArgOperand(2));
1861     } else if (IsX86 && (Name == "sse2.pshufl.w" ||
1862                          Name.startswith("avx512.mask.pshufl.w."))) {
1863       Value *Op0 = CI->getArgOperand(0);
1864       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1865       unsigned NumElts = CI->getType()->getVectorNumElements();
1866 
1867       SmallVector<uint32_t, 16> Idxs(NumElts);
1868       for (unsigned l = 0; l != NumElts; l += 8) {
1869         for (unsigned i = 0; i != 4; ++i)
1870           Idxs[i + l] = ((Imm >> (2 * i)) & 0x3) + l;
1871         for (unsigned i = 4; i != 8; ++i)
1872           Idxs[i + l] = i + l;
1873       }
1874 
1875       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1876 
1877       if (CI->getNumArgOperands() == 4)
1878         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1879                             CI->getArgOperand(2));
1880     } else if (IsX86 && (Name == "sse2.pshufh.w" ||
1881                          Name.startswith("avx512.mask.pshufh.w."))) {
1882       Value *Op0 = CI->getArgOperand(0);
1883       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1884       unsigned NumElts = CI->getType()->getVectorNumElements();
1885 
1886       SmallVector<uint32_t, 16> Idxs(NumElts);
1887       for (unsigned l = 0; l != NumElts; l += 8) {
1888         for (unsigned i = 0; i != 4; ++i)
1889           Idxs[i + l] = i + l;
1890         for (unsigned i = 0; i != 4; ++i)
1891           Idxs[i + l + 4] = ((Imm >> (2 * i)) & 0x3) + 4 + l;
1892       }
1893 
1894       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1895 
1896       if (CI->getNumArgOperands() == 4)
1897         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1898                             CI->getArgOperand(2));
1899     } else if (IsX86 && Name.startswith("avx512.mask.shuf.p")) {
1900       Value *Op0 = CI->getArgOperand(0);
1901       Value *Op1 = CI->getArgOperand(1);
1902       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1903       unsigned NumElts = CI->getType()->getVectorNumElements();
1904 
1905       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1906       unsigned HalfLaneElts = NumLaneElts / 2;
1907 
1908       SmallVector<uint32_t, 16> Idxs(NumElts);
1909       for (unsigned i = 0; i != NumElts; ++i) {
1910         // Base index is the starting element of the lane.
1911         Idxs[i] = i - (i % NumLaneElts);
1912         // If we are half way through the lane switch to the other source.
1913         if ((i % NumLaneElts) >= HalfLaneElts)
1914           Idxs[i] += NumElts;
1915         // Now select the specific element. By adding HalfLaneElts bits from
1916         // the immediate. Wrapping around the immediate every 8-bits.
1917         Idxs[i] += (Imm >> ((i * HalfLaneElts) % 8)) & ((1 << HalfLaneElts) - 1);
1918       }
1919 
1920       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1921 
1922       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
1923                           CI->getArgOperand(3));
1924     } else if (IsX86 && (Name.startswith("avx512.mask.movddup") ||
1925                          Name.startswith("avx512.mask.movshdup") ||
1926                          Name.startswith("avx512.mask.movsldup"))) {
1927       Value *Op0 = CI->getArgOperand(0);
1928       unsigned NumElts = CI->getType()->getVectorNumElements();
1929       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1930 
1931       unsigned Offset = 0;
1932       if (Name.startswith("avx512.mask.movshdup."))
1933         Offset = 1;
1934 
1935       SmallVector<uint32_t, 16> Idxs(NumElts);
1936       for (unsigned l = 0; l != NumElts; l += NumLaneElts)
1937         for (unsigned i = 0; i != NumLaneElts; i += 2) {
1938           Idxs[i + l + 0] = i + l + Offset;
1939           Idxs[i + l + 1] = i + l + Offset;
1940         }
1941 
1942       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1943 
1944       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1945                           CI->getArgOperand(1));
1946     } else if (IsX86 && (Name.startswith("avx512.mask.punpckl") ||
1947                          Name.startswith("avx512.mask.unpckl."))) {
1948       Value *Op0 = CI->getArgOperand(0);
1949       Value *Op1 = CI->getArgOperand(1);
1950       int NumElts = CI->getType()->getVectorNumElements();
1951       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1952 
1953       SmallVector<uint32_t, 64> Idxs(NumElts);
1954       for (int l = 0; l != NumElts; l += NumLaneElts)
1955         for (int i = 0; i != NumLaneElts; ++i)
1956           Idxs[i + l] = l + (i / 2) + NumElts * (i % 2);
1957 
1958       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1959 
1960       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1961                           CI->getArgOperand(2));
1962     } else if (IsX86 && (Name.startswith("avx512.mask.punpckh") ||
1963                          Name.startswith("avx512.mask.unpckh."))) {
1964       Value *Op0 = CI->getArgOperand(0);
1965       Value *Op1 = CI->getArgOperand(1);
1966       int NumElts = CI->getType()->getVectorNumElements();
1967       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
1968 
1969       SmallVector<uint32_t, 64> Idxs(NumElts);
1970       for (int l = 0; l != NumElts; l += NumLaneElts)
1971         for (int i = 0; i != NumLaneElts; ++i)
1972           Idxs[i + l] = (NumLaneElts / 2) + l + (i / 2) + NumElts * (i % 2);
1973 
1974       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1975 
1976       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1977                           CI->getArgOperand(2));
1978     } else if (IsX86 && Name.startswith("avx512.mask.pand.")) {
1979       Rep = Builder.CreateAnd(CI->getArgOperand(0), CI->getArgOperand(1));
1980       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1981                           CI->getArgOperand(2));
1982     } else if (IsX86 && Name.startswith("avx512.mask.pandn.")) {
1983       Rep = Builder.CreateAnd(Builder.CreateNot(CI->getArgOperand(0)),
1984                               CI->getArgOperand(1));
1985       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1986                           CI->getArgOperand(2));
1987     } else if (IsX86 && Name.startswith("avx512.mask.por.")) {
1988       Rep = Builder.CreateOr(CI->getArgOperand(0), CI->getArgOperand(1));
1989       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1990                           CI->getArgOperand(2));
1991     } else if (IsX86 && Name.startswith("avx512.mask.pxor.")) {
1992       Rep = Builder.CreateXor(CI->getArgOperand(0), CI->getArgOperand(1));
1993       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1994                           CI->getArgOperand(2));
1995     } else if (IsX86 && Name.startswith("avx512.mask.and.")) {
1996       VectorType *FTy = cast<VectorType>(CI->getType());
1997       VectorType *ITy = VectorType::getInteger(FTy);
1998       Rep = Builder.CreateAnd(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
1999                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2000       Rep = Builder.CreateBitCast(Rep, FTy);
2001       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2002                           CI->getArgOperand(2));
2003     } else if (IsX86 && Name.startswith("avx512.mask.andn.")) {
2004       VectorType *FTy = cast<VectorType>(CI->getType());
2005       VectorType *ITy = VectorType::getInteger(FTy);
2006       Rep = Builder.CreateNot(Builder.CreateBitCast(CI->getArgOperand(0), ITy));
2007       Rep = Builder.CreateAnd(Rep,
2008                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2009       Rep = Builder.CreateBitCast(Rep, FTy);
2010       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2011                           CI->getArgOperand(2));
2012     } else if (IsX86 && Name.startswith("avx512.mask.or.")) {
2013       VectorType *FTy = cast<VectorType>(CI->getType());
2014       VectorType *ITy = VectorType::getInteger(FTy);
2015       Rep = Builder.CreateOr(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2016                              Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2017       Rep = Builder.CreateBitCast(Rep, FTy);
2018       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2019                           CI->getArgOperand(2));
2020     } else if (IsX86 && Name.startswith("avx512.mask.xor.")) {
2021       VectorType *FTy = cast<VectorType>(CI->getType());
2022       VectorType *ITy = VectorType::getInteger(FTy);
2023       Rep = Builder.CreateXor(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2024                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2025       Rep = Builder.CreateBitCast(Rep, FTy);
2026       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2027                           CI->getArgOperand(2));
2028     } else if (IsX86 && Name.startswith("avx512.mask.padd.")) {
2029       Rep = Builder.CreateAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2030       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2031                           CI->getArgOperand(2));
2032     } else if (IsX86 && Name.startswith("avx512.mask.psub.")) {
2033       Rep = Builder.CreateSub(CI->getArgOperand(0), CI->getArgOperand(1));
2034       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2035                           CI->getArgOperand(2));
2036     } else if (IsX86 && Name.startswith("avx512.mask.pmull.")) {
2037       Rep = Builder.CreateMul(CI->getArgOperand(0), CI->getArgOperand(1));
2038       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2039                           CI->getArgOperand(2));
2040     } else if (IsX86 && (Name.startswith("avx512.mask.add.p"))) {
2041       Rep = Builder.CreateFAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2042       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2043                           CI->getArgOperand(2));
2044     } else if (IsX86 && Name.startswith("avx512.mask.div.p")) {
2045       Rep = Builder.CreateFDiv(CI->getArgOperand(0), CI->getArgOperand(1));
2046       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2047                           CI->getArgOperand(2));
2048     } else if (IsX86 && Name.startswith("avx512.mask.mul.p")) {
2049       Rep = Builder.CreateFMul(CI->getArgOperand(0), CI->getArgOperand(1));
2050       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2051                           CI->getArgOperand(2));
2052     } else if (IsX86 && Name.startswith("avx512.mask.sub.p")) {
2053       Rep = Builder.CreateFSub(CI->getArgOperand(0), CI->getArgOperand(1));
2054       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2055                           CI->getArgOperand(2));
2056     } else if (IsX86 && Name.startswith("avx512.mask.lzcnt.")) {
2057       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
2058                                                          Intrinsic::ctlz,
2059                                                          CI->getType()),
2060                                { CI->getArgOperand(0), Builder.getInt1(false) });
2061       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2062                           CI->getArgOperand(1));
2063     } else if (IsX86 && Name.startswith("avx512.mask.psll")) {
2064       bool IsImmediate = Name[16] == 'i' ||
2065                          (Name.size() > 18 && Name[18] == 'i');
2066       bool IsVariable = Name[16] == 'v';
2067       char Size = Name[16] == '.' ? Name[17] :
2068                   Name[17] == '.' ? Name[18] :
2069                   Name[18] == '.' ? Name[19] :
2070                                     Name[20];
2071 
2072       Intrinsic::ID IID;
2073       if (IsVariable && Name[17] != '.') {
2074         if (Size == 'd' && Name[17] == '2') // avx512.mask.psllv2.di
2075           IID = Intrinsic::x86_avx2_psllv_q;
2076         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psllv4.di
2077           IID = Intrinsic::x86_avx2_psllv_q_256;
2078         else if (Size == 's' && Name[17] == '4') // avx512.mask.psllv4.si
2079           IID = Intrinsic::x86_avx2_psllv_d;
2080         else if (Size == 's' && Name[17] == '8') // avx512.mask.psllv8.si
2081           IID = Intrinsic::x86_avx2_psllv_d_256;
2082         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psllv8.hi
2083           IID = Intrinsic::x86_avx512_psllv_w_128;
2084         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psllv16.hi
2085           IID = Intrinsic::x86_avx512_psllv_w_256;
2086         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psllv32hi
2087           IID = Intrinsic::x86_avx512_psllv_w_512;
2088         else
2089           llvm_unreachable("Unexpected size");
2090       } else if (Name.endswith(".128")) {
2091         if (Size == 'd') // avx512.mask.psll.d.128, avx512.mask.psll.di.128
2092           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_d
2093                             : Intrinsic::x86_sse2_psll_d;
2094         else if (Size == 'q') // avx512.mask.psll.q.128, avx512.mask.psll.qi.128
2095           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_q
2096                             : Intrinsic::x86_sse2_psll_q;
2097         else if (Size == 'w') // avx512.mask.psll.w.128, avx512.mask.psll.wi.128
2098           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_w
2099                             : Intrinsic::x86_sse2_psll_w;
2100         else
2101           llvm_unreachable("Unexpected size");
2102       } else if (Name.endswith(".256")) {
2103         if (Size == 'd') // avx512.mask.psll.d.256, avx512.mask.psll.di.256
2104           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_d
2105                             : Intrinsic::x86_avx2_psll_d;
2106         else if (Size == 'q') // avx512.mask.psll.q.256, avx512.mask.psll.qi.256
2107           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_q
2108                             : Intrinsic::x86_avx2_psll_q;
2109         else if (Size == 'w') // avx512.mask.psll.w.256, avx512.mask.psll.wi.256
2110           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_w
2111                             : Intrinsic::x86_avx2_psll_w;
2112         else
2113           llvm_unreachable("Unexpected size");
2114       } else {
2115         if (Size == 'd') // psll.di.512, pslli.d, psll.d, psllv.d.512
2116           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_d_512 :
2117                 IsVariable  ? Intrinsic::x86_avx512_psllv_d_512 :
2118                               Intrinsic::x86_avx512_psll_d_512;
2119         else if (Size == 'q') // psll.qi.512, pslli.q, psll.q, psllv.q.512
2120           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_q_512 :
2121                 IsVariable  ? Intrinsic::x86_avx512_psllv_q_512 :
2122                               Intrinsic::x86_avx512_psll_q_512;
2123         else if (Size == 'w') // psll.wi.512, pslli.w, psll.w
2124           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_w_512
2125                             : Intrinsic::x86_avx512_psll_w_512;
2126         else
2127           llvm_unreachable("Unexpected size");
2128       }
2129 
2130       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2131     } else if (IsX86 && Name.startswith("avx512.mask.psrl")) {
2132       bool IsImmediate = Name[16] == 'i' ||
2133                          (Name.size() > 18 && Name[18] == 'i');
2134       bool IsVariable = Name[16] == 'v';
2135       char Size = Name[16] == '.' ? Name[17] :
2136                   Name[17] == '.' ? Name[18] :
2137                   Name[18] == '.' ? Name[19] :
2138                                     Name[20];
2139 
2140       Intrinsic::ID IID;
2141       if (IsVariable && Name[17] != '.') {
2142         if (Size == 'd' && Name[17] == '2') // avx512.mask.psrlv2.di
2143           IID = Intrinsic::x86_avx2_psrlv_q;
2144         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psrlv4.di
2145           IID = Intrinsic::x86_avx2_psrlv_q_256;
2146         else if (Size == 's' && Name[17] == '4') // avx512.mask.psrlv4.si
2147           IID = Intrinsic::x86_avx2_psrlv_d;
2148         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrlv8.si
2149           IID = Intrinsic::x86_avx2_psrlv_d_256;
2150         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrlv8.hi
2151           IID = Intrinsic::x86_avx512_psrlv_w_128;
2152         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrlv16.hi
2153           IID = Intrinsic::x86_avx512_psrlv_w_256;
2154         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrlv32hi
2155           IID = Intrinsic::x86_avx512_psrlv_w_512;
2156         else
2157           llvm_unreachable("Unexpected size");
2158       } else if (Name.endswith(".128")) {
2159         if (Size == 'd') // avx512.mask.psrl.d.128, avx512.mask.psrl.di.128
2160           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_d
2161                             : Intrinsic::x86_sse2_psrl_d;
2162         else if (Size == 'q') // avx512.mask.psrl.q.128, avx512.mask.psrl.qi.128
2163           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_q
2164                             : Intrinsic::x86_sse2_psrl_q;
2165         else if (Size == 'w') // avx512.mask.psrl.w.128, avx512.mask.psrl.wi.128
2166           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_w
2167                             : Intrinsic::x86_sse2_psrl_w;
2168         else
2169           llvm_unreachable("Unexpected size");
2170       } else if (Name.endswith(".256")) {
2171         if (Size == 'd') // avx512.mask.psrl.d.256, avx512.mask.psrl.di.256
2172           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_d
2173                             : Intrinsic::x86_avx2_psrl_d;
2174         else if (Size == 'q') // avx512.mask.psrl.q.256, avx512.mask.psrl.qi.256
2175           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_q
2176                             : Intrinsic::x86_avx2_psrl_q;
2177         else if (Size == 'w') // avx512.mask.psrl.w.256, avx512.mask.psrl.wi.256
2178           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_w
2179                             : Intrinsic::x86_avx2_psrl_w;
2180         else
2181           llvm_unreachable("Unexpected size");
2182       } else {
2183         if (Size == 'd') // psrl.di.512, psrli.d, psrl.d, psrl.d.512
2184           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_d_512 :
2185                 IsVariable  ? Intrinsic::x86_avx512_psrlv_d_512 :
2186                               Intrinsic::x86_avx512_psrl_d_512;
2187         else if (Size == 'q') // psrl.qi.512, psrli.q, psrl.q, psrl.q.512
2188           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_q_512 :
2189                 IsVariable  ? Intrinsic::x86_avx512_psrlv_q_512 :
2190                               Intrinsic::x86_avx512_psrl_q_512;
2191         else if (Size == 'w') // psrl.wi.512, psrli.w, psrl.w)
2192           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_w_512
2193                             : Intrinsic::x86_avx512_psrl_w_512;
2194         else
2195           llvm_unreachable("Unexpected size");
2196       }
2197 
2198       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2199     } else if (IsX86 && Name.startswith("avx512.mask.psra")) {
2200       bool IsImmediate = Name[16] == 'i' ||
2201                          (Name.size() > 18 && Name[18] == 'i');
2202       bool IsVariable = Name[16] == 'v';
2203       char Size = Name[16] == '.' ? Name[17] :
2204                   Name[17] == '.' ? Name[18] :
2205                   Name[18] == '.' ? Name[19] :
2206                                     Name[20];
2207 
2208       Intrinsic::ID IID;
2209       if (IsVariable && Name[17] != '.') {
2210         if (Size == 's' && Name[17] == '4') // avx512.mask.psrav4.si
2211           IID = Intrinsic::x86_avx2_psrav_d;
2212         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrav8.si
2213           IID = Intrinsic::x86_avx2_psrav_d_256;
2214         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrav8.hi
2215           IID = Intrinsic::x86_avx512_psrav_w_128;
2216         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrav16.hi
2217           IID = Intrinsic::x86_avx512_psrav_w_256;
2218         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrav32hi
2219           IID = Intrinsic::x86_avx512_psrav_w_512;
2220         else
2221           llvm_unreachable("Unexpected size");
2222       } else if (Name.endswith(".128")) {
2223         if (Size == 'd') // avx512.mask.psra.d.128, avx512.mask.psra.di.128
2224           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_d
2225                             : Intrinsic::x86_sse2_psra_d;
2226         else if (Size == 'q') // avx512.mask.psra.q.128, avx512.mask.psra.qi.128
2227           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_128 :
2228                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_128 :
2229                               Intrinsic::x86_avx512_psra_q_128;
2230         else if (Size == 'w') // avx512.mask.psra.w.128, avx512.mask.psra.wi.128
2231           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_w
2232                             : Intrinsic::x86_sse2_psra_w;
2233         else
2234           llvm_unreachable("Unexpected size");
2235       } else if (Name.endswith(".256")) {
2236         if (Size == 'd') // avx512.mask.psra.d.256, avx512.mask.psra.di.256
2237           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_d
2238                             : Intrinsic::x86_avx2_psra_d;
2239         else if (Size == 'q') // avx512.mask.psra.q.256, avx512.mask.psra.qi.256
2240           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_256 :
2241                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_256 :
2242                               Intrinsic::x86_avx512_psra_q_256;
2243         else if (Size == 'w') // avx512.mask.psra.w.256, avx512.mask.psra.wi.256
2244           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_w
2245                             : Intrinsic::x86_avx2_psra_w;
2246         else
2247           llvm_unreachable("Unexpected size");
2248       } else {
2249         if (Size == 'd') // psra.di.512, psrai.d, psra.d, psrav.d.512
2250           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_d_512 :
2251                 IsVariable  ? Intrinsic::x86_avx512_psrav_d_512 :
2252                               Intrinsic::x86_avx512_psra_d_512;
2253         else if (Size == 'q') // psra.qi.512, psrai.q, psra.q
2254           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_512 :
2255                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_512 :
2256                               Intrinsic::x86_avx512_psra_q_512;
2257         else if (Size == 'w') // psra.wi.512, psrai.w, psra.w
2258           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_w_512
2259                             : Intrinsic::x86_avx512_psra_w_512;
2260         else
2261           llvm_unreachable("Unexpected size");
2262       }
2263 
2264       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2265     } else if (IsX86 && Name.startswith("avx512.mask.move.s")) {
2266       Rep = upgradeMaskedMove(Builder, *CI);
2267     } else if (IsX86 && Name.startswith("avx512.cvtmask2")) {
2268       Rep = UpgradeMaskToInt(Builder, *CI);
2269     } else if (IsX86 && Name.endswith(".movntdqa")) {
2270       Module *M = F->getParent();
2271       MDNode *Node = MDNode::get(
2272           C, ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
2273 
2274       Value *Ptr = CI->getArgOperand(0);
2275       VectorType *VTy = cast<VectorType>(CI->getType());
2276 
2277       // Convert the type of the pointer to a pointer to the stored type.
2278       Value *BC =
2279           Builder.CreateBitCast(Ptr, PointerType::getUnqual(VTy), "cast");
2280       LoadInst *LI = Builder.CreateAlignedLoad(BC, VTy->getBitWidth() / 8);
2281       LI->setMetadata(M->getMDKindID("nontemporal"), Node);
2282       Rep = LI;
2283     } else if (IsX86 &&
2284                (Name.startswith("sse2.pavg") || Name.startswith("avx2.pavg") ||
2285                 Name.startswith("avx512.mask.pavg"))) {
2286       // llvm.x86.sse2.pavg.b/w, llvm.x86.avx2.pavg.b/w,
2287       // llvm.x86.avx512.mask.pavg.b/w
2288       Value *A = CI->getArgOperand(0);
2289       Value *B = CI->getArgOperand(1);
2290       VectorType *ZextType = VectorType::getExtendedElementVectorType(
2291           cast<VectorType>(A->getType()));
2292       Value *ExtendedA = Builder.CreateZExt(A, ZextType);
2293       Value *ExtendedB = Builder.CreateZExt(B, ZextType);
2294       Value *Sum = Builder.CreateAdd(ExtendedA, ExtendedB);
2295       Value *AddOne = Builder.CreateAdd(Sum, ConstantInt::get(ZextType, 1));
2296       Value *ShiftR = Builder.CreateLShr(AddOne, ConstantInt::get(ZextType, 1));
2297       Rep = Builder.CreateTrunc(ShiftR, A->getType());
2298       if (CI->getNumArgOperands() > 2) {
2299         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2300                             CI->getArgOperand(2));
2301       }
2302     } else if (IsX86 && Name.startswith("avx512.mask.") &&
2303                upgradeAVX512MaskToSelect(Name, Builder, *CI, Rep)) {
2304       // Rep will be updated by the call in the condition.
2305     } else if (IsNVVM && (Name == "abs.i" || Name == "abs.ll")) {
2306       Value *Arg = CI->getArgOperand(0);
2307       Value *Neg = Builder.CreateNeg(Arg, "neg");
2308       Value *Cmp = Builder.CreateICmpSGE(
2309           Arg, llvm::Constant::getNullValue(Arg->getType()), "abs.cond");
2310       Rep = Builder.CreateSelect(Cmp, Arg, Neg, "abs");
2311     } else if (IsNVVM && (Name == "max.i" || Name == "max.ll" ||
2312                           Name == "max.ui" || Name == "max.ull")) {
2313       Value *Arg0 = CI->getArgOperand(0);
2314       Value *Arg1 = CI->getArgOperand(1);
2315       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
2316                        ? Builder.CreateICmpUGE(Arg0, Arg1, "max.cond")
2317                        : Builder.CreateICmpSGE(Arg0, Arg1, "max.cond");
2318       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "max");
2319     } else if (IsNVVM && (Name == "min.i" || Name == "min.ll" ||
2320                           Name == "min.ui" || Name == "min.ull")) {
2321       Value *Arg0 = CI->getArgOperand(0);
2322       Value *Arg1 = CI->getArgOperand(1);
2323       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
2324                        ? Builder.CreateICmpULE(Arg0, Arg1, "min.cond")
2325                        : Builder.CreateICmpSLE(Arg0, Arg1, "min.cond");
2326       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "min");
2327     } else if (IsNVVM && Name == "clz.ll") {
2328       // llvm.nvvm.clz.ll returns an i32, but llvm.ctlz.i64 and returns an i64.
2329       Value *Arg = CI->getArgOperand(0);
2330       Value *Ctlz = Builder.CreateCall(
2331           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
2332                                     {Arg->getType()}),
2333           {Arg, Builder.getFalse()}, "ctlz");
2334       Rep = Builder.CreateTrunc(Ctlz, Builder.getInt32Ty(), "ctlz.trunc");
2335     } else if (IsNVVM && Name == "popc.ll") {
2336       // llvm.nvvm.popc.ll returns an i32, but llvm.ctpop.i64 and returns an
2337       // i64.
2338       Value *Arg = CI->getArgOperand(0);
2339       Value *Popc = Builder.CreateCall(
2340           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
2341                                     {Arg->getType()}),
2342           Arg, "ctpop");
2343       Rep = Builder.CreateTrunc(Popc, Builder.getInt32Ty(), "ctpop.trunc");
2344     } else if (IsNVVM && Name == "h2f") {
2345       Rep = Builder.CreateCall(Intrinsic::getDeclaration(
2346                                    F->getParent(), Intrinsic::convert_from_fp16,
2347                                    {Builder.getFloatTy()}),
2348                                CI->getArgOperand(0), "h2f");
2349     } else {
2350       llvm_unreachable("Unknown function for CallInst upgrade.");
2351     }
2352 
2353     if (Rep)
2354       CI->replaceAllUsesWith(Rep);
2355     CI->eraseFromParent();
2356     return;
2357   }
2358 
2359   const auto &DefaultCase = [&NewFn, &CI]() -> void {
2360     // Handle generic mangling change, but nothing else
2361     assert(
2362         (CI->getCalledFunction()->getName() != NewFn->getName()) &&
2363         "Unknown function for CallInst upgrade and isn't just a name change");
2364     CI->setCalledFunction(NewFn);
2365   };
2366   CallInst *NewCall = nullptr;
2367   switch (NewFn->getIntrinsicID()) {
2368   default: {
2369     DefaultCase();
2370     return;
2371   }
2372 
2373   case Intrinsic::arm_neon_vld1:
2374   case Intrinsic::arm_neon_vld2:
2375   case Intrinsic::arm_neon_vld3:
2376   case Intrinsic::arm_neon_vld4:
2377   case Intrinsic::arm_neon_vld2lane:
2378   case Intrinsic::arm_neon_vld3lane:
2379   case Intrinsic::arm_neon_vld4lane:
2380   case Intrinsic::arm_neon_vst1:
2381   case Intrinsic::arm_neon_vst2:
2382   case Intrinsic::arm_neon_vst3:
2383   case Intrinsic::arm_neon_vst4:
2384   case Intrinsic::arm_neon_vst2lane:
2385   case Intrinsic::arm_neon_vst3lane:
2386   case Intrinsic::arm_neon_vst4lane: {
2387     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2388                                  CI->arg_operands().end());
2389     NewCall = Builder.CreateCall(NewFn, Args);
2390     break;
2391   }
2392 
2393   case Intrinsic::bitreverse:
2394     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
2395     break;
2396 
2397   case Intrinsic::ctlz:
2398   case Intrinsic::cttz:
2399     assert(CI->getNumArgOperands() == 1 &&
2400            "Mismatch between function args and call args");
2401     NewCall =
2402         Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
2403     break;
2404 
2405   case Intrinsic::objectsize: {
2406     Value *NullIsUnknownSize = CI->getNumArgOperands() == 2
2407                                    ? Builder.getFalse()
2408                                    : CI->getArgOperand(2);
2409     NewCall = Builder.CreateCall(
2410         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize});
2411     break;
2412   }
2413 
2414   case Intrinsic::ctpop:
2415     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
2416     break;
2417 
2418   case Intrinsic::convert_from_fp16:
2419     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
2420     break;
2421 
2422   case Intrinsic::dbg_value:
2423     // Upgrade from the old version that had an extra offset argument.
2424     assert(CI->getNumArgOperands() == 4);
2425     // Drop nonzero offsets instead of attempting to upgrade them.
2426     if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
2427       if (Offset->isZeroValue()) {
2428         NewCall = Builder.CreateCall(
2429             NewFn,
2430             {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
2431         break;
2432       }
2433     CI->eraseFromParent();
2434     return;
2435 
2436   case Intrinsic::x86_xop_vfrcz_ss:
2437   case Intrinsic::x86_xop_vfrcz_sd:
2438     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
2439     break;
2440 
2441   case Intrinsic::x86_xop_vpermil2pd:
2442   case Intrinsic::x86_xop_vpermil2ps:
2443   case Intrinsic::x86_xop_vpermil2pd_256:
2444   case Intrinsic::x86_xop_vpermil2ps_256: {
2445     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2446                                  CI->arg_operands().end());
2447     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
2448     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
2449     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
2450     NewCall = Builder.CreateCall(NewFn, Args);
2451     break;
2452   }
2453 
2454   case Intrinsic::x86_sse41_ptestc:
2455   case Intrinsic::x86_sse41_ptestz:
2456   case Intrinsic::x86_sse41_ptestnzc: {
2457     // The arguments for these intrinsics used to be v4f32, and changed
2458     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
2459     // So, the only thing required is a bitcast for both arguments.
2460     // First, check the arguments have the old type.
2461     Value *Arg0 = CI->getArgOperand(0);
2462     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
2463       return;
2464 
2465     // Old intrinsic, add bitcasts
2466     Value *Arg1 = CI->getArgOperand(1);
2467 
2468     Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
2469 
2470     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
2471     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
2472 
2473     NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
2474     break;
2475   }
2476 
2477   case Intrinsic::x86_sse41_insertps:
2478   case Intrinsic::x86_sse41_dppd:
2479   case Intrinsic::x86_sse41_dpps:
2480   case Intrinsic::x86_sse41_mpsadbw:
2481   case Intrinsic::x86_avx_dp_ps_256:
2482   case Intrinsic::x86_avx2_mpsadbw: {
2483     // Need to truncate the last argument from i32 to i8 -- this argument models
2484     // an inherently 8-bit immediate operand to these x86 instructions.
2485     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2486                                  CI->arg_operands().end());
2487 
2488     // Replace the last argument with a trunc.
2489     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
2490     NewCall = Builder.CreateCall(NewFn, Args);
2491     break;
2492   }
2493 
2494   case Intrinsic::x86_avx512_mask_cmp_pd_128:
2495   case Intrinsic::x86_avx512_mask_cmp_pd_256:
2496   case Intrinsic::x86_avx512_mask_cmp_pd_512:
2497   case Intrinsic::x86_avx512_mask_cmp_ps_128:
2498   case Intrinsic::x86_avx512_mask_cmp_ps_256:
2499   case Intrinsic::x86_avx512_mask_cmp_ps_512: {
2500     SmallVector<Value *, 4> Args;
2501     Args.push_back(CI->getArgOperand(0));
2502     Args.push_back(CI->getArgOperand(1));
2503     Args.push_back(CI->getArgOperand(2));
2504     if (CI->getNumArgOperands() == 5)
2505       Args.push_back(CI->getArgOperand(4));
2506 
2507     NewCall = Builder.CreateCall(NewFn, Args);
2508     unsigned NumElts = Args[0]->getType()->getVectorNumElements();
2509     Value *Res = ApplyX86MaskOn1BitsVec(Builder, NewCall, CI->getArgOperand(3),
2510                                         NumElts);
2511 
2512     std::string Name = CI->getName();
2513     if (!Name.empty()) {
2514       CI->setName(Name + ".old");
2515       NewCall->setName(Name);
2516     }
2517     CI->replaceAllUsesWith(Res);
2518     CI->eraseFromParent();
2519     return;
2520   }
2521 
2522   case Intrinsic::thread_pointer: {
2523     NewCall = Builder.CreateCall(NewFn, {});
2524     break;
2525   }
2526 
2527   case Intrinsic::invariant_start:
2528   case Intrinsic::invariant_end:
2529   case Intrinsic::masked_load:
2530   case Intrinsic::masked_store:
2531   case Intrinsic::masked_gather:
2532   case Intrinsic::masked_scatter: {
2533     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2534                                  CI->arg_operands().end());
2535     NewCall = Builder.CreateCall(NewFn, Args);
2536     break;
2537   }
2538 
2539   case Intrinsic::memcpy:
2540   case Intrinsic::memmove:
2541   case Intrinsic::memset: {
2542     // We have to make sure that the call signature is what we're expecting.
2543     // We only want to change the old signatures by removing the alignment arg:
2544     //  @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
2545     //    -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
2546     //  @llvm.memset...(i8*, i8, i[32|64], i32, i1)
2547     //    -> @llvm.memset...(i8*, i8, i[32|64], i1)
2548     // Note: i8*'s in the above can be any pointer type
2549     if (CI->getNumArgOperands() != 5) {
2550       DefaultCase();
2551       return;
2552     }
2553     // Remove alignment argument (3), and add alignment attributes to the
2554     // dest/src pointers.
2555     Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
2556                       CI->getArgOperand(2), CI->getArgOperand(4)};
2557     NewCall = Builder.CreateCall(NewFn, Args);
2558     auto *MemCI = cast<MemIntrinsic>(NewCall);
2559     // All mem intrinsics support dest alignment.
2560     const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
2561     MemCI->setDestAlignment(Align->getZExtValue());
2562     // Memcpy/Memmove also support source alignment.
2563     if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
2564       MTI->setSourceAlignment(Align->getZExtValue());
2565     break;
2566   }
2567   }
2568   assert(NewCall && "Should have either set this variable or returned through "
2569                     "the default case");
2570   std::string Name = CI->getName();
2571   if (!Name.empty()) {
2572     CI->setName(Name + ".old");
2573     NewCall->setName(Name);
2574   }
2575   CI->replaceAllUsesWith(NewCall);
2576   CI->eraseFromParent();
2577 }
2578 
2579 void llvm::UpgradeCallsToIntrinsic(Function *F) {
2580   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
2581 
2582   // Check if this function should be upgraded and get the replacement function
2583   // if there is one.
2584   Function *NewFn;
2585   if (UpgradeIntrinsicFunction(F, NewFn)) {
2586     // Replace all users of the old function with the new function or new
2587     // instructions. This is not a range loop because the call is deleted.
2588     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
2589       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
2590         UpgradeIntrinsicCall(CI, NewFn);
2591 
2592     // Remove old function, no longer used, from the module.
2593     F->eraseFromParent();
2594   }
2595 }
2596 
2597 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
2598   // Check if the tag uses struct-path aware TBAA format.
2599   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
2600     return &MD;
2601 
2602   auto &Context = MD.getContext();
2603   if (MD.getNumOperands() == 3) {
2604     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
2605     MDNode *ScalarType = MDNode::get(Context, Elts);
2606     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
2607     Metadata *Elts2[] = {ScalarType, ScalarType,
2608                          ConstantAsMetadata::get(
2609                              Constant::getNullValue(Type::getInt64Ty(Context))),
2610                          MD.getOperand(2)};
2611     return MDNode::get(Context, Elts2);
2612   }
2613   // Create a MDNode <MD, MD, offset 0>
2614   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
2615                                     Type::getInt64Ty(Context)))};
2616   return MDNode::get(Context, Elts);
2617 }
2618 
2619 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
2620                                       Instruction *&Temp) {
2621   if (Opc != Instruction::BitCast)
2622     return nullptr;
2623 
2624   Temp = nullptr;
2625   Type *SrcTy = V->getType();
2626   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
2627       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
2628     LLVMContext &Context = V->getContext();
2629 
2630     // We have no information about target data layout, so we assume that
2631     // the maximum pointer size is 64bit.
2632     Type *MidTy = Type::getInt64Ty(Context);
2633     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
2634 
2635     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
2636   }
2637 
2638   return nullptr;
2639 }
2640 
2641 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
2642   if (Opc != Instruction::BitCast)
2643     return nullptr;
2644 
2645   Type *SrcTy = C->getType();
2646   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
2647       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
2648     LLVMContext &Context = C->getContext();
2649 
2650     // We have no information about target data layout, so we assume that
2651     // the maximum pointer size is 64bit.
2652     Type *MidTy = Type::getInt64Ty(Context);
2653 
2654     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
2655                                      DestTy);
2656   }
2657 
2658   return nullptr;
2659 }
2660 
2661 /// Check the debug info version number, if it is out-dated, drop the debug
2662 /// info. Return true if module is modified.
2663 bool llvm::UpgradeDebugInfo(Module &M) {
2664   unsigned Version = getDebugMetadataVersionFromModule(M);
2665   if (Version == DEBUG_METADATA_VERSION) {
2666     bool BrokenDebugInfo = false;
2667     if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
2668       report_fatal_error("Broken module found, compilation aborted!");
2669     if (!BrokenDebugInfo)
2670       // Everything is ok.
2671       return false;
2672     else {
2673       // Diagnose malformed debug info.
2674       DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
2675       M.getContext().diagnose(Diag);
2676     }
2677   }
2678   bool Modified = StripDebugInfo(M);
2679   if (Modified && Version != DEBUG_METADATA_VERSION) {
2680     // Diagnose a version mismatch.
2681     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
2682     M.getContext().diagnose(DiagVersion);
2683   }
2684   return Modified;
2685 }
2686 
2687 bool llvm::UpgradeRetainReleaseMarker(Module &M) {
2688   bool Changed = false;
2689   NamedMDNode *ModRetainReleaseMarker =
2690       M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker");
2691   if (ModRetainReleaseMarker) {
2692     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
2693     if (Op) {
2694       MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
2695       if (ID) {
2696         SmallVector<StringRef, 4> ValueComp;
2697         ID->getString().split(ValueComp, "#");
2698         if (ValueComp.size() == 2) {
2699           std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
2700           Metadata *Ops[1] = {MDString::get(M.getContext(), NewValue)};
2701           ModRetainReleaseMarker->setOperand(0,
2702                                              MDNode::get(M.getContext(), Ops));
2703           Changed = true;
2704         }
2705       }
2706     }
2707   }
2708   return Changed;
2709 }
2710 
2711 bool llvm::UpgradeModuleFlags(Module &M) {
2712   NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
2713   if (!ModFlags)
2714     return false;
2715 
2716   bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
2717   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
2718     MDNode *Op = ModFlags->getOperand(I);
2719     if (Op->getNumOperands() != 3)
2720       continue;
2721     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
2722     if (!ID)
2723       continue;
2724     if (ID->getString() == "Objective-C Image Info Version")
2725       HasObjCFlag = true;
2726     if (ID->getString() == "Objective-C Class Properties")
2727       HasClassProperties = true;
2728     // Upgrade PIC/PIE Module Flags. The module flag behavior for these two
2729     // field was Error and now they are Max.
2730     if (ID->getString() == "PIC Level" || ID->getString() == "PIE Level") {
2731       if (auto *Behavior =
2732               mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
2733         if (Behavior->getLimitedValue() == Module::Error) {
2734           Type *Int32Ty = Type::getInt32Ty(M.getContext());
2735           Metadata *Ops[3] = {
2736               ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Max)),
2737               MDString::get(M.getContext(), ID->getString()),
2738               Op->getOperand(2)};
2739           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
2740           Changed = true;
2741         }
2742       }
2743     }
2744     // Upgrade Objective-C Image Info Section. Removed the whitespce in the
2745     // section name so that llvm-lto will not complain about mismatching
2746     // module flags that is functionally the same.
2747     if (ID->getString() == "Objective-C Image Info Section") {
2748       if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
2749         SmallVector<StringRef, 4> ValueComp;
2750         Value->getString().split(ValueComp, " ");
2751         if (ValueComp.size() != 1) {
2752           std::string NewValue;
2753           for (auto &S : ValueComp)
2754             NewValue += S.str();
2755           Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
2756                               MDString::get(M.getContext(), NewValue)};
2757           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
2758           Changed = true;
2759         }
2760       }
2761     }
2762   }
2763 
2764   // "Objective-C Class Properties" is recently added for Objective-C. We
2765   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
2766   // flag of value 0, so we can correclty downgrade this flag when trying to
2767   // link an ObjC bitcode without this module flag with an ObjC bitcode with
2768   // this module flag.
2769   if (HasObjCFlag && !HasClassProperties) {
2770     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
2771                     (uint32_t)0);
2772     Changed = true;
2773   }
2774 
2775   return Changed;
2776 }
2777 
2778 void llvm::UpgradeSectionAttributes(Module &M) {
2779   auto TrimSpaces = [](StringRef Section) -> std::string {
2780     SmallVector<StringRef, 5> Components;
2781     Section.split(Components, ',');
2782 
2783     SmallString<32> Buffer;
2784     raw_svector_ostream OS(Buffer);
2785 
2786     for (auto Component : Components)
2787       OS << ',' << Component.trim();
2788 
2789     return OS.str().substr(1);
2790   };
2791 
2792   for (auto &GV : M.globals()) {
2793     if (!GV.hasSection())
2794       continue;
2795 
2796     StringRef Section = GV.getSection();
2797 
2798     if (!Section.startswith("__DATA, __objc_catlist"))
2799       continue;
2800 
2801     // __DATA, __objc_catlist, regular, no_dead_strip
2802     // __DATA,__objc_catlist,regular,no_dead_strip
2803     GV.setSection(TrimSpaces(Section));
2804   }
2805 }
2806 
2807 static bool isOldLoopArgument(Metadata *MD) {
2808   auto *T = dyn_cast_or_null<MDTuple>(MD);
2809   if (!T)
2810     return false;
2811   if (T->getNumOperands() < 1)
2812     return false;
2813   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
2814   if (!S)
2815     return false;
2816   return S->getString().startswith("llvm.vectorizer.");
2817 }
2818 
2819 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
2820   StringRef OldPrefix = "llvm.vectorizer.";
2821   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
2822 
2823   if (OldTag == "llvm.vectorizer.unroll")
2824     return MDString::get(C, "llvm.loop.interleave.count");
2825 
2826   return MDString::get(
2827       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
2828              .str());
2829 }
2830 
2831 static Metadata *upgradeLoopArgument(Metadata *MD) {
2832   auto *T = dyn_cast_or_null<MDTuple>(MD);
2833   if (!T)
2834     return MD;
2835   if (T->getNumOperands() < 1)
2836     return MD;
2837   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
2838   if (!OldTag)
2839     return MD;
2840   if (!OldTag->getString().startswith("llvm.vectorizer."))
2841     return MD;
2842 
2843   // This has an old tag.  Upgrade it.
2844   SmallVector<Metadata *, 8> Ops;
2845   Ops.reserve(T->getNumOperands());
2846   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
2847   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
2848     Ops.push_back(T->getOperand(I));
2849 
2850   return MDTuple::get(T->getContext(), Ops);
2851 }
2852 
2853 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
2854   auto *T = dyn_cast<MDTuple>(&N);
2855   if (!T)
2856     return &N;
2857 
2858   if (none_of(T->operands(), isOldLoopArgument))
2859     return &N;
2860 
2861   SmallVector<Metadata *, 8> Ops;
2862   Ops.reserve(T->getNumOperands());
2863   for (Metadata *MD : T->operands())
2864     Ops.push_back(upgradeLoopArgument(MD));
2865 
2866   return MDTuple::get(T->getContext(), Ops);
2867 }
2868